-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSnakeGameHTML.html
117 lines (105 loc) · 2.75 KB
/
SnakeGameHTML.html
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
111
112
113
114
115
116
117
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Snake Game</title>
<style>
canvas {
border: 1px solid #ccc;
background-color: #eee;
margin: 0 auto;
display: block;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
// Constants
const WIDTH = 20;
const HEIGHT = 20;
const CELL_SIZE = 20;
const FPS = 10;
const SNAKE_COLOR = '#2ecc71';
const FOOD_COLOR = '#e74c3c';
const BACKGROUND_COLOR = '#fff';
// Initialize canvas and context
let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');
// Initialize game variables
let score = 0;
let snake = [{x: 10, y: 10}];
let food = {x: 5, y: 5};
let direction = 'right';
// Move the snake
function moveSnake() {
let head = {x: snake[0].x, y: snake[0].y};
if (direction === 'up') head.y -= 1;
if (direction === 'down') head.y += 1;
if (direction === 'left') head.x -= 1;
if (direction === 'right') head.x += 1;
snake.unshift(head);
if (head.x === food.x && head.y === food.y) {
score += 10;
generateFood();
} else {
snake.pop();
}
}
// Draw the snake
function drawSnake() {
ctx.fillStyle = SNAKE_COLOR;
snake.forEach(function(segment) {
ctx.fillRect(segment.x * CELL_SIZE, segment.y * CELL_SIZE, CELL_SIZE, CELL_SIZE);
});
}
// Generate a new piece of food
function generateFood() {
let newFood = {
x: Math.floor(Math.random() * WIDTH),
y: Math.floor(Math.random() * HEIGHT)
};
food = newFood;
}
// Draw the food
function drawFood() {
ctx.fillStyle = FOOD_COLOR;
ctx.fillRect(food.x * CELL_SIZE, food.y * CELL_SIZE, CELL_SIZE, CELL_SIZE);
}
// Update the game
function update() {
moveSnake();
draw();
}
// Draw the game
function draw() {
// Clear the canvas
ctx.fillStyle = BACKGROUND_COLOR;
ctx.fillRect(0, 0, canvas.width, canvas.height);
drawSnake();
drawFood();
// Draw the score
ctx.fillStyle = '#000';
ctx.font = '16px Arial';
ctx.fillText('Score: ' + score, 10, canvas.height - 10);
}
// Handle key presses
document.addEventListener('keydown', function(event) {
if (event.code === 'ArrowUp' && direction !== 'down') {
direction = 'up';
}
if (event.code === 'ArrowDown' && direction !== 'up') {
direction = 'down';
}
if (event.code === 'ArrowLeft' && direction !== 'right') {
direction = 'left';
}
if (event.code === 'ArrowRight' && direction !== 'left') {
direction = 'right';
}
});
// Start the game loop
setInterval(update, 1000 / FPS);
</script>
</body>
</html>