Ziel ist ein Programm, welches ein Labyrinth erstellt und es dem Spieler erlaubt, sich im Labyrinth zu bewegen. Er gewinnt, wenn er den Ausgang erreicht.

maze_fertig.py 6.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import random
  4. import Tkinter as tk
  5. import sys
  6. class Application(tk.Frame):
  7. def __init__(self, width=21, height=21, size=10):
  8. tk.Frame.__init__(self)
  9. self.maze = Maze(width, height)
  10. self.size = size
  11. self.steps = 0
  12. self.grid()
  13. self.create_widgets()
  14. self.draw_maze()
  15. self.create_events()
  16. def create_widgets(self):
  17. width = self.maze.width * self.size
  18. height = self.maze.height * self.size
  19. self.canvas = tk.Canvas(self, width=width, height=height)
  20. self.canvas.grid()
  21. self.status = tk.Label(self)
  22. self.status.grid()
  23. def draw_maze(self):
  24. for i, row in enumerate(self.maze.maze):
  25. for j, col in enumerate(row):
  26. x0 = j * self.size
  27. y0 = i * self.size
  28. x1 = x0 + self.size
  29. y1 = y0 + self.size
  30. color = self.get_color(x=j, y=i)
  31. id = self.canvas.create_rectangle(x0, y0, x1, y1, width=0, fill=color)
  32. if self.maze.start_cell == (j, i):
  33. self.cell = id
  34. self.canvas.tag_raise(self.cell)
  35. self.status.config(text='minimale Anzahl Schritte: %d' % self.maze.steps)
  36. def create_events(self):
  37. self.canvas.bind_all('<KeyPress-Up>', self.move_cell)
  38. self.canvas.bind_all('<KeyPress-Down>', self.move_cell)
  39. self.canvas.bind_all('<KeyPress-Left>', self.move_cell)
  40. self.canvas.bind_all('<KeyPress-Right>', self.move_cell)
  41. def move_cell(self, event):
  42. if event.keysym == 'Up':
  43. if self.check_move(0, -1):
  44. self.canvas.move(self.cell, 0, -self.size)
  45. self.steps += 1
  46. if event.keysym == 'Down':
  47. if self.check_move(0, 1):
  48. self.canvas.move(self.cell, 0, self.size)
  49. self.steps += 1
  50. if event.keysym == 'Left':
  51. if self.check_move(-1, 0):
  52. self.canvas.move(self.cell, -self.size, 0)
  53. self.steps += 1
  54. if event.keysym == 'Right':
  55. if self.check_move(1, 0):
  56. self.canvas.move(self.cell, self.size, 0)
  57. self.steps += 1
  58. args = (self.steps, self.maze.steps)
  59. self.status.config(text='Schritte: %d/%d' % args)
  60. self.check_status()
  61. def check_move(self, x, y):
  62. x0, y0 = self.get_cell_coords()
  63. x1 = x0 + x
  64. y1 = y0 + y
  65. return self.maze.maze[y1][x1] == 0
  66. def get_cell_coords(self):
  67. position = self.canvas.coords(self.cell)
  68. x = int(position[0] / self.size)
  69. y = int(position[1] / self.size)
  70. return (x, y)
  71. def check_status(self):
  72. if self.maze.exit_cell == self.get_cell_coords():
  73. args = (self.steps, self.maze.steps)
  74. self.status.config(text='Resultat: %d/%d Schritte!' % args)
  75. def get_color(self, x, y):
  76. if self.maze.start_cell == (x, y):
  77. return 'red'
  78. if self.maze.exit_cell == (x, y):
  79. return 'green'
  80. if self.maze.maze[y][x] == 1:
  81. return 'black'
  82. class Maze(object):
  83. def __init__(self, width=21, height=21, exit_cell=(19,1), start_cell=(1,19)):
  84. self.width = width
  85. self.height = height
  86. self.exit_cell = exit_cell
  87. self.start_cell = start_cell
  88. self.create()
  89. def create(self):
  90. self.maze = [[1] * self.width for _ in range(self.height)]
  91. self.steps = None
  92. self.recursion_depth = None
  93. self._visited_cells = []
  94. self._visit_cell(self.exit_cell)
  95. def _visit_cell(self, cell, depth=0):
  96. x, y = cell
  97. self.maze[y][x] = 0
  98. self._visited_cells.append(cell)
  99. neighbors = self._get_neighbors(cell)
  100. random.shuffle(neighbors)
  101. for neighbor in neighbors:
  102. if not neighbor in self._visited_cells:
  103. self._remove_wall(cell, neighbor)
  104. self._visit_cell(neighbor, depth+1)
  105. self._update_start_cell(cell, depth)
  106. def _get_neighbors(self, cell):
  107. """
  108. Beispiel:
  109. Die Nachbarzellen von a sind b
  110. # # # # # # # # # # # # # #
  111. # # # b # # # # a # b # # #
  112. # # # # # # # # # # # # # #
  113. # b # a # b # # b # # # # #
  114. # # # # # # # # # # # # # #
  115. # # # b # # # # # # # # # #
  116. # # # # # # # # # # # # # #
  117. """
  118. x, y = cell
  119. neighbors = []
  120. # links
  121. if x - 2 > 0:
  122. neighbors.append((x-2, y))
  123. # rechts
  124. if x + 2 < self.width:
  125. neighbors.append((x+2, y))
  126. # hoch
  127. if y - 2 > 0:
  128. neighbors.append((x, y-2))
  129. # runter
  130. if y + 2 < self.height:
  131. neighbors.append((x, y+2))
  132. return neighbors
  133. def _remove_wall(self, cell, neighbor):
  134. """
  135. Entferne die Wand zwischen den beiden Zellen
  136. Beispiel:
  137. Die Wand zwischen a und b ist w
  138. # # # # #
  139. # # # # #
  140. # a w b #
  141. # # # # #
  142. # # # # #
  143. """
  144. x0, y0 = cell
  145. x1, y1 = neighbor
  146. # vertikal
  147. if x0 == x1:
  148. x = x0
  149. y = (y0 + y1) / 2
  150. # horizontal
  151. if y0 == y1:
  152. x = (x0 + x1) / 2
  153. y = y0
  154. self.maze[y][x] = 0
  155. def _update_start_cell(self, cell, depth):
  156. if depth > self.recursion_depth:
  157. self.recursion_depth = depth
  158. self.start_cell = cell
  159. self.steps = depth * 2
  160. def show(self, verbose=False):
  161. MAP = {0: ' ', # Durchgang
  162. 1: '#', # Wand
  163. 2: 'B', # Ausgang
  164. 3: 'A', # Start
  165. }
  166. x0, y0 = self.exit_cell
  167. self.maze[y0][x0] = 2
  168. x1, y1 = self.start_cell
  169. self.maze[y1][x1] = 3
  170. for row in self.maze:
  171. print ' '.join([MAP[col] for col in row])
  172. if verbose:
  173. print "Steps from A to B:", self.steps
  174. if __name__ == '__main__':
  175. from optparse import OptionParser
  176. parser = OptionParser(description="Random maze game")
  177. parser.add_option('-W', '--width', type=int, default=21,
  178. help="maze width (default 21)")
  179. parser.add_option('-H', '--height', type=int, default=21,
  180. help="maze height (default 21)")
  181. parser.add_option('-s', '--size', type=int, default=10,
  182. help="cell size (default 10)")
  183. args, _ = parser.parse_args()
  184. for arg in ('width', 'height'):
  185. if getattr(args, arg) % 2 == 0:
  186. setattr(args, arg, getattr(args, arg) + 1)
  187. print "Warning: %s muss ungerade sein, benutze %d stattdessen" % \
  188. (arg, getattr(args, arg))
  189. sys.setrecursionlimit(5000)
  190. app = Application(args.width, args.height, args.size)
  191. app.master.title('Maze game')
  192. app.mainloop()