-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsketch.js
124 lines (90 loc) · 2.23 KB
/
sketch.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
let width = 600;
let height = 600;
let strokeRatio = 0.06;
let cols = 21;
let rows = 21;
let blockWidth = width/cols;
let blockHeight = height/rows;
let initSnakeLength = 4;
var blocks;
var snake;
let started;
let currentKey = null;
let startTime;
let time = 0;
let time2 = 0;
let cakeImage;
function setup() {
document.getElementById("scoreText").innerText = "";
cakeImage = loadImage("cake.png");
createCanvas(width, height);
background(0);
noSmooth();
textFont("Arial");
textSize(150);
strokeWeight(width/cols*strokeRatio);
blocks = [];
let blockColor = [random(0, 255), random(0, 255), random(0, 255)];
for (let i = 0; i < cols; i++) {
blocks[i] = [];
for (let j = 0; j < rows; j++) {
b = new Block(i*blockWidth, j*blockHeight, blockWidth, blockHeight, j, i, blockColor, [0, 0, 0]);
blocks[i][j] = b;
}
}
shape = [];
for (i = 0; i < initSnakeLength; i++) {
shape[i] = [initSnakeLength-1-i, Math.floor(rows/2)];
}
snakeColor = ((blockColor[0] * 0.299 + blockColor[1] * 0.587 + blockColor[2] * 0.114) > 127) ? [0, 0, 0] : [255, 255, 255];
snake = new Snake(
shape,
[[1, 0], [1, 0], [1, 0], [1, 0]],
blocks,
snakeColor,
snakeColor,
cakeImage
);
startTime = new Date().getTime();
}
function keyPressed() {
currentKey = key;
}
function draw() {
background(0);
if (!started) {
let hovered = (mouseX > width/7 && mouseY > height/4 && mouseX < width/7*6 && mouseY < height/4*3);
if (hovered) {
if (mouseIsPressed || keyCode === 32) {
started = true;
}
fill("#2e2e99");
} else {
fill("#030975");
}
stroke(0);
rect(width/7, height/4, width/7*5, height/2);
textAlign(CENTER, CENTER);
fill(255);
text("PLAY", width/2, height/2+15);
return;
}
time = new Date().getTime() - startTime;
let speed = 1/document.getElementById("speedSlider").value*1000;
document.getElementById("scoreText").innerText = snake.score;
if ((Math.ceil(time/speed)*speed) > (Math.ceil(time2/speed)*speed)) {
if (snake.tick(currentKey) === -1) {
setup();
started = false;
return;
}
currentKey = null;
}
time2 = time;
for (row of blocks) {
for (block of row) {
block.draw();
}
}
snake.draw();
}