forked from henniedeharder/snake
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnake_env.py
More file actions
364 lines (291 loc) · 12.2 KB
/
snake_env.py
File metadata and controls
364 lines (291 loc) · 12.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
import turtle
import random
import time
import math
import gym
from gym import spaces
from gym.utils import seeding
HEIGHT = 20 # number of steps vertically from wall to wall of screen
WIDTH = 20 # number of steps horizontally from wall to wall of screen
PIXEL_H = 20*HEIGHT # pixel height + border on both sides
PIXEL_W = 20*WIDTH # pixel width + border on both sides
SLEEP = 0.2 # time to wait between steps
GAME_TITLE = 'Snake'
BG_COLOR = 'white'
SNAKE_SHAPE = 'square'
SNAKE_COLOR = 'black'
SNAKE_START_LOC_H = 0
SNAKE_START_LOC_V = 0
APPLE_SHAPE = 'circle'
APPLE_COLOR = 'green'
class Snake(gym.Env):
def __init__(self, human=False, env_info={'state_space':None}):
super(Snake, self).__init__()
self.done = False
self.seed()
self.reward = 0
self.action_space = 4
self.state_space = 12
self.total, self.maximum = 0, 0
self.human = human
self.env_info = env_info
## GAME CREATION WITH TURTLE (RENDER?)
# screen/background
self.win = turtle.Screen()
self.win.title(GAME_TITLE)
self.win.bgcolor(BG_COLOR)
self.win.tracer(0)
self.win.setup(width=PIXEL_W+32, height=PIXEL_H+32)
# snake
self.snake = turtle.Turtle()
self.snake.shape(SNAKE_SHAPE)
self.snake.speed(0)
self.snake.penup()
self.snake.color(SNAKE_COLOR)
self.snake.goto(SNAKE_START_LOC_H, SNAKE_START_LOC_V)
self.snake.direction = 'stop'
# snake body, add first element (for location of snake's head)
self.snake_body = []
self.add_to_body()
# apple
self.apple = turtle.Turtle()
self.apple.speed(0)
self.apple.shape(APPLE_SHAPE)
self.apple.color(APPLE_COLOR)
self.apple.penup()
self.move_apple(first=True)
# distance between apple and snake
self.dist = math.sqrt((self.snake.xcor()-self.apple.xcor())**2 + (self.snake.ycor()-self.apple.ycor())**2)
# score
self.score = turtle.Turtle()
self.score.speed(0)
self.score.color('black')
self.score.penup()
self.score.hideturtle()
self.score.goto(0, 100)
self.score.write(f"Total: {self.total} Highest: {self.maximum}", align='center', font=('Courier', 18, 'normal'))
# control
self.win.listen()
self.win.onkey(self.go_up, 'Up')
self.win.onkey(self.go_right, 'Right')
self.win.onkey(self.go_down, 'Down')
self.win.onkey(self.go_left, 'Left')
def seed(self, seed=None):
self.np_random, seed = seeding.np_random(seed)
return [seed]
def random_coordinates(self):
apple_x = random.randint(-WIDTH/2, WIDTH/2)
apple_y = random.randint(-HEIGHT/2, HEIGHT/2)
return apple_x, apple_y
def move_snake(self):
if self.snake.direction == 'stop':
self.reward = 0
if self.snake.direction == 'up':
y = self.snake.ycor()
self.snake.sety(y + 20)
if self.snake.direction == 'right':
x = self.snake.xcor()
self.snake.setx(x + 20)
if self.snake.direction == 'down':
y = self.snake.ycor()
self.snake.sety(y - 20)
if self.snake.direction == 'left':
x = self.snake.xcor()
self.snake.setx(x - 20)
def go_up(self):
if self.snake.direction != "down":
self.snake.direction = "up"
def go_down(self):
if self.snake.direction != "up":
self.snake.direction = "down"
def go_right(self):
if self.snake.direction != "left":
self.snake.direction = "right"
def go_left(self):
if self.snake.direction != "right":
self.snake.direction = "left"
def move_apple(self, first=False):
if first or self.snake.distance(self.apple) < 20:
while True:
self.apple.x, self.apple.y = self.random_coordinates()
self.apple.goto(round(self.apple.x*20), round(self.apple.y*20))
if not self.body_check_apple():
break
if not first:
self.update_score()
self.add_to_body()
first = False
return True
def update_score(self):
self.total += 1
if self.total >= self.maximum:
self.maximum = self.total
self.score.clear()
self.score.write(f"Total: {self.total} Highest: {self.maximum}", align='center', font=('Courier', 18, 'normal'))
def reset_score(self):
self.score.clear()
self.total = 0
self.score.write(f"Total: {self.total} Highest: {self.maximum}", align='center', font=('Courier', 18, 'normal'))
def add_to_body(self):
body = turtle.Turtle()
body.speed(0)
body.shape('square')
body.color('black')
body.penup()
self.snake_body.append(body)
def move_snakebody(self):
if len(self.snake_body) > 0:
for index in range(len(self.snake_body)-1, 0, -1):
x = self.snake_body[index-1].xcor()
y = self.snake_body[index-1].ycor()
self.snake_body[index].goto(x, y)
self.snake_body[0].goto(self.snake.xcor(), self.snake.ycor())
def measure_distance(self):
self.prev_dist = self.dist
self.dist = math.sqrt((self.snake.xcor()-self.apple.xcor())**2 + (self.snake.ycor()-self.apple.ycor())**2)
def body_check_snake(self):
if len(self.snake_body) > 1:
for body in self.snake_body[1:]:
if body.distance(self.snake) < 20:
self.reset_score()
return True
def body_check_apple(self):
if len(self.snake_body) > 0:
for body in self.snake_body[:]:
if body.distance(self.apple) < 20:
return True
def wall_check(self):
if self.snake.xcor() > 200 or self.snake.xcor() < -200 or self.snake.ycor() > 200 or self.snake.ycor() < -200:
self.reset_score()
return True
def reset(self):
if self.human:
time.sleep(1)
for body in self.snake_body:
body.goto(1000, 1000)
for element in self.snake_body:
turtle = self.win.turtles().index(element)
self.win.turtles()[turtle].reset()
del self.win.turtles()[turtle]
self.snake_body = []
self.snake.goto(SNAKE_START_LOC_H, SNAKE_START_LOC_V)
self.snake.direction = 'stop'
self.reward = 0
self.total = 0
self.done = False
state = self.get_state()
return state
def run_game(self):
reward_given = False
self.win.update()
self.move_snake()
if self.move_apple():
self.reward = 10
reward_given = True
self.move_snakebody()
self.measure_distance()
if self.body_check_snake():
self.reward = -100
reward_given = True
self.done = True
if self.human:
self.reset()
if self.wall_check():
self.reward = -100
reward_given = True
self.done = True
if self.human:
self.reset()
if not reward_given:
if self.dist < self.prev_dist:
self.reward = 1
else:
self.reward = -1
# time.sleep(0.1)
if self.human:
time.sleep(SLEEP)
state = self.get_state()
# AI agent
def step(self, action):
if action == 0:
self.go_up()
if action == 1:
self.go_right()
if action == 2:
self.go_down()
if action == 3:
self.go_left()
self.run_game()
state = self.get_state()
return state, self.reward, self.done, {}
def get_state(self):
# snake coordinates abs
self.snake.x, self.snake.y = self.snake.xcor()/WIDTH, self.snake.ycor()/HEIGHT
# snake coordinates scaled 0-1
self.snake.xsc, self.snake.ysc = self.snake.x/WIDTH+0.5, self.snake.y/HEIGHT+0.5
# apple coordintes scaled 0-1
self.apple.xsc, self.apple.ysc = self.apple.x/WIDTH+0.5, self.apple.y/HEIGHT+0.5
# wall check
if self.snake.y >= HEIGHT/2:
wall_up, wall_down = 1, 0
elif self.snake.y <= -HEIGHT/2:
wall_up, wall_down = 0, 1
else:
wall_up, wall_down = 0, 0
if self.snake.x >= WIDTH/2:
wall_right, wall_left = 1, 0
elif self.snake.x <= -WIDTH/2:
wall_right, wall_left = 0, 1
else:
wall_right, wall_left = 0, 0
# body close
body_up = []
body_right = []
body_down = []
body_left = []
if len(self.snake_body) > 3:
for body in self.snake_body[3:]:
if body.distance(self.snake) == 20:
if body.ycor() < self.snake.ycor():
body_down.append(1)
elif body.ycor() > self.snake.ycor():
body_up.append(1)
if body.xcor() < self.snake.xcor():
body_left.append(1)
elif body.xcor() > self.snake.xcor():
body_right.append(1)
if len(body_up) > 0: body_up = 1
else: body_up = 0
if len(body_right) > 0: body_right = 1
else: body_right = 0
if len(body_down) > 0: body_down = 1
else: body_down = 0
if len(body_left) > 0: body_left = 1
else: body_left = 0
# state: apple_up, apple_right, apple_down, apple_left, obstacle_up, obstacle_right, obstacle_down, obstacle_left, direction_up, direction_right, direction_down, direction_left
if self.env_info['state_space'] == 'coordinates':
state = [self.apple.xsc, self.apple.ysc, self.snake.xsc, self.snake.ysc, \
int(wall_up or body_up), int(wall_right or body_right), int(wall_down or body_down), int(wall_left or body_left), \
int(self.snake.direction == 'up'), int(self.snake.direction == 'right'), int(self.snake.direction == 'down'), int(self.snake.direction == 'left')]
elif self.env_info['state_space'] == 'no direction':
state = [int(self.snake.y < self.apple.y), int(self.snake.x < self.apple.x), int(self.snake.y > self.apple.y), int(self.snake.x > self.apple.x), \
int(wall_up or body_up), int(wall_right or body_right), int(wall_down or body_down), int(wall_left or body_left), \
0, 0, 0, 0]
elif self.env_info['state_space'] == 'no body knowledge':
state = [int(self.snake.y < self.apple.y), int(self.snake.x < self.apple.x), int(self.snake.y > self.apple.y), int(self.snake.x > self.apple.x), \
wall_up, wall_right, wall_down, wall_left, \
int(self.snake.direction == 'up'), int(self.snake.direction == 'right'), int(self.snake.direction == 'down'), int(self.snake.direction == 'left')]
else:
state = [int(self.snake.y < self.apple.y), int(self.snake.x < self.apple.x), int(self.snake.y > self.apple.y), int(self.snake.x > self.apple.x), \
int(wall_up or body_up), int(wall_right or body_right), int(wall_down or body_down), int(wall_left or body_left), \
int(self.snake.direction == 'up'), int(self.snake.direction == 'right'), int(self.snake.direction == 'down'), int(self.snake.direction == 'left')]
# print(state)
return state
def bye(self):
self.win.bye()
if __name__ == '__main__':
human = True
env = Snake(human=human)
if human:
while True:
env.run_game()