-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
67 lines (64 loc) · 1.98 KB
/
Copy pathscript.js
File metadata and controls
67 lines (64 loc) · 1.98 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
const COLS = 19;
const ROWS = 19;
const CELL = 40;
let snake;
let food;
let score = 0;
let direction = [0, 0];
let scoreDisplay;
function setup() {
createCanvas(COLS * CELL, ROWS * CELL);
frameRate(10);
snake = new Snake(floor(ROWS / 2) * CELL, floor(COLS / 2) * CELL, CELL);
food = new Food(floor(random() * ROWS) * CELL, floor(random() * COLS) * CELL, CELL);
scoreDisplay = createElement('h1', `SCORE : ${score}`);
scoreDisplay.position(width / 2 - 96, height);
scoreDisplay.style('font-family', 'monospace');
scoreDisplay.style('font-size', '3em');
}
function draw() {
background(0);
stroke(120);
fill(0);
snake.direction = direction;
for (let i = 0; i < COLS; i++) {
for (let j = 0; j < ROWS; j++) {
rect(i * CELL, j * CELL, CELL, CELL);
}
}
if (snake.x < 0 || snake.x === width || snake.y < 0 || snake.y === height || snake.check()) {
removeElements();
snake.death(floor(ROWS / 2) * CELL, floor(COLS / 2) * CELL);
direction = [0, 0];
console.log(score);
score = 0;
scoreDisplay = createElement('h1', `SCORE : ${score}`);
scoreDisplay.position(width / 2 - 96, height);
scoreDisplay.style('font-family', 'monospace');
scoreDisplay.style('font-size', '3em');
}
if (snake.eat(food)) {
removeElements();
while (snake.inTail(food.x, food.y)) {
food = new Food(floor(random() * COLS) * CELL, floor(random() * ROWS) * CELL, CELL);
}
score++;
scoreDisplay = createElement('h1', `SCORE : ${score}`);
scoreDisplay.position(width / 2 - 96, height);
scoreDisplay.style('font-family', 'monospace');
scoreDisplay.style('font-size', '3em');
}
food.show();
snake.show();
}
function keyPressed() {
if (keyCode === LEFT_ARROW && snake.direction[0] !== CELL) {
direction = [-CELL, 0];
} else if (keyCode === RIGHT_ARROW && snake.direction[0] !== -CELL) {
direction = [CELL, 0];
} else if (keyCode === UP_ARROW && snake.direction[1] !== CELL) {
direction = [0, -CELL];
} else if (keyCode === DOWN_ARROW && snake.direction[1] !== -CELL) {
direction = [0, CELL];
}
}