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_Labventure1.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='mininale Anzahl an Schritten: %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=' Du brauchtest %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=(21, 1)):
  84. self.width = width
  85. self.height = height
  86. self.exit_cell = exit_cell
  87. self.create()
  88. def create(self):
  89. self.maze = [[1] * self.width for _ in range(self.height)]
  90. self.start_cell = None
  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 # Wand ersetzen
  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. Entfernen der Wand zwischen den Zellen
  136. Beispiel:
  137. gegeben sind die Zellen a und b
  138. Die Wand dazwischen ist w
  139. # # # # #
  140. # # # # #
  141. # a w b #
  142. # # # # #
  143. # # # # #
  144. """
  145. x0, y0 = cell
  146. x1, y1 = neighbor
  147. # Vertikal
  148. if x0 == x1:
  149. x = x0
  150. y = (y0 + y1) / 2
  151. # Horizontal
  152. if y0 == y1:
  153. x = (x0 + x1) / 2
  154. y = y0
  155. self.maze[y][x] = 0 # Wand entfernen
  156. def _update_start_cell(self, cell, depth):
  157. if depth > self.recursion_depth:
  158. self.recursion_depth = depth
  159. self.start_cell = cell
  160. self.steps = depth * 2 # Wand + Zelle
  161. def show(self, verbose=False):
  162. MAP = {0: ' ', # Durchgang
  163. 1: '#', # Wand
  164. 2: 'B', # Ausgang
  165. 3: 'A', # Start
  166. }
  167. x0, y0 = self.exit_cell
  168. self.maze[y0][x0] = 2
  169. x1, y1 = self.start_cell
  170. self.maze[y1][x1] = 3
  171. for row in self.maze:
  172. print ' '.join([MAP[col] for col in row])
  173. if verbose:
  174. print "Steps from A to B:", self.steps
  175. if __name__ == '__main__':
  176. from optparse import OptionParser
  177. parser = OptionParser(description="Random maze game")
  178. parser.add_option('-W', '--width', type=int, default=21,
  179. help="maze width (default 21)")
  180. parser.add_option('-H', '--height', type=int, default=21,
  181. help="maze height (default 21)")
  182. parser.add_option('-s', '--size', type=int, default=10,
  183. help="cell size (default 10)")
  184. args, _ = parser.parse_args()
  185. for arg in ('width', 'height'):
  186. if getattr(args, arg) % 2 == 0:
  187. setattr(args, arg, getattr(args, arg) + 1)
  188. print "Warnung: %s muss ungerade sein, benutze %d stattdessen" % \
  189. (arg, getattr(args, arg))
  190. sys.setrecursionlimit(5000)
  191. app = Application(args.width, args.height, args.size)
  192. app.master.title('Labventure')
  193. app.mainloop()