Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

layout.py 5.7 KB

You have to be logged in to leave a comment. Sign In
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
  1. # layout.py
  2. # ---------
  3. # Licensing Information: Please do not distribute or publish solutions to this
  4. # project. You are free to use and extend these projects for educational
  5. # purposes. The Pacman AI projects were developed at UC Berkeley, primarily by
  6. # John DeNero (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
  7. # For more info, see http://inst.eecs.berkeley.edu/~cs188/sp09/pacman.html
  8. from utilities.util import manhattanDistance
  9. from utilities.game import Grid
  10. import os
  11. import random
  12. VISIBILITY_MATRIX_CACHE = {}
  13. class Layout:
  14. """
  15. A Layout manages the static information about the game board.
  16. """
  17. def __init__(self, layoutText):
  18. self.width = len(layoutText[0])
  19. self.height = len(layoutText)
  20. self.walls = Grid(self.width, self.height, False)
  21. self.food = Grid(self.width, self.height, False)
  22. self.capsules = []
  23. self.agentPositions = []
  24. self.numGhosts = 0
  25. self.processLayoutText(layoutText)
  26. self.layoutText = layoutText
  27. # self.initializeVisibilityMatrix()
  28. def getNumGhosts(self):
  29. return self.numGhosts
  30. def initializeVisibilityMatrix(self):
  31. global VISIBILITY_MATRIX_CACHE
  32. if reduce(str.__add__, self.layoutText) not in VISIBILITY_MATRIX_CACHE:
  33. from utilities.game import Directions
  34. vecs = [(-0.5, 0), (0.5, 0), (0, -0.5), (0, 0.5)]
  35. dirs = [Directions.NORTH, Directions.SOUTH, Directions.WEST, Directions.EAST]
  36. vis = Grid(self.width, self.height,
  37. {Directions.NORTH: set(), Directions.SOUTH: set(), Directions.EAST: set(),
  38. Directions.WEST: set(), Directions.STOP: set()})
  39. for x in range(self.width):
  40. for y in range(self.height):
  41. if self.walls[x][y] == False:
  42. for vec, direction in zip(vecs, dirs):
  43. dx, dy = vec
  44. nextx, nexty = x + dx, y + dy
  45. while (nextx + nexty) != int(nextx) + int(nexty) or not \
  46. self.walls[int(nextx)][int(nexty)]:
  47. vis[x][y][direction].add((nextx, nexty))
  48. nextx, nexty = x + dx, y + dy
  49. self.visibility = vis
  50. VISIBILITY_MATRIX_CACHE[reduce(str.__add__, self.layoutText)] = vis
  51. else:
  52. self.visibility = VISIBILITY_MATRIX_CACHE[reduce(str.__add__, self.layoutText)]
  53. def isWall(self, pos):
  54. x, col = pos
  55. return self.walls[x][col]
  56. def getRandomLegalPosition(self):
  57. x = random.choice(range(self.width))
  58. y = random.choice(range(self.height))
  59. while self.isWall((x, y)):
  60. x = random.choice(range(self.width))
  61. y = random.choice(range(self.height))
  62. return (x, y)
  63. def getRandomCorner(self):
  64. poses = [(1, 1), (1, self.height - 2), (self.width - 2, 1),
  65. (self.width - 2, self.height - 2)]
  66. return random.choice(poses)
  67. def getFurthestCorner(self, pacPos):
  68. poses = [(1, 1), (1, self.height - 2), (self.width - 2, 1),
  69. (self.width - 2, self.height - 2)]
  70. dist, pos = max([(manhattanDistance(p, pacPos), p) for p in poses])
  71. return pos
  72. def isVisibleFrom(self, ghostPos, pacPos, pacDirection):
  73. row, col = [int(x) for x in pacPos]
  74. return ghostPos in self.visibility[row][col][pacDirection]
  75. def __str__(self):
  76. return "\n".join(self.layoutText)
  77. def deepCopy(self):
  78. return Layout(self.layoutText[:])
  79. def processLayoutText(self, layoutText):
  80. """
  81. Coordinates are flipped from the input format to the (x,y) convention here
  82. The shape of the maze. Each character
  83. represents a different type of object.
  84. % - Wall
  85. . - Food
  86. o - Capsule
  87. G - Ghost
  88. P - Pacman
  89. Other characters are ignored.
  90. """
  91. maxY = self.height - 1
  92. for y in range(self.height):
  93. for x in range(self.width):
  94. layoutChar = layoutText[maxY - y][x]
  95. self.processLayoutChar(x, y, layoutChar)
  96. self.agentPositions.sort()
  97. self.agentPositions = [(i == 0, pos) for i, pos in self.agentPositions]
  98. def processLayoutChar(self, x, y, layoutChar):
  99. if layoutChar == '%':
  100. self.walls[x][y] = True
  101. elif layoutChar == '.':
  102. self.food[x][y] = True
  103. elif layoutChar == 'o':
  104. self.capsules.append((x, y))
  105. elif layoutChar == 'P':
  106. self.agentPositions.append((0, (x, y)))
  107. elif layoutChar in ['G']:
  108. self.agentPositions.append((1, (x, y)))
  109. self.numGhosts += 1
  110. elif layoutChar in ['1', '2', '3', '4']:
  111. self.agentPositions.append((int(layoutChar), (x, y)))
  112. self.numGhosts += 1
  113. def getLayout(name, back=2):
  114. if name.endswith('.lay'):
  115. layout = tryToLoad('utilities/layouts/' + name)
  116. if layout == None: layout = tryToLoad(name)
  117. else:
  118. layout = tryToLoad('utilities/layouts/' + name + '.lay')
  119. if layout == None: layout = tryToLoad(name + '.lay')
  120. if layout == None and back >= 0:
  121. curdir = os.path.abspath('.')
  122. os.chdir('..')
  123. layout = getLayout(name, back - 1)
  124. os.chdir(curdir)
  125. return layout
  126. def tryToLoad(fullname):
  127. if (not os.path.exists(fullname)): return None
  128. f = open(fullname)
  129. try:
  130. return Layout([line.strip() for line in f])
  131. finally:
  132. f.close()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...