forked from benspector3/snake
-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.js
262 lines (199 loc) · 7.27 KB
/
index.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
/* global $, sessionStorage*/
////////////////////////////////////////////////////////////////////////////////
///////////////////////// VARIABLE DECLARATIONS ////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// HTML jQuery Objects
var board = $("#board");
var scoreElement = $("#score");
var highScoreElement = $("#highScore");
// TODO 4a: Create the snake, apple and score variables
// Game Variables
// Constant Variables
var ROWS = 20;
var COLUMNS = 20;
var SQUARE_SIZE = 20;
var KEY = {
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
};
// interval variable required for stopping the update function when the game ends
var updateInterval;
// variable to keep track of the key (keycode) last pressed by the user
var activeKey;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////// GAME SETUP //////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// TODO: turn on keyboard inputs
$("body").on("keydown", handleKeyDown);
// start the game
init();
function init() {
// TODO 4c-2: initialize the snake
// TODO 4b-2: initialize the apple
// TODO 5a: Initialize the interval
}
////////////////////////////////////////////////////////////////////////////////
///////////////////////// PROGRAM FUNCTIONS ////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/*
* On each update tick update each bubble's position and check for
* collisions with the walls.
*/
function update() {
// TODO 5b: Fill in the update function's code block
}
function checkForNewDirection(event) {
/*
TODO 6b: Update snake.head.direction based on the value of activeKey.
BONUS: Only allow direction changes to take place if the new direction is
perpendicular to the current direction
*/
if (activeKey === KEY.LEFT) {
snake.head.direction = "left";
}
// FILL IN THE REST
// console.log(snake.head.direction); // uncomment me!
}
function moveSnake() {
/*
TODO 11: Move each part of the snake's body such that it's body follows the head.
HINT: To complete this TODO we must figure out the next direction, row, and
column for each snakeSquare in the snake's body. The parts of the snake are
stored in the Array snake.body and each part knows knows its current
column/row properties.
*/
//Before moving the head, check for a new direction from the keyboard input
checkForNewDirection();
/*
TODO 7: determine the next row and column for the snake's head
HINT: The snake's head will need to move forward 1 square based on the value
of snake.head.direction which may be one of "left", "right", "up", or "down"
*/
}
function hasHitWall() {
/*
TODO 8: Should return true if the snake's head has collided with the four walls of the
board, false otherwise.
HINT: What will the row and column of the snake's head be if this were the case?
*/
return false;
}
function hasCollidedWithApple() {
/*
TODO 9: Should return true if the snake's head has collided with the apple,
false otherwise
HINT: Both the apple and the snake's head are aware of their own row and column
*/
return false;
}
function handleAppleCollision() {
// increase the score and update the score DOM element
score++;
scoreElement.text("Score: " + score);
// Remove existing Apple and create a new one
apple.element.remove();
makeApple();
/*
TODO 10: determine the location of the next snakeSquare based on the .row,
.column and .direction properties of the snake.tail snakeSquare
HINT: snake.tail.direction will be either "left", "right", "up", or "down".
If the tail is moving "left", place the next snakeSquare to its right.
If the tail is moving "down", place the next snakeSquare above it.
etc...
*/
var row = 0;
var column = 0;
// code to determine the row and column of the snakeSquare to add to the snake
makeSnakeSquare(row, column);
}
function hasCollidedWithSnake() {
/*
TODO 12: Should return true if the snake's head has collided with any part of the
snake's body.
HINT: Each part of the snake's body is stored in the snake.body Array. The
head and each part of the snake's body also knows its own row and column.
*/
return false;
}
function endGame() {
// stop update function from running
clearInterval(updateInterval);
// clear board of all elements
board.empty();
// update the highScoreElement to display the highScore
highScoreElement.text("High Score: " + calculateHighScore());
scoreElement.text("Score: 0");
score = 0;
// restart the game after 500 ms
setTimeout(init, 500);
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////// HELPER FUNCTIONS ////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/* Create an HTML element for the apple using jQuery. Then find a random
* position on the board that is not occupied and position the apple there.
*/
function makeApple() {
// TODO 4b-1: Fill in the makeApple() code block
}
/* Create an HTML element for a snakeSquare using jQuery. Then, given a row and
* column on the board, position it on the screen. Finally, add the new
* snakeSquare to the snake.body Array and set a new tail.
*/
function makeSnakeSquare(row, column) {
// TODO 4c-1: Fill in this function's code block
}
/*
event.which returns the keycode of the key that is pressed when the
keydown event occurs
The KEY Object creates a map for the Arrow Keys to their keycode:
KEY.LEFT = 37
KEY.UP = 38
KEY.RIGHT = 39
KEY.DOWN = 40
*/
function handleKeyDown(event) {
// TODO 6a: make the handleKeyDown function register which key is pressed
}
/* Given a gameSquare (which may be a snakeSquare or the apple), position
* the gameSquare on the screen.
*/
function repositionSquare(square) {
var squareElement = square.element;
var row = square.row;
var column = square.column;
var buffer = 20;
// position the square on the screen according to the row and column
squareElement.css("left", column * SQUARE_SIZE + buffer);
squareElement.css("top", row * SQUARE_SIZE + buffer);
}
/* Returns a (row,column) Object that is not occupied by another game component
*/
function getRandomAvailablePosition() {
var spaceIsAvailable;
var randomPosition = {};
/* Generate random positions until one is found that doesn't overlap with the snake */
while (!spaceIsAvailable) {
randomPosition.column = Math.floor(Math.random() * COLUMNS);
randomPosition.row = Math.floor(Math.random() * ROWS);
spaceIsAvailable = true;
/*
TODO 13: After generating the random position determine if that position is
not occupied by a snakeSquare in the snake's body. If it is then set
spaceIsAvailable to false so that a new position is generated.
*/
}
return randomPosition;
}
function calculateHighScore() {
// retrieve the high score from session storage if it exists, or set it to 0
var highScore = sessionStorage.getItem("highScore") || 0;
if (score > highScore) {
sessionStorage.setItem("highScore", score);
highScore = score;
alert("New High Score!");
}
return highScore;
}