4 Коммиты a7837e221d ... e0035a891d

Автор SHA1 Сообщение Дата
  ateubert e0035a891d Merge branch 'master' of http://es-lab.de:60080/ateubert/Labventure лет назад: 7
  ateubert e8f8a935ba Grundgeruest. Random Maze wird generiert. лет назад: 7
  ateubert 894d63958b Grundgeruest. Ein Random Maze wird generiert. лет назад: 7
  ateubert cdbb811130 Grundgeruest. Random Maze wird generiert. лет назад: 7
3 измененных файлов с 487 добавлено и 0 удалено
  1. 225 0
      Maze_Labventure1.py
  2. 131 0
      Vorüberlegung_Maze.py
  3. 131 0
      Vorüberlegung_Maze1.py

+ 225 - 0
Maze_Labventure1.py

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

+ 131 - 0
Vorüberlegung_Maze.py

@@ -0,0 +1,131 @@
1
+#!/usr/bin/env python
2
+# -*- coding: utf-8 -*-
3
+
4
+import random
5
+
6
+
7
+class Maze(object):
8
+
9
+    def __init__(self, width=21, height=21, exit_cell=(1, 1)):
10
+        self.width = width
11
+        self.height = height
12
+        self.exit_cell = exit_cell
13
+        self.create()
14
+
15
+    def create(self):
16
+        self.maze = [[1] * self.width for _ in range(self.height)] 
17
+        self.start_cell = None
18
+        self.steps = None
19
+        self.recursion_depth = None
20
+        self._visited_cells = []
21
+        self._visit_cell(self.exit_cell)
22
+
23
+    def _visit_cell(self, cell, depth=0):
24
+        x, y = cell
25
+        self.maze[y][x] = 0 # Wand entfernen
26
+        self._visited_cells.append(cell)
27
+        neighbors = self._get_neighbors(cell)
28
+        random.shuffle(neighbors)
29
+        for neighbor in neighbors:
30
+            if not neighbor in self._visited_cells:
31
+                self._remove_wall(cell, neighbor)
32
+                self._visit_cell(neighbor, depth+1)
33
+        self._update_start_cell(cell, depth)
34
+
35
+    def _get_neighbors(self, cell):
36
+        """
37
+        Die benachbarten Zellen nehmen.
38
+        Beispiel:
39
+          b sind die benachbarten Zellen von a 
40
+          # # # # # # #     # # # # # # #
41
+          # # # b # # #     # a # b # # #
42
+          # # # # # # #     # # # # # # #
43
+          # b # a # b #     # b # # # # #
44
+          # # # # # # #     # # # # # # #
45
+          # # # b # # #     # # # # # # #
46
+          # # # # # # #     # # # # # # #
47
+        """
48
+        x, y = cell
49
+        neighbors = []
50
+
51
+        # Links
52
+        if x - 2 > 0:
53
+            neighbors.append((x-2, y))
54
+        # Rechts
55
+        if x + 2 < self.width:
56
+            neighbors.append((x+2, y))
57
+        # Hoch
58
+        if y - 2 > 0:
59
+            neighbors.append((x, y-2))
60
+        # Runter
61
+        if y + 2 < self.height:
62
+            neighbors.append((x, y+2))
63
+
64
+        return neighbors
65
+
66
+    def _remove_wall(self, cell, neighbor):
67
+        """
68
+        Entfernen der Wand zwischen zwei Zellen
69
+        Example:
70
+          gegeben sind die Zellen a und b
71
+          Die Wand dazwischen ist w
72
+          # # # # #
73
+          # # # # #
74
+          # a w b #
75
+          # # # # #
76
+          # # # # #
77
+        """
78
+        x0, y0 = cell
79
+        x1, y1 = neighbor
80
+        # Vertikal
81
+        if x0 == x1:
82
+            x = x0
83
+            y = (y0 + y1) / 2
84
+        # Horizontal
85
+        if y0 == y1:
86
+            x = (x0 + x1) / 2
87
+            y = y0
88
+        self.maze[y][x] = 0 # Wand entfernen
89
+
90
+    def _update_start_cell(self, cell, depth):
91
+        if depth > self.recursion_depth:
92
+            self.recursion_depth = depth
93
+            self.start_cell = cell
94
+            self.steps = depth * 2 # Wand + Zelle
95
+
96
+    def show(self, verbose=False):
97
+        MAP = {0: ' ', # Durchgang
98
+               1: '#', # Wand
99
+               2: 'B', # Ausgang
100
+               3: 'A', # Start
101
+              }
102
+        x0, y0 = self.exit_cell
103
+        self.maze[y0][x0] = 2
104
+        x1, y1 = self.start_cell
105
+        self.maze[y1][x1] = 3
106
+        for row in self.maze:
107
+            print ' '.join([MAP[col] for col in row])
108
+        if verbose:
109
+            print "Schritte von A nach B:", self.steps
110
+
111
+
112
+if __name__ == '__main__':
113
+
114
+    from optparse import OptionParser
115
+    parser = OptionParser(description="Maze random generator")
116
+    parser.add_option('-W', '--width', type=int, default=21,
117
+                      help="maze width (muss ungerade sein)")
118
+    parser.add_option('-H', '--height', type=int, default=21,
119
+                      help="maze height (muss ungerade sein)")
120
+    parser.add_option('-v', '--verbose', action='store_true',
121
+                      help="zeigt Schritte von Start bis Ziel")
122
+    args, _ = parser.parse_args()
123
+
124
+    for arg in ('width', 'height'):
125
+        if getattr(args, arg) % 2 == 0:
126
+            setattr(args, arg, getattr(args, arg) + 1)
127
+            print "Warnung: %s muss ungerade sein, benutze %d stattdessen" % (arg, getattr(args, arg))
128
+
129
+    exit_cell = (args.width-2, args.height-2)
130
+    maze = Maze(args.width, args.height, exit_cell)
131
+    maze.show(args.verbose)

