-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
167 lines (128 loc) · 2.36 KB
/
game.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
let s;
let scl = 20;
let food;
let score;
let maxScore = 0;
let PLAYING = 0;
let GAME_OVER = 1;
let gameMode;
let w;
let h;
let lastKey = null;
function setup(){
createCanvas(600, 600);
w = floor(width/scl);
h = floor(height/scl);
s = new Snake();
score = 0;
frameRate(10);
pickLocation();
gameMode = PLAYING;
}
function pickLocation(){
let x = floor(random(w));
let y = floor(random(h));
food = createVector(x, y);
}
function draw() {
scale(scl);
background(51);
if(gameMode == PLAYING){
if(s.eat(food)){
score += 10;
pickLocation();
}
s.move();
s.render();
if(s.death()){
if(score > maxScore){
maxScore = score;
}
gameMode = GAME_OVER;
}
fill(255);
textSize(1);
text("Score: " + score + " - Max: " + maxScore, 1, 1);
noStroke();
fill(255, 0, 100);
rect(food.x, food.y, 1, 1);
}else{
fill(255);
text("GAME OVER", 1, 20);
text("Space to restart", 1, 21);
}
}
function moveUp(){
if(lastKey != "down"){
s.setDir(0, -1);
lastKey = "up";
}else{
lastKey = "down";
}
}
function moveDown(){
if(lastKey != "up"){
s.setDir(0, 1);
lastKey = "down";
}else{
lastKey = "up";
}
}
function moveLeft(){
if(lastKey != "right"){
s.setDir(-1, 0);
lastKey = "left";
}else{
lastKey = "right";
}
}
function moveRight(){
if(lastKey != "left"){
s.setDir(1, 0);
lastKey = "right";
}else{
lastKey = "left";
}
}
function keyPressed(){
if(keyCode === UP_ARROW){
moveUp();
}
if(keyCode === DOWN_ARROW){
moveDown();
}
if(keyCode === LEFT_ARROW){
moveLeft();
}
if(keyCode === RIGHT_ARROW){
moveRight();
}
if(key === ' ' && gameMode == GAME_OVER){
setup();
}
}
function mousePressed(){
let xPos = floor(mouseX/scl);
let yPos = floor(mouseY/scl);
let wQuar = floor(w/4);
let w3Quar = 3 * wQuar;
let hQuar = floor(h/4);
let h3Quar = 3 * hQuar;
console.log("POS", xPos, yPos);
console.log(wQuar, hQuar, h3Quar);
if(gameMode == GAME_OVER){
setup();
}
if(xPos < wQuar && yPos > hQuar && yPos < h3Quar){
moveLeft();
}
if(xPos > w3Quar && yPos > hQuar && yPos < h3Quar){
moveRight();
}
if(yPos < hQuar && xPos > wQuar && xPos < w3Quar){
moveUp();
}
if(yPos > h3Quar && xPos > wQuar && xPos < w3Quar){
moveDown();
}
}