From a8928b64ae37cc43c51f084129a9d5c54d4ac3aa Mon Sep 17 00:00:00 2001 From: zm343 <2639-zm343@users.noreply.gitlab.cci.drexel.edu> Date: Sun, 18 Aug 2024 00:16:47 +0000 Subject: [PATCH] Fix movement --- src/game/game.js | 46 ++++++++++++++++++++++++---------------------- 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/src/game/game.js b/src/game/game.js index 4845186..4210b6e 100644 --- a/src/game/game.js +++ b/src/game/game.js @@ -68,18 +68,23 @@ module.exports = { if (gameBoard[y][x].type === cellTypes.EMPTY) { gameBoard[y][x].type = cellTypes.PLAYERHEAD; gameBoard[y][x].pid = pid; - gameBoard[y][x].direction = 0; - - let y2 = y - 1; - if (y2 >= 0 && gameBoard[y2][x].type === cellTypes.EMPTY) { - gameBoard[y2][x].type = cellTypes.PLAYERBODY; - gameBoard[y2][x].pid = pid; - gameBoard[y2][x].direction = 0; - gameBoard[y][x].next = gameBoard[y2][x]; + + let bodyPlaced = false; + + if (y - 1 >= 0 && gameBoard[y - 1][x].type === cellTypes.EMPTY) { + // Place body segment + gameBoard[y - 1][x] = createCell(x, y - 1, cellTypes.PLAYERBODY); + gameBoard[y - 1][x].pid = pid; + gameBoard[y][x].next = gameBoard[y - 1][x]; + bodyPlaced = true; } - placedCell = true; + if (bodyPlaced) { + placedCell = true; + } else { + gameBoard[y][x] = createCell(x, y, cellTypes.EMPTY); } } + } //console.log(gameBoard); return gameBoard; }, @@ -94,6 +99,8 @@ module.exports = { let oldY = cell.y; let newX = oldX; let newY = oldY; + + let tempVar = cell.direction; //New position based on direction if (cell.direction === 0) { @@ -118,17 +125,15 @@ module.exports = { newY < gameBoard.length ) { //Snake head to new position by updating cell object - gameBoard[newY][newX] = { - ...cell, - x: newX, - y: newY, - }; + let newHeadCell = createCell(newX, newY, cellTypes.PLAYERHEAD); + newHeadCell.pid = cell.pid; + gameBoard[newY][newX] = newHeadCell; + + newHeadCell.direction = tempVar; + gameBoard[newY][newX] = newHeadCell; //Remove previous head position - gameBoard[oldY][oldX].type = cellTypes.EMPTY; - gameBoard[oldY][oldX].pid = 0; - gameBoard[oldY][oldX].direction = 0; - gameBoard[oldY][oldX].next = null; + gameBoard[oldY][oldX] = createCell(oldX, oldY, cellTypes.EMPTY); //Snake body to previous locations let currentBody = gameBoard[newY][newX].next; @@ -149,10 +154,7 @@ module.exports = { } //Remove previous body position - gameBoard[oldY][oldX].type = cellTypes.EMPTY; - gameBoard[oldY][oldX].pid = 0; - gameBoard[oldY][oldX].direction = 0; - gameBoard[oldY][oldX].next = null; + gameBoard[oldY][oldX] = createCell(oldX, oldY, cellTypes.EMPTY); console.log(gameBoard); return gameBoard; -- GitLab