+ 131 - 0
Vorüberlegung_Maze1.py

@@ -0,0 +1,131 @@
1
+#!/usr/bin/env python
2
+# -*- coding: utf-8 -*-
3
+
4
+import random
5
+
6
+
7
+class Maze(object):
8
+
9
+    def __init__(self, width=21, height=21, exit_cell=(1, 1)):
10
+        self.width = width
11
+        self.height = height
12
+        self.exit_cell = exit_cell
13
+        self.create()
14
+
15
+    def create(self):
16
+        self.maze = [[1] * self.width for _ in range(self.height)] 
17
+        self.start_cell = None
18
+        self.steps = None
19
+        self.recursion_depth = None
20
+        self._visited_cells = []
21
+        self._visit_cell(self.exit_cell)
22
+
23
+    def _visit_cell(self, cell, depth=0):
24
+        x, y = cell
25
+        self.maze[y][x] = 0 # Wand entfernen
26
+        self._visited_cells.append(cell)
27
+        neighbors = self._get_neighbors(cell)
28
+        random.shuffle(neighbors)
29
+        for neighbor in neighbors:
30
+            if not neighbor in self._visited_cells:
31
+                self._remove_wall(cell, neighbor)
32
+                self._visit_cell(neighbor, depth+1)
33
+        self._update_start_cell(cell, depth)
34
+
35
+    def _get_neighbors(self, cell):
36
+        """
37
+        Die benachbarten Zellen nehmen.
38
+        Beispiel:
39
+          b sind die benachbarten Zellen von a 
40
+          # # # # # # #     # # # # # # #
41
+          # # # b # # #     # a # b # # #
42
+          # # # # # # #     # # # # # # #
43
+          # b # a # b #     # b # # # # #
44
+          # # # # # # #     # # # # # # #
45
+          # # # b # # #     # # # # # # #
46
+          # # # # # # #     # # # # # # #
47
+        """
48
+        x, y = cell
49
+        neighbors = []
50
+
51
+        # Links
52
+        if x - 2 > 0:
53
+            neighbors.append((x-2, y))
54
+        # Rechts
55
+        if x + 2 < self.width:
56
+            neighbors.append((x+2, y))
57
+        # Hoch
58
+        if y - 2 > 0:
59
+            neighbors.append((x, y-2))
60
+        # Runter
61
+        if y + 2 < self.height:
62
+            neighbors.append((x, y+2))
63
+
64
+        return neighbors
65
+
66
+    def _remove_wall(self, cell, neighbor):
67
+        """
68
+        Entfernen der Wand zwischen zwei Zellen
69
+        Example:
70
+          gegeben sind die Zellen a und b
71
+          Die Wand dazwischen ist w
72
+          # # # # #
73
+          # # # # #
74
+          # a w b #
75
+          # # # # #
76
+          # # # # #
77
+        """
78
+        x0, y0 = cell
79
+        x1, y1 = neighbor
80
+        # Vertikal
81
+        if x0 == x1:
82
+            x = x0
83
+            y = (y0 + y1) / 2
84
+        # Horizontal
85
+        if y0 == y1:
86
+            x = (x0 + x1) / 2
87
+            y = y0
88
+        self.maze[y][x] = 0 # Wand entfernen
89
+
90
+    def _update_start_cell(self, cell, depth):
91
+        if depth > self.recursion_depth:
92
+            self.recursion_depth = depth
93
+            self.start_cell = cell
94
+            self.steps = depth * 2 # Wand + Zelle
95
+
96
+    def show(self, verbose=False):
97
+        MAP = {0: ' ', # Durchgang
98
+               1: '#', # Wand
99
+               2: 'B', # Ausgang
100
+               3: 'A', # Start
101
+              }
102
+        x0, y0 = self.exit_cell
103
+        self.maze[y0][x0] = 2
104
+        x1, y1 = self.start_cell
105
+        self.maze[y1][x1] = 3
106
+        for row in self.maze:
107
+            print ' '.join([MAP[col] for col in row])
108
+        if verbose:
109
+            print "Schritte von A nach B:", self.steps
110
+
111
+
112
+if __name__ == '__main__':
113
+
114
+    from optparse import OptionParser
115
+    parser = OptionParser(description="Maze random generator")
116
+    parser.add_option('-W', '--width', type=int, default=21,
117
+                      help="maze width (muss ungerade sein)")
118
+    parser.add_option('-H', '--height', type=int, default=21,
119
+                      help="maze height (muss ungerade sein)")
120
+    parser.add_option('-v', '--verbose', action='store_true',
121
+                      help="zeigt Schritte von Start bis Ziel")
122
+    args, _ = parser.parse_args()
123
+
124
+    for arg in ('width', 'height'):
125
+        if getattr(args, arg) % 2 == 0:
126
+            setattr(args, arg, getattr(args, arg) + 1)
127
+            print "Warnung: %s muss ungerade sein, benutze %d stattdessen" % (arg, getattr(args, arg))
128
+
129
+    exit_cell = (args.width-2, args.height-2)
130
+    maze = Maze(args.width, args.height, exit_cell)
131
+    maze.show(args.verbose)