From 7bc0d8ae52addd0a8d4d21909678275c2fbc228d Mon Sep 17 00:00:00 2001 From: ys678 <ys678@drexel.edu> Date: Fri, 6 Sep 2024 00:07:49 +0000 Subject: [PATCH] Prevent the snake move opposite --- src/models/WebSocketModel.js | 38 +++++++++++++++++++++--------------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/src/models/WebSocketModel.js b/src/models/WebSocketModel.js index 6a76982..c13e4b4 100644 --- a/src/models/WebSocketModel.js +++ b/src/models/WebSocketModel.js @@ -144,22 +144,28 @@ class WebSocketModel { for (var j = 0; j < gameBoard[0].length; j++) { if (gameBoard[i][j].type === 1 && gameBoard[i][j].pid === pid) { console.log("Updating direction to: " + movement); - switch (movement) { - case "up": - gameBoard[i][j].direction = 0; - break; - case "right": - gameBoard[i][j].direction = 1; - cell.direction = 1; - break; - case "down": - gameBoard[i][j].direction = 2; - break; - case "left": - gameBoard[i][j].direction = 3; - break; - } - console.log("New direction set to: " + gameBoard[i][j].direction); + + let currentDirection = gameBoard[i][j].direction; + let newDirection = currentDirection; + + switch (movement) { + case "up": + if (currentDirection !== 2) newDirection = 0; // Cannot move up if going down + break; + case "right": + if (currentDirection !== 3) newDirection = 1; // Cannot move right if going left + break; + case "down": + if (currentDirection !== 0) newDirection = 2; // Cannot move down if going up + break; + case "left": + if (currentDirection !== 1) newDirection = 3; // Cannot move left if going right + break; + } + if (newDirection !== currentDirection) { + console.log("Updating direction to: " + movement); + gameBoard[i][j].direction = newDirection; + } return; } } -- GitLab