-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgrid.js
More file actions
84 lines (74 loc) · 1.94 KB
/
Copy pathgrid.js
File metadata and controls
84 lines (74 loc) · 1.94 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
const Square = Object.freeze({
Empty: 0,
SnakeHead: 1,
SnakeBody: 2,
Food: 3,
});
class Grid {
constructor(size, width, height) {
this.width = width
this.height = height
this.square_size = size
this.width_in_squares = int(width / size)
this.height_in_squares = int(height / size)
// make the grid
this.grid = new Array(this.width_in_squares)
for (let i = 0; i < this.height_in_squares; i++) {
this.grid[i] = new Array(this.height_in_squares).fill(Square.Empty)
}
}
show() {
stroke(100)
// draw vert bars
for (let i = 1; i < this.width_in_squares; i++) {
let x = i * this.square_size
line(x, 0, x, height);
}
// draw vert bars
for (let j = 1; j < this.height_in_squares; j++) {
let y = j * this.square_size
line(0, y, width, y);
}
// draw squares
for (let i = 0; i < this.width_in_squares; i++) {
for (let j = 0; j < this.height_in_squares; j++) {
let square = this.grid[i][j]
let x = i * this.square_size
let y = j * this.square_size
let [r, g, b] = squareToColor(square);
fill(r, g, b);
rect(x, y, this.square_size, this.square_size)
}
}
}
clear_snake_from_grid() {
for (let i = 0; i < this.width_in_squares; i++) {
for (let j = 0; j < this.height_in_squares; j++) {
let square = this.grid[i][j]
if (square == Square.SnakeHead || square == Square.SnakeBody) {
this.grid[i][j] = Square.Empty
}
}
}
}
is_out_of_bounds(x, y) {
return x < 0
|| y < 0
|| x >= this.width_in_squares
|| y >= this.height_in_squares
}
}
function squareToColor(square) {
switch (square) {
case Square.Empty:
return [0, 0, 0];
case Square.SnakeHead:
return [255, 0, 0];
case Square.SnakeBody:
return [200, 200, 200];
case Square.Food:
return [0, 255, 0];
default:
return [0, 0, 0];
}
}