-
Notifications
You must be signed in to change notification settings - Fork 0
/
snake.py
207 lines (166 loc) · 5.12 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
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
import os
import msvcrt
import time
import random
from termcolor import colored
import json
# ----------------- Required Data -----------------
spot_types = {
-1: 'border',
0: 'free',
1: 'snake',
2: 'food',
}
spot_view = {
'border': colored('#', 'magenta'),
'free': " ",
'snake': "X",
'food': colored('&', 'yellow'),
}
moves = {
'up': (-1, 0),
'down': (1, 0),
'right': (0, 1),
'left': (0, -1),
}
key_commands = {
'w': 'up',
's': 'down',
'a': 'left',
'd': 'right',
}
opposite_commands = {
'up': 'down',
'down': 'up',
'right': 'left',
'left': 'right',
}
# ---------------- Custom Functions ---------------
def num_to_view(num):
return spot_view[spot_types[num]]
def row_to_view(row):
return ' '.join([num_to_view(n) for n in row])
# -------------------- Classes ------------------
class Game(object):
def __init__(self, size):
self.size = size
self.zone = [[0 for x in xrange(self.size)] for y in xrange(self.size)]
self.add_borders()
self.next_move = 'down'
self.snake = [[self.size//2, self.size//2 - 1], [self.size//2, self.size//2]]
self.play = True
self.result = ""
self.score = "Score: {}".format(len(self.snake) - 2)
self.food_coordinates = ""
self.rounds = 0
self.timeout = 0.3 / (len(self.snake) - 1.0)
self.food = {
'y': 0,
'x': 0,
}
def add_borders(self):
self.zone.append([-1 for x in xrange(self.size + 2)])
self.zone.insert(0, [-1 for x in xrange(self.size + 2)])
for r in self.zone:
if r[0] == 0:
r.insert(0, -1)
r.append(-1)
def next_spot(self):
next_spot_y = self.snake[-1][0] + moves[self.next_move][0]
next_spot_x = self.snake[-1][1] + moves[self.next_move][1]
return [next_spot_y, next_spot_x]
def check_spot(self, spot):
spot_value = self.zone[spot[0]][spot[1]]
if spot_value == 0:
return 'free'
elif spot_value == 2:
return 'eat'
if spot_value == -1 or spot_value == 1:
return 'crash'
def clear_spot(self, spot):
self.zone[spot[0]][spot[1]] = 0
def draw_spot(self, spot, num):
self.zone[spot[0]][spot[1]] = num
def snake_move(self, eat):
for spot in self.snake:
self.clear_spot(spot)
if not eat:
self.snake.pop(0)
self.snake.append(self.next_spot())
for spot in self.snake:
self.draw_spot(spot, 1)
if eat:
self.generate_food()
def generate_food(self):
a = random.randint(1, self.size)
b = random.randint(1, self.size)
if self.check_spot((a, b)) == 'free':
self.zone[a][b] = 2
self.food['y'] = a
self.food['x'] = b
else:
return self.generate_food()
def show(self):
os.system('cls')
for r in self.zone:
print row_to_view(r)
def exec_round(self):
self.rounds += 1
if self.check_spot(self.next_spot()) == 'free':
self.snake_move(False)
elif self.check_spot(self.next_spot()) == 'eat':
self.snake_move(True)
elif self.check_spot(self.next_spot()) == 'crash':
self.play = False
self.result = "You lose!"
self.jsonify()
self.show()
def loop(self):
self.show()
self.generate_food()
self.snake_move(False)
while self.play:
self.timeout = 0.3 / (len(self.snake) - 1.0)
start_time = time.time()
while True:
if msvcrt.kbhit():
inp = msvcrt.getch()
if inp in key_commands:
if not key_commands[inp] == opposite_commands[self.next_move]:
self.next_move = key_commands[inp]
else:
self.next_move = opposite_commands[key_commands[inp]]
break
elif time.time() - start_time > self.timeout:
break
self.exec_round()
self.score = "Score: {}".format(len(self.snake) - 2)
print self.score
print self.result
def jsonify(self):
f = open('log.txt', 'w')
f.write(json.dumps(self.__dict__))
f.close()
class Menu(object):
def __init__(self, board_size):
self.board_size = board_size
self.game = Game(self.board_size)
def run(self):
self.game.loop()
self.ask_for_restart()
def ask_for_restart(self):
i = raw_input("Would you like to restart? Y/N: ")
if i.upper() == 'Y':
return self.restart()
elif i.upper() == 'N':
print 'Thank you for playing! Ohad Chaet'
exit()
else:
print 'Answer must be either "Y" or "N".'
return self.ask_for_restart()
def restart(self):
self.game = Game(self.board_size)
self.run()
if __name__ == '__main__':
menu = Menu(20)
menu.run()