-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscript.js
245 lines (217 loc) · 5.84 KB
/
script.js
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
// Define HTML elements
const board = document.getElementById('game-board');
const instructionText = document.getElementById('instruction-text');
const logo = document.getElementById('logo');
const score = document.getElementById('score');
const highScoreText = document.getElementById('highScore');
// Define game variables
const gridSize = 20;
let snake = [{ x: 10, y: 10 }];
let food = generateFood();
let highScore = 0;
let direction = 'right';
let gameInterval;
let gameSpeedDelay = 200;
let gameStarted = false;
// Draw game map, snake, food
function draw() {
board.innerHTML = '';
drawSnake();
drawFood();
updateScore();
}
// Draw snake
function drawSnake() {
snake.forEach((segment) => {
const snakeElement = createGameElement('div', 'snake');
setPosition(snakeElement, segment);
board.appendChild(snakeElement);
});
}
// Create a snake or food cube/div
function createGameElement(tag, className) {
const element = document.createElement(tag);
element.className = className;
return element;
}
// Set the position of snake or food
function setPosition(element, position) {
element.style.gridColumn = position.x;
element.style.gridRow = position.y;
}
// Testing draw function
// draw();
// Draw food function
function drawFood() {
if (gameStarted) {
const foodElement = createGameElement('div', 'food');
setPosition(foodElement, food);
board.appendChild(foodElement);
}
}
function move() {
const head = { ...snake[0] };
switch (direction) {
case 'up':
head.y--;
break;
case 'down':
head.y++;
break;
case 'left':
head.x--;
break;
case 'right':
head.x++;
break;
}
snake.unshift(head);
// Check if the snake's head reaches the food
if (head.x === food.x && head.y === food.y) {
generateAndAskQuestion();
increaseSpeed();
} else {
snake.pop();
}
checkCollision();
draw();
}
function generateFood() {
const x = Math.floor(Math.random() * gridSize) + 1;
const y = Math.floor(Math.random() * gridSize) + 1;
// Return food position without asking question
return { x, y };
}
function generateAndAskQuestion() {
// Generate random arithmetic operation (0: addition, 1: subtraction, 2: multiplication, 3: division)
const operationIndex = Math.floor(Math.random() * 4);
let num1, num2, answer, question;
// Generate random numbers for the math question
switch (operationIndex) {
case 0: // Addition
num1 = Math.floor(Math.random() * 10) + 1;
num2 = Math.floor(Math.random() * 10) + 1;
answer = num1 + num2;
question = `${num1} + ${num2}`;
break;
case 1: // Subtraction
num1 = Math.floor(Math.random() * 10) + 1;
num2 = Math.floor(Math.random() * 10) + 1;
// Ensure num1 is greater than or equal to num2 for positive result
if (num1 < num2) {
[num1, num2] = [num2, num1];
}
answer = num1 - num2;
question = `${num1} - ${num2}`;
break;
case 2: // Multiplication
num1 = Math.floor(Math.random() * 5) + 1;
num2 = Math.floor(Math.random() * 5) + 1;
answer = num1 * num2;
question = `${num1} * ${num2}`;
break;
case 3: // Division
// Generate divisor and dividend such that the result is an integer
num2 = Math.floor(Math.random() * 5) + 1;
answer = Math.floor(Math.random() * 5) + 1;
num1 = num2 * answer;
question = `${num1} / ${num2}`;
break;
}
// Ask the question to the player
const userAnswer = prompt(`What is ${question}?`);
// Check if the answer is correct
if (parseInt(userAnswer) === answer) {
alert('Correct!');
food = generateFood(); // Generate new food position
} else {
alert(`Incorrect! The correct answer is ${answer}. Game Over!`);
resetGame();
}
}
// Start game function
function startGame() {
gameStarted = true; // Keep track of a running game
instructionText.style.display = 'none';
logo.style.display = 'none';
gameInterval = setInterval(() => {
move();
checkCollision();
draw();
}, gameSpeedDelay);
}
// Keypress event listener
function handleKeyPress(event) {
if (
(!gameStarted && event.code === 'Space') ||
(!gameStarted && event.key === ' ')
) {
startGame();
} else {
switch (event.key) {
case 'ArrowUp':
direction = 'up';
break;
case 'ArrowDown':
direction = 'down';
break;
case 'ArrowLeft':
direction = 'left';
break;
case 'ArrowRight':
direction = 'right';
break;
}
}
}
document.addEventListener('keydown', handleKeyPress);
function increaseSpeed() {
// console.log(gameSpeedDelay);
if (gameSpeedDelay > 150) {
gameSpeedDelay -= 5;
} else if (gameSpeedDelay > 100) {
gameSpeedDelay -= 3;
} else if (gameSpeedDelay > 50) {
gameSpeedDelay -= 2;
} else if (gameSpeedDelay > 25) {
gameSpeedDelay -= 1;
}
}
function checkCollision() {
const head = snake[0];
if (head.x < 1 || head.x > gridSize || head.y < 1 || head.y > gridSize) {
resetGame();
}
for (let i = 1; i < snake.length; i++) {
if (head.x === snake[i].x && head.y === snake[i].y) {
resetGame();
}
}
}
function resetGame() {
updateHighScore();
stopGame();
snake = [{ x: 10, y: 10 }];
food = generateFood();
direction = 'right';
gameSpeedDelay = 200;
updateScore();
}
function updateScore() {
const currentScore = snake.length - 1;
score.textContent = currentScore.toString().padStart(3, '0');
}
function stopGame() {
clearInterval(gameInterval);
gameStarted = false;
instructionText.style.display = 'block';
logo.style.display = 'block';
}
function updateHighScore() {
const currentScore = snake.length - 1;
if (currentScore > highScore) {
highScore = currentScore;
highScoreText.textContent = highScore.toString().padStart(3, '0');
}
highScoreText.style.display = 'block';
}