-
Notifications
You must be signed in to change notification settings - Fork 0
/
t.py
451 lines (339 loc) · 14.4 KB
/
t.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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
import random
import pygame
from directions import Directions
from settings import *
import time
import simple_greedy_agent
"""
GAME SETUP
"""
pygame.init()
settings = get_settings()
display = pygame.display.set_mode((settings['display_width'], settings['display_height']))
pygame.display.set_caption('Snake')
default_font = settings['default_font']
title_font = settings['title_font']
score_font = settings['score_font']
SEG_DIM = settings['block_dim']
snake_head_img = pygame.image.load("snake head.png")
snake_head_img = pygame.transform.scale(snake_head_img, (settings['block_dim'], settings['block_dim']))
snake_body_img = pygame.image.load("snake body.png")
snake_body_img = pygame.transform.scale(snake_body_img, (settings['block_dim'], settings['block_dim']))
apple_img = pygame.image.load("apple.png")
apple_img = pygame.transform.scale(apple_img, (settings['block_dim'], settings['block_dim']))
star_img = pygame.image.load("star.png")
star_img = pygame.transform.scale(star_img, (settings['block_dim'], settings['block_dim']))
wall_img = pygame.image.load("wall.png")
wall_img = pygame.transform.scale(wall_img, (settings['block_dim'], settings['block_dim']))
head = dict()
tail = []
facing = None
opposite = None
direction = None
apple = None
walls = []
tunnels = []
stars = []
score = 0
apples_ate = 0
tunnels_burrowed = 0
stars_collected = 0
def reset(settings, first_play=False):
global head, tail, facing, opposite, direction, apple, snake_head_img, snake_body_img
direction = settings['starting_direction']
opposite = Directions.get_opposite(facing)
head['rect'] = get_segment()
head['facing'] = settings['starting_direction']
apple = spawn_apple()
snake_head_img = pygame.image.load("snake head.png")
snake_head_img = pygame.transform.scale(snake_head_img, (settings['block_dim'], settings['block_dim']))
snake_body_img = pygame.image.load("snake body.png")
snake_body_img = pygame.transform.scale(snake_body_img, (settings['block_dim'], settings['block_dim']))
if settings['autostart']:
direction = facing
if first_play:
if settings['walls_on']:
generate_walls()
if settings['tunnels_on']:
generate_tunnels()
else:
tail = []
for _ in range(settings['starting_tail']):
move_head(head['facing'])
tail.append(get_segment())
"""
GAME MECHANICS
"""
def move_head(direction):
global head, tail, head_x, head_y, facing, opposite, snake_head_img
if direction == opposite:
direction = head['facing']
if facing != direction:
snake_head_img = orientate_snake(snake_head_img, head, direction.value)
if direction == Directions.UP:
head['rect'].top -= SEG_DIM
head['facing'] = Directions.UP
opposite = Directions.get_opposite(direction)
elif direction == Directions.RIGHT:
head['rect'].left += SEG_DIM
head['facing'] = Directions.RIGHT
opposite = Directions.get_opposite(direction)
elif direction == Directions.DOWN:
head['rect'].top += SEG_DIM
head['facing'] = Directions.DOWN
opposite = Directions.get_opposite(direction)
elif direction == Directions.LEFT:
head['rect'].left -= SEG_DIM
head['facing'] = Directions.LEFT
opposite = Directions.get_opposite(direction)
def move_tail(prev_head):
global tail
if tail:
new_tail = tail[1: len(tail)]
new_tail.append(prev_head)
tail = new_tail
def orientate_snake(img, segment, value):
rotation = segment['facing'].value - value
img = pygame.transform.rotate(img, rotation)
return img
def generate_walls():
global walls, wall_img
for _ in range(100):
if settings['wall_density'] >= random.random():
loc_x = round(random.randrange(0, settings['display_width']) / settings['block_dim']) * settings['block_dim']
loc_y = round(random.randrange(0, settings['display_height']) / settings['block_dim']) * settings['block_dim']
width = round(random.randrange(0, settings['wall_max_w']) / settings['block_dim']) * settings['block_dim']
height = round(random.randrange(0, settings['wall_max_h']) / settings['block_dim']) * settings['block_dim']
wall_img = pygame.transform.scale(wall_img, (settings['block_dim'], settings['block_dim']))
walls.append(pygame.Rect([loc_x, loc_y, width, height]))
def generate_tunnels():
global tunnels
for _ in range(settings['tunnel_count']):
collided = True
while collided:
x = round(random.randrange(0, settings['display_width'] - settings['block_dim']) / settings['block_dim']) * settings['block_dim']
y = round(random.randrange(0, settings['display_height'] - settings['block_dim']) / settings['block_dim']) * settings['block_dim']
tunnel = pygame.Rect(x, y, settings['block_dim'], settings['block_dim'])
collided = False
for wall in walls:
if tunnel.colliderect(wall):
collided = True
tunnels.append(tunnel)
def burrow_tunnel(tunnel_ind):
global head, tunnels_burrowed
emerging_tunnel = tunnel_ind
while emerging_tunnel == tunnel_ind:
emerging_tunnel = random.randrange(len(tunnels))
tunnels_burrowed += 1
head['rect'] = tunnels[emerging_tunnel].copy()
def has_apple_collided():
global score, apples_ate
if apple and head['rect'].colliderect(apple):
score += settings['apple_reward']
apples_ate += 1
spawn_apple()
return True
def has_wall_collided():
for wall in walls:
if head['rect'].colliderect(wall):
return True
return False
def has_self_collided():
for seg in tail:
if head['rect'].colliderect(seg['rect']):
return True
return False
def has_tunnel_collided():
return head['rect'].collidelist(tunnels)
def has_star_collided():
global stars, stars_collected, score
star_ind = head['rect'].collidelist([i['star_rect'] for i in stars])
if star_ind != -1:
del stars[star_ind]
stars_collected += 1
score += settings['star_reward']
render_score()
def grow(prev_head):
global tail, snake_body_img
new_segment = prev_head.copy()
rotation = prev_head['facing'].value - direction.value
snake_body_img = pygame.transform.rotate(snake_body_img, rotation)
tail.append(new_segment)
def get_segment():
return pygame.Rect(settings['starting_x'], settings['starting_y'], SEG_DIM, SEG_DIM)
def spawn_apple():
"""
Randomly generate an apple. The old apple will disappear and appear in a new position.
Rule 1: It cannot land on a walls or tunnels. Assume a collision and iteratively spawn until no collision is found.
Rule 2: It is allowed to collide with a snake allowing the snake to gain an easy catch.
:return: a new randomly generated apple.
"""
global apple
collided = True
while collided:
x = round(random.randrange(0, settings['display_width'] - settings['block_dim']) / settings['block_dim']) * settings['block_dim']
y = round(random.randrange(0, settings['display_height'] - settings['block_dim']) / settings['block_dim']) * settings['block_dim']
apple = pygame.Rect(x, y, settings['block_dim'], settings['block_dim'])
collided = False
for wall in walls:
if apple.colliderect(wall):
collided = True
return apple
def spawn_star():
if settings['stars_on']:
if settings['star_probability'] > random.random():
collision = True
while collision:
x = round(random.randrange(0, settings['display_width'] - settings['block_dim']) / settings['block_dim']) * settings['block_dim']
y = round(random.randrange(0, settings['display_height'] - settings['block_dim']) / settings['block_dim']) * settings['block_dim']
star = pygame.Rect(x, y, settings['block_dim'], settings['block_dim'])
collision = False
if star.collidelist(tunnels) != -1 or star.collidelist(walls) != -1 or star.colliderect(apple):
collision = True
stars.append({'star_rect': star, 'countdown': settings['star_fade_steps']})
def fade_stars():
for star in stars:
star['countdown'] -= 1
if star['countdown'] == 0:
stars.remove(star)
def random_color():
colors = ['green', 'yellow', 'orange', 'purple', 'pink']
return colors[random.randrange(len(colors))]
def get_text_object(text, color, large_font=False):
if large_font:
text_surf = title_font.render(text, True, color)
else:
text_surf = default_font.render(text, True, color)
return text_surf, text_surf.get_rect()
def display_message(message, color, large_font=False, y_displace=0):
text_surf, text_rect = get_text_object(message, color, large_font)
text_rect.center = (settings['display_width'] / 2, settings['display_height'] / 2 + y_displace)
display.blit(text_surf, text_rect)
def render_score():
text = score_font.render("Score: " + str(score) +
" Stars collected: " + str(stars_collected) +
" Apples ate: " + str(apples_ate) +
" Tunnels burrowed: " + str(tunnels_burrowed), True, pygame.Color('green'))
display.blit(text, [0, 0])
def render():
global head, tail, display, wall_img, walls, snake_head_img
display.fill(settings['background_color'])
display.blit(snake_head_img, head['rect'])
display.blit(apple_img, apple)
for segment in tail:
img = orientate_snake(snake_body_img, segment)
display.blit(img, segment['rect'])
for wall in walls:
start_x = wall.left
start_y = wall.top
end_x = wall.left + wall.width
end_y = wall.top + wall.height
for i in range(start_x, end_x, settings['block_dim']):
for j in range(start_y, end_y, settings['block_dim']):
block = pygame.Rect(i, j, settings['block_dim'], settings['block_dim'])
display.blit(wall_img, block)
for tunnel in tunnels:
display.fill(settings['tunnel_color'], tunnel)
for star in stars:
display.blit(star_img, star['star_rect'])
render_score()
pygame.display.update()
def intro_screen():
global display
intro = True
done = False
while intro:
display.fill(settings['background_color'])
display_message("Welcome to Snake", pygame.Color('green'), large_font=True, y_displace=-150)
display_message("- Use the arrow buttons to move", pygame.Color('blue'), y_displace=-60)
display_message("- Eat the apples to grow!", pygame.Color('blue'), y_displace=-20)
display_message("- Avoid walls, edges and yourself!", pygame.Color('blue'), y_displace=20)
display_message("- Collect stars for points", pygame.Color('blue'), y_displace=60)
display_message("- Burrow tunnels at your own risk!!!", pygame.Color('blue'), y_displace=100)
display_message(" optional features: walls || tunnels || stars", pygame.Color('purple'), y_displace=170)
display_message("- press ENTER to continue or SPACE to exit game", pygame.Color(random_color()), y_displace=200)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
return done
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
done = False
return done
elif event.key == pygame.K_SPACE:
done = True
return done
"""
GAME LOOP
"""
def game_loop(done=False):
global direction
game_over = False
clock = pygame.time.Clock()
while not done:
if game_over:
while game_over:
display.fill(settings['background_color'])
display_message("GAME OVER", pygame.Color('red'), True, -60)
display_message("Press ENTER to play again or SPACE to quit", pygame.Color('black'), False, 50)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
game_over = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
reset(settings)
game_over = False
elif event.key == pygame.K_SPACE:
game_over = False
done = True
render()
if settings['agent_hook']:
pygame.event.post(simple_greedy_agent.act(
head['rect'], apple, settings['block_dim'], facing, tail
))
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
print(event)
if event.key == pygame.K_UP:
direction = Directions.UP
elif event.key == pygame.K_RIGHT:
direction = Directions.RIGHT
elif event.key == pygame.K_DOWN:
direction = Directions.DOWN
elif event.key == pygame.K_LEFT:
direction = Directions.LEFT
temp_head = dict()
temp_head['rect'] = head['rect'].copy()
temp_head['facing'] = head['facing']
move_head(direction)
if has_wall_collided() or has_self_collided():
game_over = True
if has_apple_collided():
grow(temp_head)
else:
tunnel_ind = has_tunnel_collided()
has_star_collided()
if tunnel_ind >= 0:
burrow_tunnel(tunnel_ind)
move_tail(temp_head)
if head['rect'].left < 0 or head['rect'].left >= settings['display_width'] \
or head['rect'].top < 0 or head['rect'].top >= settings[
'display_height']:
if settings['auto_reset']:
display_message("YOU LOSE... Resetting game", pygame.Color('red'))
reset(settings)
else:
game_over = True
spawn_star()
fade_stars()
clock.tick(10)
reset(settings, first_play=True)
done = intro_screen()
game_loop(done)
pygame.quit()
quit()