-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathpuzzle.py
executable file
·176 lines (152 loc) · 6.17 KB
/
puzzle.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Author: Leo Vidarte <http://nerdlabs.com.ar>
This is free software,
you can redistribute it and/or modify it
under the terms of the GPL version 3
as published by the Free Software Foundation.
"""
import random
import Tkinter as tk
import tkMessageBox
from PIL import Image, ImageTk
MAX_BOARD_SIZE = 500
class Application(tk.Frame):
def __init__(self, image, board_grid=4):
tk.Frame.__init__(self)
self.grid()
self.board_grid = board_grid if board_grid > 2 else 3
self.load_image(image)
self.steps = 0
self.create_widgets()
self.create_events()
self.create_board()
self.show()
def load_image(self, image):
image = Image.open(image)
board_size = min(image.size)
if image.size[0] != image.size[1]:
image = image.crop((0, 0, board_size, board_size))
if board_size > MAX_BOARD_SIZE:
board_size = MAX_BOARD_SIZE
image = image.resize((board_size, board_size), Image.ANTIALIAS)
self.image = image
self.board_size = board_size
self.piece_size = self.board_size / self.board_grid
def create_widgets(self):
args = dict(width=self.board_size, height=self.board_size)
self.canvas = tk.Canvas(self, **args)
self.canvas.grid()
def create_events(self):
self.canvas.bind_all('<KeyPress-Up>', self.slide)
self.canvas.bind_all('<KeyPress-Down>', self.slide)
self.canvas.bind_all('<KeyPress-Left>', self.slide)
self.canvas.bind_all('<KeyPress-Right>', self.slide)
self.canvas.bind_all('<KeyPress-h>', self.slide)
self.canvas.bind_all('<KeyPress-j>', self.slide)
self.canvas.bind_all('<KeyPress-k>', self.slide)
self.canvas.bind_all('<KeyPress-l>', self.slide)
self.canvas.bind_all('<KeyPress-H>', self.help)
def help(self, event):
if getattr(self, '_img_help_id', None) is None:
self._img_help = ImageTk.PhotoImage(self.image)
self._img_help_id = self.canvas.create_image(0, 0,
image=self._img_help, anchor=tk.NW)
else:
state = self.canvas.itemcget(self._img_help_id, 'state')
state = 'hidden' if state == '' else ''
self.canvas.itemconfigure(self._img_help_id, state=state)
def slide(self, event):
pieces = self.get_pieces_around()
if event.keysym in ('Up', 'k') and pieces['bottom']:
self._slide(pieces['bottom'], pieces['center'],
(0, -self.piece_size))
if event.keysym in ('Down', 'j') and pieces['top']:
self._slide(pieces['top'], pieces['center'],
(0, self.piece_size))
if event.keysym in ('Left', 'h') and pieces['right']:
self._slide(pieces['right'], pieces['center'],
(-self.piece_size, 0))
if event.keysym in ('Right', 'l') and pieces['left']:
self._slide(pieces['left'], pieces['center'],
(self.piece_size, 0))
self.check_status()
def _slide(self, from_, to, coord):
self.canvas.move(from_['id'], *coord)
to['pos_a'], from_['pos_a'] = from_['pos_a'], to['pos_a']
self.steps += 1
def get_pieces_around(self):
pieces = {'center': None,
'right' : None,
'left' : None,
'top' : None,
'bottom': None}
for piece in self.board:
if not piece['visible']:
pieces['center'] = piece
break
x0, y0 = pieces['center']['pos_a']
for piece in self.board:
x1, y1 = piece['pos_a']
if y0 == y1 and x1 == x0 + 1:
pieces['right'] = piece
if y0 == y1 and x1 == x0 - 1:
pieces['left'] = piece
if x0 == x1 and y1 == y0 - 1:
pieces['top'] = piece
if x0 == x1 and y1 == y0 + 1:
pieces['bottom'] = piece
return pieces
def create_board(self):
self.board = []
for x in xrange(self.board_grid):
for y in xrange(self.board_grid):
x0 = x * self.piece_size
y0 = y * self.piece_size
x1 = x0 + self.piece_size
y1 = y0 + self.piece_size
image = ImageTk.PhotoImage(
self.image.crop((x0, y0, x1, y1)))
piece = {'id' : None,
'image' : image,
'pos_o' : (x, y),
'pos_a' : None,
'visible': True}
self.board.append(piece)
self.board[-1]['visible'] = False
def check_status(self):
for piece in self.board:
if piece['pos_a'] != piece['pos_o']:
return
title = 'Ganaste!'
message = 'Lo resolviste en %d movidas!' % self.steps
tkMessageBox.showinfo(title, message)
def show(self):
random.shuffle(self.board)
index = 0
for x in xrange(self.board_grid):
for y in xrange(self.board_grid):
self.board[index]['pos_a'] = (x, y)
if self.board[index]['visible']:
x1 = x * self.piece_size
y1 = y * self.piece_size
image = self.board[index]['image']
id = self.canvas.create_image(
x1, y1, image=image, anchor=tk.NW)
self.board[index]['id'] = id
index += 1
if __name__ == '__main__':
from optparse import OptionParser
parser = OptionParser(description="Sliding puzzle")
parser.add_option('-g', '--board-grid', type=int, default=4,
help="(the minimum value is 3)")
parser.add_option('-i', '--image', type=str, default='spider.png',
help="path to image")
args, _ = parser.parse_args()
if args.board_grid < 3:
args.board_grid = 3
print "Warning: using 3 for board-grid"
app = Application(args.image, args.board_grid)
app.master.title('Sliding puzzle')
app.mainloop()