-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnake.py
More file actions
437 lines (415 loc) · 14.2 KB
/
snake.py
File metadata and controls
437 lines (415 loc) · 14.2 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
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
from org.transcrypt.stubs.browser import __pragma__
from com.fabricjs import fabric
__pragma__("alias", "S", "$")
__pragma__("noalias", "clear")
w, h = 500,500
inc = 20
left, right, space = 37, 39, 32
window.onkeydown = lambda event: event.keycode != space
player = apple = obstacle = mongoose = canvas = None
facing = [1, 2, 3, 4]
LEFT = 1
UP = 2
RIGHT = 3
DOWN = 4
class Snake:
def __init__(self):
self.alive = True
self.past = []
self.tail = []
self.coords = []
self.snake_length = 1
self.loc = (5*inc, 5*inc)
self.snake = __new__(fabric.Rect({
'left': self.loc[0],
'top': self.loc[1],
'width': inc,
'height': inc,
'originX': 'left',
'originY': 'top',
'fill': 'green'
}))
self.facing = 3
def update(self):
canvas.remove(self.snake)
for t_box in self.tail:
canvas.remove(t_box)
self.coords = []
self.tail = []
self.past.append(self.loc)
if self.facing == 1:
self.loc = (self.loc[0] - inc, self.loc[1])
elif self.facing == 2:
self.loc = (self.loc[0], self.loc[1] - inc)
elif self.facing == 3:
self.loc = (self.loc[0] + inc, self.loc[1])
else:
self.loc = (self.loc[0], self.loc[1] + inc)
self.snake = __new__(fabric.Rect({
'left': self.loc[0],
'top': self.loc[1],
'width': inc,
'height': inc,
'originX': 'left',
'originY': 'top',
'fill': 'green'
}))
self.coords.append(self.loc)
self.snake.hasControls = False
tail = []
for i in range(self.snake_length-1):
self.tail.append(__new__(fabric.Rect({
'left': self.past[len(self.past) - (i+1)][0],
'top': self.past[len(self.past) - (i+1)][1],
'width': inc,
'height': inc,
'originX': 'left',
'originY': 'top',
'fill': 'green'
})))
self.coords.append(self.past[len(self.past) - (i+1)])
for t_box in self.tail:
canvas.add(t_box)
if t_box.left == self.snake.left and t_box.top == self.snake.top:
alert("You ate yourself! Click OK to continue.")
self.die()
canvas.add(self.snake)
def turn(self, e):
if e.keyCode == 37:
if self.facing == 1:
self.facing = 4
else:
self.facing = facing[facing.index(self.facing)-1]
elif e.keyCode == 39:
if self.facing == 4:
self.facing = 1
else:
self.facing = facing[facing.index(self.facing)+1]
elif e.keyCode == 80:
alert("Game Paused. Click OK to continue.")
def turn_mobile(self, event):
if event.clientX < screen.width/2:
if self.facing == 1:
self.facing = 4
else:
self.facing = facing[facing.index(self.facing)-1]
elif event.clientX > screen.width/2:
if self.facing == 4:
self.facing = 1
else:
self.facing = facing[facing.index(self.facing)+1]
def die(self):
player.alive = False
canvas.remove(self.snake)
for t_box in self.tail:
canvas.remove(t_box)
start = started = False
gameOver()
class Apple:
def __init__(self):
self.spawn()
def spawn(self):
self.loc = (int(Math.random() * w / inc) * inc, int(Math.random() * h / inc) * inc)
self.apple = __new__(fabric.Rect({
'left': self.loc[0],
'top': self.loc[1],
'width': inc,
'height': inc,
'originX': 'left',
'originY': 'top',
'fill': 'red'
}))
self.apple.hasControls = False
self.apple.evented = False
self.apple.selectable = False
canvas.add(self.apple)
def eat(self):
canvas.remove(self.apple)
class Obstacle:
def __init__(self):
self.in_place = False
self.block = None
def generate_obstacle(self, apple_loc):
if self.block != None:
canvas.remove(self.block)
self.apple_loc = apple_loc
self.spot = int(Math.random()*3)+1
if self.spot == LEFT and apple_loc[0] == 0:
self.spot = RIGHT
if self.spot == RIGHT and apple_loc[0] == w-inc:
self.spot = LEFT
if self.spot == UP and apple_loc[1] == 0:
self.spot = DOWN
if self.spot == DOWN and apple_loc[1] == h-inc:
self.spot = UP
if self.spot == LEFT:
self.locs = (self.apple_loc[0]-inc, self.apple_loc[1])
elif self.spot == UP:
self.locs = (self.apple_loc[0], self.apple_loc[1]-inc)
elif self.spot == RIGHT:
self.locs = (self.apple_loc[0]+inc, self.apple_loc[1])
elif self.spot == DOWN:
self.locs = (self.apple_loc[0], self.apple_loc[1]+inc)
def draw_obstacle(self):
if self.block != None:
canvas.remove(self.block)
self.block = __new__(fabric.Rect({
'left': self.locs[0],
'top': self.locs[1],
'width': inc,
'height': inc,
'originX': 'left',
'originY': 'top',
'fill': 'black'
}))
self.block.hasControls = False
self.block.evented = False
self.block.selectable = False
canvas.add(self.block)
self.in_place = True
def remove_obstacle(self):
canvas.remove(self.block)
self.in_place = False
class Mongoose:
def __init__(self):
self.locs = [0,0]
self.mongoose = None
def generate_mongoose(self):
self.direction = int(Math.random()*3)+1
if self.direction == LEFT:
self.locs[0] = w
self.locs[1] = int(Math.random()*h/inc)*inc
if self.direction == UP:
self.locs[0] = int(Math.random()*w/inc)*inc
self.locs[1] = h
if self.direction == RIGHT:
self.locs[0] = -1*inc
self.locs[1] = int(Math.random()*h/inc)*inc
if self.direction == DOWN:
self.locs[0] = int(Math.random()*w/inc)*inc
self.locs[1] = -1*inc
self.hunting = True
def draw(self):
if self.mongoose != None:
canvas.remove(self.mongoose)
if self.hunting:
if self.direction == LEFT:
self.locs = [self.locs[0]-inc, self.locs[1]]
if self.locs[0] < 0:
self.die()
if self.direction == UP:
self.locs = [self.locs[0], self.locs[1]-inc]
if self.locs[1] < 0:
self.die()
if self.direction == RIGHT:
self.locs = [self.locs[0]+inc, self.locs[1]]
if self.locs[0] >= w:
self.die()
if self.direction == DOWN:
self.locs = [self.locs[0], self.locs[1]+inc]
if self.locs[1] >= h:
self.die()
self.mongoose = __new__(fabric.Rect({
'left': self.locs[0],
'top': self.locs[1],
'width': inc,
'height': inc,
'originX': 'left',
'originY': 'top',
'fill': 'yellow'
}))
self.mongoose.hasControls = False
self.mongoose.evented = False
self.mongoose.selectable = False
canvas.add(self.mongoose)
def die(self):
self.hunting = False
canvas.remove(self.mongoose)
u = None
def update():
nonlocal u
if u != None:
window.clearTimeout(u)
nonlocal slowdown
nonlocal start
nonlocal started
if player != None:
moveCanvas()
changeColor()
if not started and start:
startTheGame()
if start and started and player != None:
player.update()
if player.loc[0] == apple.loc[0] and player.loc[1] == apple.loc[1]:
apple.eat()
apple.spawn()
player.snake_length += 1
changeScore(player.snake_length - 1)
if player.snake_length-1 > 5:
obstacle.generate_obstacle(apple.loc)
if obstacle.locs not in player.coords:
obstacle.draw_obstacle()
elif obstacle.in_place:
obstacle.remove_obstacle()
'''if mongoose.hunting and player.loc[0]==mongoose.locs[0] and player.loc[1]==mongoose.locs[1]:
mongoose.die()
player.snake_length += 2
changeScore(player.snake_length - 1)
index = 0
for coordinate in player.coords:
if mongoose.locs[0] == coordinate[0] and mongoose.locs[1] == coordinate[1] and mongoose.hunting:
player.snake_length = index+1
changeScore(player.snake_length - 1)
index += 1'''
if obstacle.in_place and player.loc[0]==obstacle.locs[0] and player.loc[1]==obstacle.locs[1]:
alert("You ran into an obstacle! Click OK to continue.")
player.die()
if player.loc[0] < 0 or player.loc[0] >= w or player.loc[1] < 0 or player.loc[1] >= h:
alert("You went out of bounds! Click OK to continue.")
player.die()
if player.alive:
update_time = 350 - (10*(player.snake_length-1))
if update_time <= 0:
update_time = 1
u = window.setTimeout(update, update_time)
else:
u = window.setTimeout(update, 500)
#window.onblur = pauseGame
def focus():
focus = not focus
def pauseGame():
alert("Game Paused. Click OK to continue.")
def startTheGame():
nonlocal canvas
canvas = __new__(fabric.Canvas("canvas", {'width': w, 'height': h}))
document.getElementById("canvas").style.border = '5px solid black'
nonlocal started
nonlocal player
nonlocal apple
nonlocal obstacle
nonlocal mongoose
player = Snake()
apple = Apple()
obstacle = Obstacle()
mongoose = Mongoose()
window.setTimeout(genMongoose, 2000)
window.addEventListener('keydown', player.turn, True)
document.addEventListener('click', player.turn_mobile)
started = True
update()
d = None
def draw_mongoose():
nonlocal d
if d != None:
window.clearTimeout(d)
mongoose.draw()
checkMongooseOrDead()
if mongoose.hunting:
d = window.setTimeout(draw_mongoose, 250)
c = None
def checkMongooseOrDead():
nonlocal c
if c != None:
window.clearTimeout(c)
if mongoose.hunting:
index = 0
for coordinate in player.coords:
if coordinate[0] == player.loc[0] and coordinate[1] == player.loc[1]:
continue
if mongoose.locs[0] == coordinate[0] and mongoose.locs[1] == coordinate[1]:
player.snake_length = index+1
changeScore(player.snake_length - 1)
break
index += 1
if player.loc[0]==mongoose.locs[0] and player.loc[1]==mongoose.locs[1]:
mongoose.die()
player.snake_length += 2
changeScore(player.snake_length - 1)
update_time = 50
if update_time <= 0:
update_time = 1
c = window.setTimeout(checkMongooseOrDead, update_time)
g = None
def genMongoose():
nonlocal g
if g != None:
window.clearTimeout(g)
if start and started:
mongoose.generate_mongoose()
draw_mongoose()
g = window.setTimeout(genMongoose, 250*h/inc*2)
cv_mv = 1
left = 0
top = 0
m = None
def moveCanvas():
nonlocal m
if m != None:
window.clearTimeout(m)
nonlocal start
nonlocal started
if start and started:
if player.alive:
nonlocal mv_right
nonlocal mv_bottom
cv = document.getElementById("canvas")
if player.alive and (player.snake_length-1 >= 15):
if left+w+20 < window.innerWidth and mv_right:
left += cv_mv
if left+w+20 >= window.innerWidth:
mv_right = False
elif not mv_right:
left -= cv_mv
if left <= 0:
mv_right = True
if top+h+160 < window.innerHeight and mv_bottom:
top += cv_mv
if top+h+160 >= window.innerHeight:
mv_bottom = False
elif not mv_bottom:
top -= cv_mv
if top <= 0:
mv_bottom = True
cv.style.left = ""+left+"px"
cv.style.top = ""+top+"px"
cv.style.border = '5px solid black'
m = window.setTimeout(moveCanvas, 125)
mv_right = True
mv_bottom = True
t = None
def changeColor():
nonlocal t
if t != None:
window.clearTimeout(t)
if start and started and player.alive and (player.snake_length-1 >=10):
nonlocal rd
nonlocal gd
nonlocal bd
if r > 0 and rd:
r -= 1
if r == 0:
rd = False
elif not rd:
r += 1
if r == 255:
rd = True
if g > 0 and gd:
g -= 1
if g == 0:
gd = False
elif not gd:
g += 1
if g == 255:
gd = True
if b > 0 and bd:
b -= 1
if b == 0:
bd = False
elif not bd:
b += 1
if b == 255:
bd = True
canvas.backgroundColor = 'rgb('+r+','+g+','+b+')'
t = window.setTimeout(changeColor, 100)
r, g, b = int(255*Math.random()), int(255*Math.random()), int(255*Math.random())
rd, gd, bd = True, True, True