-
Notifications
You must be signed in to change notification settings - Fork 0
/
snake_new.py
362 lines (293 loc) · 12 KB
/
snake_new.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
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
import pygame
import os
import random
import numpy as np
from feed_forward_neural_network import *
class Snake:
def __init__(self, x, y, food, color):
self.x = x
self.y = y
self.width = 9
self.height = 9
self.snake_list = list()
self.snake_list.append(pygame.Rect(self.x * 10 + 1, self.y * 10 + 1, self.width, self.height))
self.snake_list.append(pygame.Rect((self.x + 1) * 10 + 1, (self.y) * 10 + 1, self.width, self.height))
self.snake_list.append(pygame.Rect((self.x + 1) * 10 + 1, (self.y + 1) * 10 + 1, self.width, self.height))
self.state = "none"
self.food = food
self.color = color
self.isDead = False
self.points = 0
def change_directions(self, state):
# directions = ["left", "right", "up", "down"]
# left is 0, right is 1, up is 2, down is 3
if (self.state == 0 and state == 1) or (self.state == 1 and state == 0) or (self.state == 2 and state == 3) or (self.state == 3 and state == 2):
return
self.state = state
def move(self):
# check if food is in sight
# food_direction = [i for i, x in enumerate(self.observe_all_directions()) if x > 0]
# if len(food_direction) > 0:
# index = food_direction[0]
# reward = 0
# punishment = 5
# if index in [2, 4, 7] and self.state == 3: # up
# self.points += reward
# elif index in [0, 1, 2] and self.state == 0: # right
# self.points += reward
# elif index in [0, 3, 5] and self.state == 2: # down
# self.points += reward
# elif index in [5, 6, 7] and self.state == 1: # left
# self.points += reward
# else:
# self.points -= punishment
if self.state == 0:
self.x -= 1
elif self.state == 1:
self.x += 1
elif self.state == 2:
self.y -= 1
elif self.state == 3:
self.y += 1
else:
return
self.snake_list.append((self.x, self.y))
if self.eat():
self.points += 1000
self.food.relocate(self.snake_list)
return
self.snake_list.pop(0)
def eat(self):
if self.x == self.food.x and self.y == self.food.y:
return True
else:
return False
def draw(self):
for segment in self.snake_list:
pygame.draw.rect(screen, self.color, pygame.Rect(segment[0] * 10 + 1, segment[1] * 10 + 1, self.width, self.height))
def dead(self, snakes):
punishment = 900
if self.x < 0 or self.x >= grid_width or self.y < 0 or self.y >= grid_height:
self.points -= punishment
self.isDead = True
return True
elif self.collide_body():
self.points -= punishment
self.isDead = True
return True
elif self.collide_other(snakes):
self.isDead = True
return True
else:
return False
def collide_body(self):
for segment in self.snake_list[:-1]:
if segment[0] == self.x and segment[1] == self.y:
return True
return False
def collide_other(self, snakes):
for snake in snakes:
if (self.x, self.y) in snake.snake_list:
return True
return False
def observe(self, snakes):
return self.observe_all_directions(snakes) + self.apple_direction()
def observe_all_directions(self, snakes):
# Observe what is happening in each of the 8 directions from the snake
# For each of the 8 directions, find out the distance between the snake and the food, wall, and body
observations = list()
for x_dir in range(-1, 2):
for y_dir in range(-1, 2):
if x_dir == 0 and y_dir == 0:
continue
observations += self.observe_direction(x_dir, y_dir, snakes)
return observations
def observe_direction(self, x_dir, y_dir, snakes):
x_bounds = -1 if x_dir < 0 else grid_width
y_bounds = -1 if y_dir < 0 else grid_height
x = self.x
y = self.y
dist_covered = 0
(dist_food, dist_wall, dist_body) = (-1, -1, -1)
body_hit = False
while x != x_bounds and y != y_bounds:
x += x_dir
y += y_dir
dist_covered += 1
if x == self.food.x and y == self.food.y:
dist_food = dist_covered
break
for snake in snakes:
if (self.x, self.y) in snake.snake_list:
dist_body = dist_covered
break
if x == x_bounds or y == y_bounds:
dist_wall = dist_covered
if not body_hit:
for segment in self.snake_list[:-1]:
if segment[0] == self.x and segment[1] == self.y:
dist_body = dist_covered
body_hit = True
break
dist_obstacle = dist_wall if dist_body < 0 else min(dist_body, dist_wall)
return [dist_food if dist_food < dist_obstacle and dist_food > 0 else -dist_obstacle]
def apple_direction(self):
vector = list()
x_diff = self.food.x - self.x
y_diff = self.food.y - self.y
if x_diff != 0:
vector.append(int(abs(x_diff) / x_diff))
else:
vector.append(0)
if y_diff != 0:
vector.append(int(abs(y_diff) / y_diff))
else:
vector.append(0)
return vector
class Food:
def __init__(self, grid_width, grid_height):
self.grid_width = grid_width
self.grid_height = grid_height
self.x = random.randint(0, self.grid_width - 1)
self.y = random.randint(0, self.grid_height - 1)
self.width = 9
self.height = 9
self.rect = pygame.Rect(self.x * 10 + 1, self.y * 10 + 1, self.width, self.height)
def relocate(self, snake):
self.x = random.randint(0, self.grid_width - 1)
self.y = random.randint(0, self.grid_height - 1)
self.rect = pygame.Rect(self.x * 10 + 1, self.y * 10 + 1, self.width, self.height)
if (self.x, self.y) in snake:
self.relocate(snake)
def draw(self):
pygame.draw.rect(screen, (218, 165, 32), self.rect)
def display_game_with_GA(weights, num_snakes):
f = Food(grid_width, grid_height)
# player1 = Snake(random.randint(1, grid_width - 2), random.randint(1, grid_height - 2), f, (77, 237, 48))
# player2 = Snake(random.randint(1, grid_width - 2), random.randint(1, grid_height - 2), f, (255, 0, 0))
player_list = list()
for i in range(num_snakes):
player_list.append(Snake(random.randint(1, grid_width - 2), random.randint(1, grid_height - 2), f, (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))))
max_steps = 3000
running = True
for i in range(max_steps):
pygame.event.get()
clock.tick(FPS)
alive_list = [snek for snek in player_list if not snek.isDead]
if len(alive_list) == 0:
running = False
# if player1.isDead and player2.isDead:
# running = False
for event in pygame.event.get():
# If you press the x button on the top right, quit the game
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
# If you press the q key, quit the game
if event.key == pygame.K_q:
running = False
if not running:
break
# player.change_directions(random.randint(0, 3))
for i in range(len(alive_list)):
player = alive_list[i]
predicted_direction = np.argmax(np.array(forward_propagation(np.array(player.observe(alive_list[0: i] + alive_list[i + 1: len(alive_list)])).reshape(-1, n_x), weights)))
player.change_directions(predicted_direction)
player.move()
# if not player1.isDead:
# predicted_direction_1 = np.argmax(np.array(forward_propagation(np.array(player1.observe(player2)).reshape(-1, n_x), weights1)))
# player1.change_directions(predicted_direction_1)
# player1.move()
#
# if not player2.isDead:
# predicted_direction_2 = np.argmax(np.array(forward_propagation(np.array(player2.observe(player1)).reshape(-1, n_x), weights2)))
# player2.change_directions(predicted_direction_2)
# player2.move()
for i in range(len(alive_list)):
player = alive_list[i]
if not player.isDead and player.dead(alive_list[0: i] + alive_list[i + 1: len(alive_list)]):
print("A player died.")
# if not player1.isDead and player1.dead(player2):
# print("Player 1 died.")
# if not player2.isDead and player2.dead(player1):
# print("Player 2 died.")
pygame.draw.rect(screen, (0, 0, 0), background)
# if not player1.isDead:
# player1.draw()
# player1.food.draw()
# if not player2.isDead:
# player2.draw()
# player2.food.draw()
for player in alive_list:
if not player.isDead:
player.draw()
alive_list[0].food.draw()
pygame.display.update()
for i in range(len(player_list)):
print("Player " + str(i) + " was " + str(len(player_list[i].snake_list)) + " long!")
# return player.points
def run_game_with_GA(weights):
f = Food(grid_width, grid_height)
player = Snake(random.randint(1, grid_width - 2), random.randint(1, grid_height - 2), f)
max_steps = 3000
for i in range(max_steps):
pygame.event.get()
# player.change_directions(random.randint(0, 3))
predicted_direction = np.argmax(np.array(forward_propagation(np.array(player.observe()).reshape(-1, n_x), weights)))
player.change_directions(predicted_direction)
player.move()
if player.dead():
break
pygame.draw.rect(screen, (0, 0, 0), background)
player.draw()
player.food.draw()
pygame.display.update()
return player.points
def test_game():
f = Food(grid_width, grid_height)
player = Snake(random.randint(1, grid_width - 2), random.randint(1, grid_height - 2), f)
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
# If you press the x button on the top right, quit the game
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
# If you press the q key, quit the game
if event.key == pygame.K_q:
running = False
if event.key == pygame.K_w:
player.change_directions(2)
if event.key == pygame.K_s:
player.change_directions(3)
if event.key == pygame.K_a:
player.change_directions(0)
if event.key == pygame.K_d:
player.change_directions(1)
# directions = ["left", "right", "up", "down"]
player.move()
if player.dead():
running = False
continue
pygame.draw.rect(screen, (0, 0, 0), background)
player.draw()
player.food.draw()
pygame.display.update()
# print(player.observe())
print(player.observe(player2))
else:
print("You lose! Your snake's length was " + str(len(player.snake_list)))
# These are the dimensions of the background image for our game
(grid_width, grid_height) = (40, 40)
screen_length = grid_width * 10 + 1
screen_height = grid_height * 10 + 1
dim_field = (screen_length, screen_height)
screen = pygame.display.set_mode(dim_field)
background = pygame.Rect(0, 0, screen_length, screen_height)
FPS = 10
# Game loop
clock = pygame.time.Clock()
# Direction travelling
# each of the 8 directions from the snake
# location of apple