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 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #erstellt von Alexander Teubert und Michelle Piras /MT2016
  4. #MAZE GAME
  5. #klassisches Labyrinth Spiel. Du musst das Ziel finden. Die Waende sind nicht begehbar. Mit Hilfe der Pfeiltasten bewegst du dich fort.
  6. #IMPORTIEREN
  7. import random
  8. import Tkinter as tk
  9. import sys
  10. #IMPLEMENTIERUNG IN TKINTER
  11. class Application(tk.Frame):
  12. def __init__(self, width=21, height=21, size=10): #Erstellung des Rahmens vom Maze
  13. tk.Frame.__init__(self) #hier werden alle weiteren Funktionen initiiert
  14. self.maze = Maze(width, height)
  15. self.size = size
  16. self.steps = 0
  17. self.grid()
  18. self.create_widgets()
  19. self.draw_maze()
  20. self.create_events()
  21. def create_widgets(self):
  22. width = self.maze.width * self.size
  23. height = self.maze.height * self.size
  24. self.canvas = tk.Canvas(self, width=width, height=height)
  25. self.canvas.grid()
  26. self.status = tk.Label(self)
  27. self.status.grid()
  28. def draw_maze(self): #das unten generierte Maze wird hier nun grafisch umgesetzt
  29. for i, row in enumerate(self.maze.maze):
  30. for j, col in enumerate(row):
  31. x0 = j * self.size
  32. y0 = i * self.size
  33. x1 = x0 + self.size
  34. y1 = y0 + self.size
  35. color = self.get_color(x=j, y=i)
  36. id = self.canvas.create_rectangle(x0, y0, x1, y1, width=0, fill=color) #rectangle=Rechteck. Das Maze besteht aus Rechtecken(Quadraten)
  37. if self.maze.start_cell == (j, i):
  38. self.cell = id
  39. self.canvas.tag_raise(self.cell) #self.cell wird an die Spitze des canvas stacks gehoben
  40. self.status.config(text='minimale Anzahl Schritte: %d' % self.maze.steps)
  41. #STEUERUNG
  42. def create_events(self): #bind <- Beteatigung einer Taste ruft einen callback hervor.
  43. self.canvas.bind_all('<KeyPress-Up>', self.move_cell) #der callback ist die Bewegung des Quadrats
  44. self.canvas.bind_all('<KeyPress-Down>', self.move_cell) # bind bindet ein event an einen callback
  45. self.canvas.bind_all('<KeyPress-Left>', self.move_cell)
  46. self.canvas.bind_all('<KeyPress-Right>', self.move_cell)
  47. def move_cell(self, event):
  48. if event.keysym == 'Up': #keysym ermoeglicht nur events ueber das Keyboard
  49. if self.check_move(0, -1): #es sind nur Eingaben uebers Keyboard moeglich
  50. self.canvas.move(self.cell, 0, -self.size)
  51. self.steps += 1
  52. if event.keysym == 'Down':
  53. if self.check_move(0, 1):
  54. self.canvas.move(self.cell, 0, self.size)
  55. self.steps += 1
  56. if event.keysym == 'Left':
  57. if self.check_move(-1, 0):
  58. self.canvas.move(self.cell, -self.size, 0)
  59. self.steps += 1
  60. if event.keysym == 'Right':
  61. if self.check_move(1, 0):
  62. self.canvas.move(self.cell, self.size, 0)
  63. self.steps += 1
  64. args = (self.steps, self.maze.steps)
  65. self.status.config(text='Schritte: %d/%d' % args)
  66. self.check_status()
  67. #UEBERPRUEFUNG DER KOORDINATEN
  68. def check_move(self, x, y):
  69. x0, y0 = self.get_cell_coords()
  70. x1 = x0 + x
  71. y1 = y0 + y
  72. return self.maze.maze[y1][x1] == 0
  73. def get_cell_coords(self):
  74. position = self.canvas.coords(self.cell) #coords gibt die Koordiaten der sich bewegenden Zelle(dir) wieder
  75. x = int(position[0] / self.size)
  76. y = int(position[1] / self.size)
  77. return (x, y)
  78. def check_status(self):
  79. if self.maze.exit_cell == self.get_cell_coords():
  80. args = (self.steps, self.maze.steps)
  81. self.status.config(text='Resultat: %d/%d Schritte!' % args)
  82. #FARBFESTLEGUNG
  83. def get_color(self, x, y):
  84. if self.maze.start_cell == (x, y):
  85. return 'red'
  86. if self.maze.exit_cell == (x, y):
  87. return 'green'
  88. if self.maze.maze[y][x] == 1:
  89. return 'black'
  90. #GENERIERUNG DES LABYRINTHS
  91. class Maze(object):
  92. def __init__(self, width=21, height=21, exit_cell=(19,1), start_cell=(1,19)): #Initierung des Rahmens des Maze, sowie Start und Ziel Festlegung
  93. self.width = width
  94. self.height = height
  95. self.exit_cell = exit_cell
  96. self.start_cell = start_cell
  97. self.create()
  98. def create(self):
  99. self.maze = [[1] * self.width for _ in range(self.height)]
  100. self.steps = None
  101. self.recursion_depth = None
  102. self._visited_cells = []
  103. self._visit_cell(self.exit_cell)
  104. def _visit_cell(self, cell, depth=0):
  105. x, y = cell
  106. self.maze[y][x] = 0
  107. self._visited_cells.append(cell)
  108. neighbors = self._get_neighbors(cell)
  109. random.shuffle(neighbors)
  110. for neighbor in neighbors:
  111. if not neighbor in self._visited_cells:
  112. self._remove_wall(cell, neighbor)
  113. self._visit_cell(neighbor, depth+1)
  114. self._update_start_cell(cell, depth)
  115. def _get_neighbors(self, cell): #Zur Generierung des Maze wird der Depth-first-search Algorithmus verwendet
  116. """
  117. Beispiel:
  118. Die Nachbarzellen von a sind b
  119. # # # # # # # # # # # # # #
  120. # # # b # # # # a # b # # #
  121. # # # # # # # # # # # # # #
  122. # b # a # b # # b # # # # #
  123. # # # # # # # # # # # # # #
  124. # # # b # # # # # # # # # #
  125. # # # # # # # # # # # # # #
  126. """
  127. x, y = cell
  128. neighbors = []
  129. # links
  130. if x - 2 > 0:
  131. neighbors.append((x-2, y))
  132. # rechts
  133. if x + 2 < self.width:
  134. neighbors.append((x+2, y))
  135. # hoch
  136. if y - 2 > 0:
  137. neighbors.append((x, y-2))
  138. # runter
  139. if y + 2 < self.height:
  140. neighbors.append((x, y+2))
  141. return neighbors
  142. def _remove_wall(self, cell, neighbor):
  143. """
  144. Entferne die Wand zwischen den beiden Zellen
  145. Beispiel:
  146. Die Wand zwischen a und b ist w
  147. # # # # #
  148. # # # # #
  149. # a w b #
  150. # # # # #
  151. # # # # #
  152. """
  153. x0, y0 = cell
  154. x1, y1 = neighbor
  155. # vertikal
  156. if x0 == x1:
  157. x = x0
  158. y = (y0 + y1) / 2
  159. # horizontal
  160. if y0 == y1:
  161. x = (x0 + x1) / 2
  162. y = y0
  163. self.maze[y][x] = 0
  164. def _update_start_cell(self, cell, depth):
  165. if depth > self.recursion_depth:
  166. self.recursion_depth = depth
  167. self.start_cell = cell
  168. self.steps = depth * 2
  169. def show(self, verbose=False):
  170. MAP = {0: ' ', # Durchgang
  171. 1: '#', # Wand
  172. 2: 'B', # Ausgang
  173. 3: 'A', # Start
  174. }
  175. x0, y0 = self.exit_cell
  176. self.maze[y0][x0] = 2
  177. x1, y1 = self.start_cell
  178. self.maze[y1][x1] = 3
  179. for row in self.maze:
  180. print ' '.join([MAP[col] for col in row])
  181. if verbose:
  182. print "Steps from A to B:", self.steps
  183. if __name__ == '__main__':
  184. from optparse import OptionParser
  185. parser = OptionParser(description="Random maze game")
  186. parser.add_option('-W', '--width', type=int, default=21,
  187. help="maze width (default 21)")
  188. parser.add_option('-H', '--height', type=int, default=21,
  189. help="maze height (default 21)")
  190. parser.add_option('-s', '--size', type=int, default=10,
  191. help="cell size (default 10)")
  192. args, _ = parser.parse_args()
  193. for arg in ('width', 'height'):
  194. if getattr(args, arg) % 2 == 0:
  195. setattr(args, arg, getattr(args, arg) + 1)
  196. print "Warning: %s muss ungerade sein, benutze %d stattdessen" % \
  197. (arg, getattr(args, arg))
  198. sys.setrecursionlimit(5000)
  199. app = Application(args.width, args.height, args.size)
  200. app.master.title('Maze game')
  201. app.mainloop()