forked from Midway91/HactoberFest2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SNAKE GAME USING JAVASCRIPT ( #213)
110 lines (95 loc) · 3.02 KB
/
SNAKE GAME USING JAVASCRIPT ( #213)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<!DOCTYPE html>
<html>
<head>
<title>Snake Game</title>
<style>
#game-board {
background-color: black;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<canvas id="game-board" width="400" height="400"></canvas>
<script>
// Get the canvas element and its context
const canvas = document.getElementById("game-board");
const ctx = canvas.getContext("2d");
// Define the size of the snake's grid and the size of each cell
const gridSize = 20;
const cellSize = canvas.width / gridSize;
// Initialize the snake
let snake = [
{ x: 10, y: 10 },
{ x: 9, y: 10 },
];
// Initialize the food
let food = { x: 5, y: 5 };
// Initialize the direction
let direction = "right";
// Function to draw a cell
function drawCell(x, y, color) {
ctx.fillStyle = color;
ctx.fillRect(x * cellSize, y * cellSize, cellSize, cellSize);
}
// Function to update the game
function update() {
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Move the snake
let newX = snake[0].x;
let newY = snake[0].y;
if (direction === "right") newX++;
if (direction === "left") newX--;
if (direction === "up") newY--;
if (direction === "down") newY++;
// Check for collision with the food
if (newX === food.x && newY === food.y) {
snake.unshift({ x: food.x, y: food.y });
food = {
x: Math.floor(Math.random() * gridSize),
y: Math.floor(Math.random() * gridSize),
};
} else {
snake.pop();
}
// Check for collision with walls or itself
if (
newX < 0 ||
newX >= gridSize ||
newY < 0 ||
newY >= gridSize ||
snake.some((segment) => segment.x === newX && segment.y === newY)
) {
// Game over
clearInterval(gameLoop);
alert("Game Over!");
location.reload();
}
// Update the snake array
snake.unshift({ x: newX, y: newY });
// Draw the snake
snake.forEach((segment) => drawCell(segment.x, segment.y, "green"));
// Draw the food
drawCell(food.x, food.y, "red");
}
// Handle key presses to change direction
document.addEventListener("keydown", (event) => {
if (event.key === "ArrowRight" && direction !== "left") {
direction = "right";
} else if (event.key === "ArrowLeft" && direction !== "right") {
direction = "left";
} else if (event.key === "ArrowUp" && direction !== "down") {
direction = "up";
} else if (event.key === "ArrowDown" && direction !== "up") {
direction = "down";
}
});
// Start the game loop
const gameLoop = setInterval(update, 100);
</script>
</body>
</html>