Skip to content
Snippets Groups Projects
Commit 09f0b9b7 authored by ys678's avatar ys678
Browse files

Update game.js for collision & growing features

parent a8928b64
No related branches found
No related tags found
1 merge request!10Update game.js for collision & growing features
...@@ -117,26 +117,44 @@ module.exports = { ...@@ -117,26 +117,44 @@ module.exports = {
newX -= 1; newX -= 1;
} }
//Continue if within bounds // Check for collisions with walls
if ( if (
newX >= 0 && newX < 0 ||
newX < gameBoard[0].length && newX >= gameBoard[0].length ||
newY >= 0 && newY < 0 ||
newY < gameBoard.length newY >= gameBoard.length
) { ) {
console.log(`Player ${cell.pid} has collided with the wall!`);
// Remove the player from the game (indicating death)
return gameBoard.map(row =>
row.map(c => (c.pid === cell.pid ? createCell(c.x, c.y, cellTypes.EMPTY) : c))
);
}
// Handle collision with food
if (gameBoard[newY][newX].type === cellTypes.FOOD) {
console.log(`Player ${cell.pid} has eaten the food!`);
// Add new body segment at the current head's position
let newBodySegment = createCell(oldX, oldY, cellTypes.PLAYERBODY);
newBodySegment.pid = cell.pid;
newBodySegment.next = cell.next;
cell.next = newBodySegment;
// Place new food somewhere else
gameBoard = addFood(gameBoard);
}
// Snake head to new position by updating cell object // Snake head to new position by updating cell object
let newHeadCell = createCell(newX, newY, cellTypes.PLAYERHEAD); let newHeadCell = createCell(newX, newY, cellTypes.PLAYERHEAD);
newHeadCell.pid = cell.pid; newHeadCell.pid = cell.pid;
gameBoard[newY][newX] = newHeadCell;
newHeadCell.direction = tempVar; newHeadCell.direction = tempVar;
newHeadCell.next = cell.next;
gameBoard[newY][newX] = newHeadCell; gameBoard[newY][newX] = newHeadCell;
// Remove previous head position // Remove previous head position
gameBoard[oldY][oldX] = createCell(oldX, oldY, cellTypes.EMPTY); gameBoard[oldY][oldX] = createCell(oldX, oldY, cellTypes.EMPTY);
//Snake body to previous locations // Move the body segments
let currentBody = gameBoard[newY][newX].next; let currentBody = newHeadCell.next;
while (currentBody) { while (currentBody) {
let bodyOldX = currentBody.x; let bodyOldX = currentBody.x;
let bodyOldY = currentBody.y; let bodyOldY = currentBody.y;
...@@ -153,15 +171,16 @@ module.exports = { ...@@ -153,15 +171,16 @@ module.exports = {
currentBody = currentBody.next; currentBody = currentBody.next;
} }
//Remove previous body position // Remove previous body position if it's no longer part of the snake
if (oldX !== newHeadCell.x || oldY !== newHeadCell.y) {
gameBoard[oldY][oldX] = createCell(oldX, oldY, cellTypes.EMPTY); gameBoard[oldY][oldX] = createCell(oldX, oldY, cellTypes.EMPTY);
}
console.log(gameBoard); console.log(gameBoard);
return gameBoard; return gameBoard;
} }
} }
} }
}
return gameBoard; return gameBoard;
}, },
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment