-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearchsnake.py
More file actions
85 lines (68 loc) · 2.31 KB
/
Copy pathsearchsnake.py
File metadata and controls
85 lines (68 loc) · 2.31 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
from colors import Color
from gamestate import GameState
from searchproblem import PositionSearchProblem
from util import manhattanDistance
import pygame
import search
BOARD_SIZE = 25
NUMBER_OF_SEARCHES = 10 # Number of times snake will search for food
BLOCK_S = 10
pygame.init()
clock = pygame.time.Clock()
draw = pygame.draw
screen = pygame.display.set_mode((BOARD_SIZE*BLOCK_S, BOARD_SIZE*BLOCK_S))
pygame.display.set_caption("Search Snake")
if __name__ == '__main__':
# Set up game
snakePos = (2, 0)
foodPos = (3, 2)
board = []
for _ in range(BOARD_SIZE):
board.append([0]*BOARD_SIZE)
# Set up initial gamestate
game = GameState(snakePos, foodPos, board)
# Repeat search n times
for search_num in range(NUMBER_OF_SEARCHES):
# Get resulting path nodes from performing a search
problem = PositionSearchProblem(game)
#path_nodes = search.depthFirstSearch(problem)
#path_nodes = search.breadthFirstSearch(problem)
path_nodes = search.greedySearch(problem, lambda node: manhattanDistance(node.state, (game.food.x, game.food.y)))
# Print path nodes
'''
for node in path_nodes:
print(node)
'''
# Check if a path was found
if path_nodes is None:
print("Could not find path")
pygame.quit()
exit()
actions = [node.action for node in path_nodes]
for action in actions:
# Make call to pygame event and check if windows is closed
if pygame.QUIT in [event.type for event in pygame.event.get()]:
pygame.quit()
exit()
# Draw game board
screen.fill(Color.WHITE)
for tailPiece in game.player.tail:
draw.rect(screen, Color.RED, (BLOCK_S*tailPiece.x, BLOCK_S*tailPiece.y, BLOCK_S, BLOCK_S))
draw.rect(screen, Color.GREEN, (BLOCK_S*game.food.x, BLOCK_S*game.food.y, BLOCK_S, BLOCK_S))
pygame.display.update()
clock.tick(12)
# Move snake with chosen action
if action is not None:
game.frame_step(action)
# Draw game board one last time
screen.fill(Color.WHITE)
for tailPiece in game.player.tail:
draw.rect(screen, Color.RED, (BLOCK_S*tailPiece.x, BLOCK_S*tailPiece.y, BLOCK_S, BLOCK_S))
draw.rect(screen, Color.GREEN, (BLOCK_S*game.food.x, BLOCK_S*game.food.y, BLOCK_S, BLOCK_S))
pygame.display.update()
clock.tick(12)
print("%d food pellets eaten" % (search_num+1))
# Move food to continue game with new search
game.moveFood()
pygame.quit()
exit()