-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
174 lines (142 loc) · 5.37 KB
/
script.js
File metadata and controls
174 lines (142 loc) · 5.37 KB
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
document.addEventListener('DOMContentLoaded', function () {
const gameArena = document.getElementById('game-arena');
const arenaSize = 600;
const cellSize = 20;
let score = 0; //Score of the game.
let gameStarted = false; //Game Status
let food = {x: 300, y: 200}; // {x : 15*20, y: 10*20} -> cell coordinate -> pixels
let snake = [
{x: 160, y: 200}, {x:140 , y:200}, {x: 120, y: 200}
]; // [HEAD, BODY, BODY, TAIL]
let dx = cellSize; //+20
let dy = 0;
let intervalId;
let gameSpeed = 200;
function drawScoreBoard() {
const scoreBoard = document.getElementById('score-board');
scoreBoard.textContent = `score : ${score}`;
}
function updateFood() {
let newX, newY;
do {
newX = Math.floor(Math.random() * 30) * cellSize;
newY = Math.floor(Math.random() * 30) * cellSize;
} while(snake.some((snakeCell) => { return (snakeCell.x === newX && snakeCell.y === newY)}));
food = {x: newX, y: newY};
}
function updateSnake() {
let newHead = {x: snake[0].x + dx, y: snake[0].y + dy};
snake.unshift(newHead); //Add new-head to the snake array.
//Check collision with food.
if(newHead.x === food.x && newHead.y === food.y) {
score += 10
updateFood();
//Update the speed of the snake
if(gameSpeed > 50) {
clearInterval(intervalId);
gameSpeed -= 10;
gameLoop();
}
} else {
snake.pop(); //Remove the tail.
}
}
function changeDirection(event) {
console.log("Key Pressed.", event);
const isGoingDown = dy === cellSize;
const isGoingUp = dy === -cellSize;
const isGoingRight = dx === cellSize;
const isGoingLeft = dx === -cellSize;
if(event.key === "ArrowUp" && !isGoingDown) {
dx = 0;
dy = -cellSize;
} else if(event.key == "ArrowDown" && !isGoingUp) {
dx = 0;
dy = cellSize;
} else if(event.key == "ArrowLeft" && !isGoingRight) {
dx = -cellSize;
dy = 0;
} else if(event.key == "ArrowRight" && !isGoingLeft) {
dx = cellSize;
dy = 0;
}
}
function drawDiv(x, y, label) {
const divElement = document.createElement('div');
divElement.classList.add(label);
divElement.style.top = `${y}px`;
divElement.style.left = `${x}px`;
return divElement;
}
function drawFoodAndSnake() {
gameArena.innerHTML = ''; //Clear the game-arena
snake.forEach((snakeCell) => {
const snakeElement = drawDiv(snakeCell.x, snakeCell.y, 'snake');
gameArena.appendChild(snakeElement);
})
const foodElement = drawDiv(food.x, food.y, 'food');
gameArena.appendChild(foodElement);
}
function isGameOver() {
//Snake Collision with body check
for(let i=1; i<snake.length; i++) {
if(snake[0].x === snake[i].x && snake[0].y === snake[i].y) {
return true;
}
}
//Wall Collision Check
const hitLeftWall = (snake[0].x < 0); //snake[0] -> head
const hitRightWall = (snake[0].x >= arenaSize - cellSize);
const hitTopWall = (snake[0].y < 0);
const hitBottomWall = (snake[0].y >= arenaSize - cellSize);
return hitLeftWall || hitRightWall || hitTopWall || hitBottomWall;
}
function gameLoop() {
intervalId = setInterval(() => {
if(isGameOver()) {
clearInterval(intervalId);
gameStarted = false;
alert('Game Over' + '\n' + 'Your Score is : ' + score);
let startButton = document.getElementById('start-button');
startButton.style.removeProperty("display");
return;
}
updateSnake();
drawFoodAndSnake();
drawScoreBoard();
}, gameSpeed)
}
function runGame() {
//Resetting all the values again when start Button hit again.
score = 0;
dx = cellSize;
dy = 0;
gameSpeed = 200;
//Whenever the start game button will hit it will bring back the snake and food to its intiale position.
food = {x: 300, y: 200};
snake = [
{x: 160, y: 200}, {x:140 , y:200}, {x: 120, y: 200}
];
if(!gameStarted) {
gameStarted = true;
document.addEventListener('keydown', changeDirection);
// drawFoodAndSnake();
gameLoop();
}
}
function initiateGame() {
const scoreBoard = document.createElement('div');
scoreBoard.id = 'score-board';
document.body.insertBefore(scoreBoard, gameArena); //Insert the score-board before the game-arena.
const startButton = document.createElement('button');
startButton.textContent = "Start Game";
startButton.classList.add('start-button');
startButton.id = 'start-button';
startButton.addEventListener('click', function startGame() {
startButton.style.display = 'none'; //Hide the start Button.
runGame(); //To start the game.
});
document.body.appendChild(startButton); //Append start button to the body.
}
initiateGame();
});