2024-04-22 19:03:07 +02:00
|
|
|
import {makeApiUrl, Scores} from './serverCalls';
|
|
|
|
import {Guid} from './Guid.ts';
|
|
|
|
import Column from './components/Column.tsx';
|
|
|
|
import useWebSocket, {ReadyState} from 'react-use-websocket';
|
|
|
|
import {useEffect, useState} from 'react';
|
2024-04-13 17:56:33 +02:00
|
|
|
|
2024-04-19 13:50:06 +02:00
|
|
|
function ScoreRow({name, value}: {
|
|
|
|
name: string;
|
|
|
|
value?: any;
|
|
|
|
}) {
|
|
|
|
return <tr>
|
|
|
|
<td>{name}</td>
|
|
|
|
<td>{value ?? '?'}</td>
|
|
|
|
</tr>;
|
|
|
|
}
|
|
|
|
|
2024-04-22 19:03:07 +02:00
|
|
|
type Controls = {
|
|
|
|
readonly forward: boolean;
|
|
|
|
readonly backward: boolean;
|
|
|
|
readonly turnLeft: boolean;
|
|
|
|
readonly turnRight: boolean;
|
|
|
|
readonly shoot: boolean;
|
|
|
|
}
|
|
|
|
|
|
|
|
type PlayerInfoMessage = {
|
|
|
|
readonly name: string;
|
|
|
|
readonly scores: Scores;
|
|
|
|
readonly controls: Controls;
|
|
|
|
}
|
|
|
|
|
|
|
|
function controlsString(controls: Controls) {
|
|
|
|
let str = "";
|
|
|
|
if (controls.forward)
|
|
|
|
str += "▲";
|
|
|
|
if (controls.backward)
|
|
|
|
str += "▼";
|
|
|
|
if (controls.turnLeft)
|
|
|
|
str += "◄";
|
|
|
|
if (controls.turnRight)
|
|
|
|
str += "►";
|
|
|
|
if (controls.shoot)
|
|
|
|
str += "•";
|
|
|
|
return str;
|
|
|
|
}
|
|
|
|
|
2024-04-17 23:09:01 +02:00
|
|
|
export default function PlayerInfo({playerId}: { playerId: Guid }) {
|
2024-04-22 19:03:07 +02:00
|
|
|
const [shouldSendMessage, setShouldSendMessage] = useState(true);
|
|
|
|
|
|
|
|
const url = makeApiUrl('/player');
|
|
|
|
url.searchParams.set('id', playerId);
|
|
|
|
|
|
|
|
const {lastJsonMessage, readyState, sendMessage} = useWebSocket<PlayerInfoMessage>(url.toString(), {
|
|
|
|
onMessage: () => setShouldSendMessage(true)
|
2024-04-17 23:09:01 +02:00
|
|
|
});
|
2024-04-13 17:56:33 +02:00
|
|
|
|
2024-04-22 19:03:07 +02:00
|
|
|
useEffect(() => {
|
|
|
|
if (!shouldSendMessage || readyState !== ReadyState.OPEN)
|
|
|
|
return;
|
|
|
|
setShouldSendMessage(false);
|
|
|
|
sendMessage('');
|
|
|
|
}, [readyState, shouldSendMessage]);
|
|
|
|
|
|
|
|
if (!lastJsonMessage)
|
|
|
|
return <></>;
|
|
|
|
|
|
|
|
return <Column className="PlayerInfo">
|
2024-04-13 23:53:09 +02:00
|
|
|
<h3>
|
2024-04-22 19:03:07 +02:00
|
|
|
Playing as {lastJsonMessage.name}
|
2024-04-13 23:53:09 +02:00
|
|
|
</h3>
|
2024-04-22 19:03:07 +02:00
|
|
|
<table>
|
2024-04-14 00:49:39 +02:00
|
|
|
<tbody>
|
2024-04-22 19:03:07 +02:00
|
|
|
<ScoreRow name="controls" value={controlsString(lastJsonMessage.controls)}/>
|
|
|
|
<ScoreRow name="kills" value={lastJsonMessage.scores.kills}/>
|
|
|
|
<ScoreRow name="deaths" value={lastJsonMessage.scores.deaths}/>
|
|
|
|
<ScoreRow name="walls" value={lastJsonMessage.scores.wallsDestroyed}/>
|
2024-04-14 00:49:39 +02:00
|
|
|
</tbody>
|
2024-04-22 19:03:07 +02:00
|
|
|
</table>
|
2024-04-13 23:07:08 +02:00
|
|
|
</Column>;
|
2024-04-13 17:56:33 +02:00
|
|
|
}
|