-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsnake.py
97 lines (87 loc) · 3.36 KB
/
snake.py
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
import itertools, time, random
from curtsies import FullscreenWindow, Input, FSArray
from curtsies.fmtfuncs import red, bold, green, on_blue, yellow, on_red, blue
MAX_FPS = 10
time_per_frame = 1. / MAX_FPS
class FrameCounter(object):
def __init__(self):
self.render_times = []
self.dt = .5
def frame(self):
self.render_times.append(time.time())
def fps(self):
now = time.time()
while self.render_times and self.render_times[0] < now - self.dt:
self.render_times.pop(0)
return len(self.render_times) / max(self.dt, now - self.render_times[0] if self.render_times else self.dt)
class SnakeGame(object):
def __init__(self, width, height):
self.snake_segments = [(10, 10), (10, 11), (10, 12)]
self.width = width
self.height = height
self.direction = (1, 0)
def render(self, isDead):
if not isDead:
a = FSArray(self.height, self.width)
for seg in self.snake_segments:
a[seg[0],seg[1]] = blue('X')
return a
else:
a = self.deathSequence()
return a
def move(self):
self.snake_segments.insert(0, (self.snake_segments[0][0] + self.direction[0],
(self.snake_segments[0][1] + self.direction[1])))
self.snake_segments.pop(3)
def deathSequence(self):
a = FSArray(self.height, self.width)
a[10,10] = red('X')
a[10,14] = red('X')
a[12, 10] = red('_')
a[12, 11] = red('_')
a[12, 12] = red('_')
a[12, 13] = red('_')
a[12, 14] = red('_')
return a
def main():
counter = FrameCounter()
with FullscreenWindow() as window:
print('Press escape to exit')
game = SnakeGame(window.height, window.width)
with Input() as input_generator:
c = None
last_c = '<DOWN>'
for framenum in itertools.count(0):
t0 = time.time()
while True:
t = time.time()
temp_c = input_generator.send(max(0, t - (t0 + time_per_frame)))
if temp_c is not None:
c = temp_c
if c is None:
pass
elif c == '<ESC>':
return
elif c == '<UP>' and last_c != '<DOWN>':
game.direction = (-1, 0)
last_c = '<UP>'
elif c == '<DOWN>' and last_c != '<UP>':
game.direction = (1, 0)
last_c = '<DOWN>'
elif c == '<LEFT>' and last_c != '<RIGHT>':
game.direction = (0, -1)
last_c = '<LEFT>'
elif c == '<RIGHT>' and last_c != '<LEFT>':
game.direction = (0, 1)
last_c = '<RIGHT>'
c = None
if time_per_frame < t - t0:
break
fps = 'FPS: %.1f' % counter.fps()
a = game.render(isDead = False) # insert death boolean
a[0:1, 0:len(fps)] = [fps]
game.move()
window.render_to_terminal(a)
counter.frame()
if __name__ == '__main__':
main()