Repository navigation
Expand file tree
/
Copy pathold.py
More file actions
110 lines (83 loc) · 2.47 KB
/
Copy pathold.py
File metadata and controls
110 lines (83 loc) · 2.47 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
import asyncio
from collections import deque
from random import randrange
from blessed import Terminal
terminal = Terminal()
snake = deque([(1, 2), (1, 1), (2, 1)])
dir = (1, 0)
inp = True
stop = False
rows, cols = 20, 20
t = 0.2
def new_food():
while True:
food = randrange(cols), randrange(rows)
if food not in snake:
return food
food = new_food()
def print_grid():
# clear screen
print(terminal.home + terminal.clear_eos, end='')
grid = []
for y in range(rows):
for x in range(cols):
if (x, y) in snake:
grid.append(terminal.reverse('██'))
elif (x, y) == food:
grid.append(terminal.red('██'))
else:
grid.append('██')
grid.append('\n')
print(''.join(grid))
async def input_loop():
global dir, stop, inp
with terminal.cbreak():
while not stop:
key = terminal.inkey(timeout=0)
# the keypress will be buffered by the terminal
if not key or not inp:
await asyncio.sleep(0.01)
continue
if key.name == 'KEY_UP' and dir != (0, 1):
dir = (0, -1)
inp = False
elif key.name == 'KEY_DOWN' and dir != (0, -1):
dir = (0, 1)
inp = False
elif key.name == 'KEY_LEFT' and dir != (1, 0):
dir = (-1, 0)
inp = False
elif key.name == 'KEY_RIGHT' and dir != (-1, 0):
dir = (1, 0)
inp = False
elif key.name == 'KEY_ESCAPE' or key in 'Qq':
stop = True
print('Quiting...')
async def game_loop():
global stop, inp, food, t
print(terminal.hide_cursor(), end='')
print_grid()
while not stop:
head_x, head_y = snake[-1]
dx, dy = dir
new_head_x, new_head_y = (head_x + dx) % cols, (head_y + dy) % rows
if (new_head_x, new_head_y) in snake:
stop = True
print_grid()
print('Game Over :(')
break
snake.append((new_head_x, new_head_y))
if (new_head_x, new_head_y) == food:
food = new_food()
t /= 1.1
else:
snake.popleft()
print_grid()
inp = True
await asyncio.sleep(t)
async def main():
await asyncio.gather(
input_loop(),
game_loop(),
)
asyncio.run(main())