-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
167 lines (146 loc) · 4.82 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
// HTML Elements
const board = document.getElementById('board');
const scoreBoard = document.getElementById('scoreBoard');
const startButton = document.getElementById('start');
const gameOverSign = document.getElementById('gameOver');
// Game settings
const boardSize = 10;6
const gameSpeed = 500;
const squareTypes = {
emptySquare: 0,
snakeSquare: 1,
foodSquare: 2
};
const directions = {
ArrowUp: -10,
ArrowDown: 10,
ArrowRight: 1,
ArrowLeft: -1,
};
// Game variables
let snake;
let score;
let direction;
let boardSquares;
let emptySquares;
let moveInterval;
const drawSnake = () => {
snake.forEach( square => drawSquare(square, 'snakeSquare'));
}
// Rellena cada cuadrado del tablero
// @params
// square: posicion del cuadrado,
// type: tipo de cuadrado (emptySquare, snakeSquare, foodSquare)
const drawSquare = (square, type) => {
const [ row, column ] = square.split('');
boardSquares[row][column] = squareTypes[type];
const squareElement = document.getElementById(square);
squareElement.setAttribute('class', `square ${type}`);
if(type === 'emptySquare') {
emptySquares.push(square);
} else {
if(emptySquares.indexOf(square) !== -1) {
emptySquares.splice(emptySquares.indexOf(square), 1);
}
}
}
const moveSnake = () => {
const newSquare = String(
Number(snake[snake.length - 1]) + directions[direction])
.padStart(2, '0');
const [row, column] = newSquare.split('');
// Corrección de la condición de Game Over y límites del tablero
if (newSquare < 0 ||
newSquare > boardSize * boardSize - 1 || // <--- Corregido
(direction === 'ArrowRight' && column == 0) ||
(direction === 'ArrowLeft' && column == 9) ||
boardSquares[row][column] === squareTypes.snakeSquare) {
endGame(); // <--- ¡Aquí faltaba llamar a endGame()!
return; // <--- ¡Y aquí faltaba detener la función!
} else {
snake.push(newSquare);
if (boardSquares[row][column] === squareTypes.foodSquare) {
addFood();
} else {
const emptySquare = snake.shift();
drawSquare(emptySquare, 'emptySquare');
}
drawSnake();
}
};
const addFood = () => {
score++;
updateScore();
createRandomFood();
}
const endGame = () => {
clearInterval(moveInterval); // Detener el movimiento de la serpiente
gameOverSign.style.display = 'block'; // Mostrar el mensaje de Game Over
gameOverSign.classList.add('explode'); // Agregar la clase para la animación
// Reiniciar la animación si es necesario
setTimeout(() => {
gameOverSign.classList.remove('explode'); // Eliminar la clase
void gameOverSign.offsetWidth; // Forzar el reflow
gameOverSign.classList.add('explode'); // Volver a agregar la clase
}, 0);
startButton.disabled = false; // Habilitar el botón de inicio
};
const setDirection = newDirection => {
direction = newDirection;
}
const directionEvent = key => {
switch (key.code) {
case 'ArrowUp':
direction != 'ArrowDown' && setDirection(key.code)
break;
case 'ArrowDown':
direction != 'ArrowUp' && setDirection(key.code)
break;
case 'ArrowLeft':
direction != 'ArrowRight' && setDirection(key.code)
break;
case 'ArrowRight':
direction != 'ArrowLeft' && setDirection(key.code)
break;
}
}
const createRandomFood = () => {
const randomEmptySquare = emptySquares[Math.floor(Math.random() * emptySquares.length)];
drawSquare(randomEmptySquare, 'foodSquare');
}
const updateScore = () => {
scoreBoard.innerText = score;
}
const createBoard = () => {
boardSquares.forEach( (row, rowIndex) => {
row.forEach( (column, columnndex) => {
const squareValue = `${rowIndex}${columnndex}`;
const squareElement = document.createElement('div');
squareElement.setAttribute('class', 'square emptySquare');
squareElement.setAttribute('id', squareValue);
board.appendChild(squareElement);
emptySquares.push(squareValue);
})
})
}
const setGame = () => {
snake = ['00', '01', '02', '03'];
score = snake.length;
direction = 'ArrowRight';
boardSquares = Array.from(Array(boardSize), () => new Array(boardSize).fill(squareTypes.emptySquare));
console.log(boardSquares);
board.innerHTML = '';
emptySquares = [];
createBoard();
}
const startGame = () => {
setGame();
gameOverSign.style.display = 'none';
startButton.disabled = true;
drawSnake();
updateScore();
createRandomFood();
document.addEventListener('keydown', directionEvent);
moveInterval = setInterval( () => moveSnake(), gameSpeed);
}
startButton.addEventListener('click', startGame);