-
Notifications
You must be signed in to change notification settings - Fork 0
/
tetrisSearchAgent.py
65 lines (58 loc) · 2.21 KB
/
tetrisSearchAgent.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
import pygame, sys
import tetris
from tetris import TetrisApp
import time
import TetrisSearch
class SearchAgent():
#Get the search function from its name
def __init__(self, fn = "breadthFirstSearch"):
if fn not in dir(TetrisSearch):
raise AttributeError, fn + " is not in TetrisSearch.py."
func = getattr(TetrisSearch, fn)
self.searchFunction = func
def registerInitialState(self, state):
"""
Agent sees layout of game for first time
Compute path to goal and store in local variable
state = a GameState object (TetrisSearch.py)
"""
if self.searchFunction == None: raise Exception, "No search function provided for SearchAgent"
startTime = time.time()
problem = self.searchType(state)
self.actions = self.searchFunction(problem)
print("Path found in %.1f seconds" % (time.time() - startTime))
def getAction(self, state):
"""
Returns the next action in the path chosen earlier (in
registerInitialState). Returns gameover if no more actions to take.
state = a GameState object (TetrisSearch.py)
"""
dont_burn_my_cpu = pygame.time.Clock()
key_actions = {
'ESCAPE': state.quit,
'LEFT': lambda:state.move(-1),
'RIGHT': lambda:state.move(+1),
'DOWN': lambda:state.drop(True),
'UP': state.rotate_stone,
'p': state.toggle_pause,
'SPACE': state.start_game,
'RETURN': state.insta_drop
}
self.actionIndex = 0
i = self.actionIndex
self.actionIndex += 1
for event in pygame.eveng.get():
if event.type == pygame.USEREVENT+1:
self.drop(False)
elif event.type == pygame.QUIT:
self.quit()
elif i < len(self.actions):
for key in key_actions:
if self.actions[i] == eval(key):
return key_actions[key]()
if event.type == pygame.USEREVENT+1:
self.drop(False)
elif event.type == pygame.QUIT:
self.quit()
else:
return TetrisApp.quit()