Skip to content

Commit

Permalink
Improve player controlled snake
Browse files Browse the repository at this point in the history
  • Loading branch information
Dolvur committed Mar 12, 2024
1 parent c60faa3 commit 77c26a0
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 8 deletions.
18 changes: 11 additions & 7 deletions src/playerApi.ts → src/playerBot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,8 @@ export function simpleClient(
ws.onclose = handleClose;
ws.onerror = (error: any) => console.error("PLAYER: Error:", error);

let currentDirection = Direction.Up;
let directionQueue: Direction[] = [Direction.Up];
let lastDirection = Direction.Up;

// event listener to change the direction of the player
document.addEventListener("keydown", handleKeyDown);
Expand All @@ -96,22 +97,22 @@ export function simpleClient(
switch (event.key) {
case "ArrowLeft":
case "a":
currentDirection = Direction.Left;
directionQueue.push(Direction.Left);
break;
case "ArrowUp":
case "w":
currentDirection = Direction.Up;
directionQueue.push(Direction.Up);
break;
case "ArrowRight":
case "d":
currentDirection = Direction.Right;
directionQueue.push(Direction.Right);
break;
case "ArrowDown":
case "s":
currentDirection = Direction.Down;
directionQueue.push(Direction.Down);
break;
}
console.log("current direction: " + currentDirection);
console.log("current direction: " + directionQueue[0]);
}

function sendMessage(message: any) {
Expand Down Expand Up @@ -194,14 +195,17 @@ export function simpleClient(
if (receivingPlayerId === null)
throw new Error("PLAYER: Receiving player id is null");

const direction = directionQueue.shift() || lastDirection;

const moveMessage = createRegisterMoveMessage(
currentDirection,
direction,
receivingPlayerId,
gameId,
gameTick,
);
console.info("PLAYER: Sending move message", moveMessage);
sendMessage(moveMessage);
lastDirection = direction;
}

return close;
Expand Down
2 changes: 1 addition & 1 deletion src/views/ArenaView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import PlayerList from "../components/arena/PlayerList";
import Settings from "../components/arena/Settings";
import { ArenaEnums } from "../constants/ViewEnums";
import { useAppSelector } from "../context/hooks";
import { simpleClient } from "../playerApi";
import { simpleClient } from "../playerBot";

function ArenaView() {
const activeArenaView = useAppSelector(state => state.arena.arenaViewState);
Expand Down

0 comments on commit 77c26a0

Please sign in to comment.