-
Notifications
You must be signed in to change notification settings - Fork 13
/
sokoban.py
executable file
·318 lines (291 loc) · 11.8 KB
/
sokoban.py
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
#!../bin/python
import sys
import pygame
import string
import Queue
class game:
def is_valid_value(self,char):
if ( char == ' ' or #floor
char == '#' or #wall
char == '@' or #worker on floor
char == '.' or #dock
char == '*' or #box on dock
char == '$' or #box
char == '+' ): #worker on dock
return True
else:
return False
def __init__(self,filename,level):
self.queue = Queue.LifoQueue()
self.matrix = []
# if level < 1 or level > 50:
if level < 1:
print "ERROR: Level "+str(level)+" is out of range"
sys.exit(1)
else:
file = open(filename,'r')
level_found = False
for line in file:
row = []
if not level_found:
if "Level "+str(level) == line.strip():
level_found = True
else:
if line.strip() != "":
row = []
for c in line:
if c != '\n' and self.is_valid_value(c):
row.append(c)
elif c == '\n': #jump to next row when newline
continue
else:
print "ERROR: Level "+str(level)+" has invalid value "+c
sys.exit(1)
self.matrix.append(row)
else:
break
def load_size(self):
x = 0
y = len(self.matrix)
for row in self.matrix:
if len(row) > x:
x = len(row)
return (x * 32, y * 32)
def get_matrix(self):
return self.matrix
def print_matrix(self):
for row in self.matrix:
for char in row:
sys.stdout.write(char)
sys.stdout.flush()
sys.stdout.write('\n')
def get_content(self,x,y):
return self.matrix[y][x]
def set_content(self,x,y,content):
if self.is_valid_value(content):
self.matrix[y][x] = content
else:
print "ERROR: Value '"+content+"' to be added is not valid"
def worker(self):
x = 0
y = 0
for row in self.matrix:
for pos in row:
if pos == '@' or pos == '+':
return (x, y, pos)
else:
x = x + 1
y = y + 1
x = 0
def can_move(self,x,y):
return self.get_content(self.worker()[0]+x,self.worker()[1]+y) not in ['#','*','$']
def next(self,x,y):
return self.get_content(self.worker()[0]+x,self.worker()[1]+y)
def can_push(self,x,y):
return (self.next(x,y) in ['*','$'] and self.next(x+x,y+y) in [' ','.'])
def is_completed(self):
for row in self.matrix:
for cell in row:
if cell == '$':
return False
return True
def move_box(self,x,y,a,b):
# (x,y) -> move to do
# (a,b) -> box to move
current_box = self.get_content(x,y)
future_box = self.get_content(x+a,y+b)
if current_box == '$' and future_box == ' ':
self.set_content(x+a,y+b,'$')
self.set_content(x,y,' ')
elif current_box == '$' and future_box == '.':
self.set_content(x+a,y+b,'*')
self.set_content(x,y,' ')
elif current_box == '*' and future_box == ' ':
self.set_content(x+a,y+b,'$')
self.set_content(x,y,'.')
elif current_box == '*' and future_box == '.':
self.set_content(x+a,y+b,'*')
self.set_content(x,y,'.')
def unmove(self):
if not self.queue.empty():
movement = self.queue.get()
if movement[2]:
current = self.worker()
self.move(movement[0] * -1,movement[1] * -1, False)
self.move_box(current[0]+movement[0],current[1]+movement[1],movement[0] * -1,movement[1] * -1)
else:
self.move(movement[0] * -1,movement[1] * -1, False)
def move(self,x,y,save):
if self.can_move(x,y):
current = self.worker()
future = self.next(x,y)
if current[2] == '@' and future == ' ':
self.set_content(current[0]+x,current[1]+y,'@')
self.set_content(current[0],current[1],' ')
if save: self.queue.put((x,y,False))
elif current[2] == '@' and future == '.':
self.set_content(current[0]+x,current[1]+y,'+')
self.set_content(current[0],current[1],' ')
if save: self.queue.put((x,y,False))
elif current[2] == '+' and future == ' ':
self.set_content(current[0]+x,current[1]+y,'@')
self.set_content(current[0],current[1],'.')
if save: self.queue.put((x,y,False))
elif current[2] == '+' and future == '.':
self.set_content(current[0]+x,current[1]+y,'+')
self.set_content(current[0],current[1],'.')
if save: self.queue.put((x,y,False))
elif self.can_push(x,y):
current = self.worker()
future = self.next(x,y)
future_box = self.next(x+x,y+y)
if current[2] == '@' and future == '$' and future_box == ' ':
self.move_box(current[0]+x,current[1]+y,x,y)
self.set_content(current[0],current[1],' ')
self.set_content(current[0]+x,current[1]+y,'@')
if save: self.queue.put((x,y,True))
elif current[2] == '@' and future == '$' and future_box == '.':
self.move_box(current[0]+x,current[1]+y,x,y)
self.set_content(current[0],current[1],' ')
self.set_content(current[0]+x,current[1]+y,'@')
if save: self.queue.put((x,y,True))
elif current[2] == '@' and future == '*' and future_box == ' ':
self.move_box(current[0]+x,current[1]+y,x,y)
self.set_content(current[0],current[1],' ')
self.set_content(current[0]+x,current[1]+y,'+')
if save: self.queue.put((x,y,True))
elif current[2] == '@' and future == '*' and future_box == '.':
self.move_box(current[0]+x,current[1]+y,x,y)
self.set_content(current[0],current[1],' ')
self.set_content(current[0]+x,current[1]+y,'+')
if save: self.queue.put((x,y,True))
if current[2] == '+' and future == '$' and future_box == ' ':
self.move_box(current[0]+x,current[1]+y,x,y)
self.set_content(current[0],current[1],'.')
self.set_content(current[0]+x,current[1]+y,'@')
if save: self.queue.put((x,y,True))
elif current[2] == '+' and future == '$' and future_box == '.':
self.move_box(current[0]+x,current[1]+y,x,y)
self.set_content(current[0],current[1],'.')
self.set_content(current[0]+x,current[1]+y,'+')
if save: self.queue.put((x,y,True))
elif current[2] == '+' and future == '*' and future_box == ' ':
self.move_box(current[0]+x,current[1]+y,x,y)
self.set_content(current[0],current[1],'.')
self.set_content(current[0]+x,current[1]+y,'+')
if save: self.queue.put((x,y,True))
elif current[2] == '+' and future == '*' and future_box == '.':
self.move_box(current[0]+x,current[1]+y,x,y)
self.set_content(current[0],current[1],'.')
self.set_content(current[0]+x,current[1]+y,'+')
if save: self.queue.put((x,y,True))
def print_game(matrix,screen):
screen.fill(background)
x = 0
y = 0
for row in matrix:
for char in row:
if char == ' ': #floor
screen.blit(floor,(x,y))
elif char == '#': #wall
screen.blit(wall,(x,y))
elif char == '@': #worker on floor
screen.blit(worker,(x,y))
elif char == '.': #dock
screen.blit(docker,(x,y))
elif char == '*': #box on dock
screen.blit(box_docked,(x,y))
elif char == '$': #box
screen.blit(box,(x,y))
elif char == '+': #worker on dock
screen.blit(worker_docked,(x,y))
x = x + 32
x = 0
y = y + 32
def get_key():
while 1:
event = pygame.event.poll()
if event.type == pygame.KEYDOWN:
return event.key
else:
pass
def display_box(screen, message):
"Print a message in a box in the middle of the screen"
fontobject = pygame.font.Font(None,18)
pygame.draw.rect(screen, (0,0,0),
((screen.get_width() / 2) - 100,
(screen.get_height() / 2) - 10,
200,20), 0)
pygame.draw.rect(screen, (255,255,255),
((screen.get_width() / 2) - 102,
(screen.get_height() / 2) - 12,
204,24), 1)
if len(message) != 0:
screen.blit(fontobject.render(message, 1, (255,255,255)),
((screen.get_width() / 2) - 100, (screen.get_height() / 2) - 10))
pygame.display.flip()
def display_end(screen):
message = "Level Completed"
fontobject = pygame.font.Font(None,18)
pygame.draw.rect(screen, (0,0,0),
((screen.get_width() / 2) - 100,
(screen.get_height() / 2) - 10,
200,20), 0)
pygame.draw.rect(screen, (255,255,255),
((screen.get_width() / 2) - 102,
(screen.get_height() / 2) - 12,
204,24), 1)
screen.blit(fontobject.render(message, 1, (255,255,255)),
((screen.get_width() / 2) - 100, (screen.get_height() / 2) - 10))
pygame.display.flip()
def ask(screen, question):
"ask(screen, question) -> answer"
pygame.font.init()
current_string = []
display_box(screen, question + ": " + string.join(current_string,""))
while 1:
inkey = get_key()
if inkey == pygame.K_BACKSPACE:
current_string = current_string[0:-1]
elif inkey == pygame.K_RETURN:
break
elif inkey == pygame.K_MINUS:
current_string.append("_")
elif inkey <= 127:
current_string.append(chr(inkey))
display_box(screen, question + ": " + string.join(current_string,""))
return string.join(current_string,"")
def start_game():
start = pygame.display.set_mode((320,240))
level = ask(start,"Select Level")
if level > 0:
return level
else:
print "ERROR: Invalid Level: "+str(level)
sys.exit(2)
wall = pygame.image.load('images/wall.png')
floor = pygame.image.load('images/floor.png')
box = pygame.image.load('images/box.png')
box_docked = pygame.image.load('images/box_docked.png')
worker = pygame.image.load('images/worker.png')
worker_docked = pygame.image.load('images/worker_dock.png')
docker = pygame.image.load('images/dock.png')
background = 255, 226, 191
pygame.init()
level = start_game()
game = game('levels',level)
size = game.load_size()
screen = pygame.display.set_mode(size)
while 1:
if game.is_completed(): display_end(screen)
print_game(game.get_matrix(),screen)
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit(0)
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP: game.move(0,-1, True)
elif event.key == pygame.K_DOWN: game.move(0,1, True)
elif event.key == pygame.K_LEFT: game.move(-1,0, True)
elif event.key == pygame.K_RIGHT: game.move(1,0, True)
elif event.key == pygame.K_q: sys.exit(0)
elif event.key == pygame.K_d: game.unmove()
pygame.display.update()