Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/SliderPuzzleWidget.py
blob: 60e0b219fb93c2a140ef08e602c4d103ece4b9fc (plain)
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
# Copyright 2007 World Wide Workshop Foundation
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#
# If you find this activity useful or end up using parts of it in one of your
# own creations we would love to hear from you at info@WorldWideWorkshop.org !
#

from gi.respository import Gtk, GObject, Pango, GdkPixbuf
import md5
import logging

from mamamedia_modules import utils

#from utils import load_image, calculate_matrix, debug, SliderCreator, trace

from types import TupleType, ListType
from random import random
from time import time
from math import sqrt
from cStringIO import StringIO
import os

###
# General Information
###

up_key =    ['Up', 'KP_Up', 'KP_8']
down_key =  ['Down', 'KP_Down', 'KP_2']
left_key =  ['Left', 'KP_Left', 'KP_4']
right_key = ['Right', 'KP_Right', 'KP_6']

SLIDE_UP = 1
SLIDE_DOWN = 2
SLIDE_LEFT = 3
SLIDE_RIGHT = 4

def calculate_matrix (pieces):
    """ Given a number of pieces, calculate the best fit 2 dimensional matrix """
    rows = int(sqrt(pieces))
    cols = int(float(pieces) / rows)
    return rows*cols, rows, cols


class SliderCreator (GdkPixbuf):
    def __init__ (self, width, height, fname=None, tlist=None): #tlist):
        if width == -1:
            width = 564
        if height == -1:
            height = 564
        super(SliderCreator, self).__init__(Gdk.COLORSPACE_RGB, False, 8, width, height)
        if tlist is None:
          items = []
          cmds = file(fname).readlines()
          if len(cmds) > 1:
              _x_ = eval(cmds[0])
              for i in range(16):
                  items.append(_x_)
                  _x_ = eval(cmds[1])
        else:
            items = tlist
        self.width = width
        self.height = height
        self.tlist = items
        self.prepare_stringed(2,2)

    #def scale_simple (self, w,h,m):
    #    return SliderCreator(w,h,tlist=self.tlist)

    #def subpixbuf (self, x,y,w,h):
    #    return SliderCreator(w,h,tlist=self.tlist)

    @classmethod
    def can_handle(klass, fname):
        return fname.lower().endswith('.sequence')

    def prepare_stringed (self, rows, cols):
        # We use a Pixmap as offscreen drawing canvas
        cm = Gdk.colormap_get_system()
        pm = Gdk.Pixmap(None, self.width, self.height, cm.get_visual().depth)
        #pangolayout = pm.create_pango_layout("")
        font_size = int(self.width / cols / 4)
        l = Gtk.Label()
        pangolayout = Pango.Layout(l.create_pango_context())
        pangolayout.set_font_description(Pango.FontDescription("sans bold %i" % font_size))
        gc = pm.new_gc()
        gc.set_colormap(Gdk.colormap_get_system())
        color = cm.alloc_color('white')
        gc.set_foreground(color)
        pm.draw_rectangle(gc, True, 0, 0, self.width, self.height)
        color = cm.alloc_color('black')
        gc.set_foreground(color)

        sw, sh = (self.width / cols), (self.height / rows)
        item = iter(self.tlist)
        for r in range(rows):
            for c in range(cols):
                px = sw * c
                py = sh * r
                #if c > 0 and r > 0:
                #    pm.draw_line(gc, px, 0, px, self.height-1)
                #    pm.draw_line(gc, 0, py, self.width-1, py)
                pangolayout.set_text(str(item.next()))
                pe = pangolayout.get_pixel_extents()
                pe = pe[1][2]/2, pe[1][3]/2
                pm.draw_layout(gc, px + (sw / 2) - pe[0],  py + (sh / 2) - pe[1], pangolayout)
        self.get_from_drawable(pm, cm, 0, 0, 0, 0, -1, -1)

utils.register_image_type(SliderCreator)

###
# Game Logic
###

class MatrixPosition (object):
    """ Helper class to hold a x/y coordinate, and move it by passing a direction,
    taking care of enforcing boundaries as needed.
    The x and y coords are 0 based. """
    def __init__ (self, rowsize, colsize, x=0, y=0):
        self.rowsize = rowsize
        self.colsize = colsize
        self.x = min(x, colsize-1)
        self.y = min(y, rowsize-1)

    def __eq__ (self, other):
        if isinstance(other, (TupleType, ListType)) and len(other) == 2:
            return self.x == other[0] and self.y == other[1]
        return False

    def __ne__ (self, other):
        return not self.__eq__ (other)

    def bottom_right (self):
        """ Move to the lower right position of the matrix, having 0,0 as the top left corner """
        self.x = self.colsize - 1
        self.y = self.rowsize-1

    def move (self, direction, count=1):
        """ Moving direction is actually the opposite of what is passed.
        We are moving the hole position, so if you slice a piece down into the hole,
        that hole is actually moving up.
        Returns bool, false if we can't move in the requested direction."""
        if direction == SLIDE_UP and self.y < self.rowsize-1:
            self.y += 1
            return True
        if direction == SLIDE_DOWN and self.y > 0:
            self.y -= 1
            return True
        if direction == SLIDE_LEFT and self.x < self.colsize-1:
            self.x += 1
            return True
        if direction == SLIDE_RIGHT and self.x > 0:
            self.x -= 1
            return True
        return False

    def clone (self):
        return MatrixPosition(self.rowsize, self.colsize, self.x, self.y)

    def _freeze (self):
        return (self.rowsize, self.colsize, self.x, self.y)

    def _thaw (self, obj):
        if obj is not None:
            self.rowsize, self.colsize, self.x, self.y = obj
        

class SliderPuzzleMap (object):
    """ This class holds the game logic.
    The current pieces position is held in self.pieces_map[YROW][XROW].
    """
    def __init__ (self, pieces=9, move_cb=None):
        self.reset(pieces)
        self.move_cb = move_cb
        self.solved = True

    def reset (self, pieces=9):
        self.pieces, self.rowsize, self.colsize = calculate_matrix(pieces)
        pieces_map = range(1,self.pieces+1)
        self.pieces_map = []
        for i in range(self.rowsize):
            self.pieces_map.append(pieces_map[i*self.colsize:(i+1)*self.colsize])
        self.hole_pos = MatrixPosition(self.rowsize, self.colsize)
        self.hole_pos.bottom_right()
        self.solved_map = [list(x) for x in self.pieces_map]
        self.solved_map[-1][-1] = None

    def randomize (self):
        """ To make sure the randomization is solvable, we don't simply shuffle the numbers.
        We move the hole in random directions through a finite number of iteractions. """
        # Remove the move callback temporarily
        cb = self.move_cb
        self.move_cb = None

        iteractions = self.rowsize * self.colsize * (int(100*random())+1)

        t = time()
        for i in range(iteractions):
            while not (self.do_move(int(4*random())+1)):
                pass

        t = time() - t

        # Now move the hole to the bottom right
        for x in range(self.colsize-self.hole_pos.x-1):
            self.do_move(SLIDE_LEFT)
        for y in range(self.rowsize-self.hole_pos.y-1):
            self.do_move(SLIDE_UP)

        # Put the callback where it was
        self.move_cb = cb
        self.solved = False

    def do_move (self, slide_direction):
        """
        The moves are relative to the moving piece:
        
        >>> jm = SliderPuzzleMap()
        >>> jm.debug_map()
        1 2 3
        4 5 6
        7 8 *
        >>> jm.do_move(SLIDE_DOWN)
        True
        >>> jm.debug_map() # DOWN
        1 2 3
        4 5 *
        7 8 6
        >>> jm.do_move(SLIDE_RIGHT)
        True
        >>> jm.debug_map() # RIGHT
        1 2 3
        4 * 5
        7 8 6
        >>> jm.do_move(SLIDE_UP)
        True
        >>> jm.debug_map() # UP
        1 2 3
        4 8 5
        7 * 6
        >>> jm.do_move(SLIDE_LEFT)
        True
        >>> jm.debug_map() # LEFT
        1 2 3
        4 8 5
        7 6 *

        We can't move over the matrix edges:

        >>> jm.do_move(SLIDE_LEFT)
        False
        >>> jm.debug_map() # LEFT
        1 2 3
        4 8 5
        7 6 *
        >>> jm.do_move(SLIDE_UP)
        False
        >>> jm.debug_map() # UP
        1 2 3
        4 8 5
        7 6 *
        >>> jm.do_move(SLIDE_RIGHT)
        True
        >>> jm.do_move(SLIDE_RIGHT)
        True
        >>> jm.do_move(SLIDE_RIGHT)
        False
        >>> jm.debug_map() # RIGHT x 3
        1 2 3
        4 8 5
        * 7 6
        >>> jm.do_move(SLIDE_DOWN)
        True
        >>> jm.do_move(SLIDE_DOWN)
        True
        >>> jm.do_move(SLIDE_DOWN)
        False
        >>> jm.debug_map() # DOWN x 3
        * 2 3
        1 8 5
        4 7 6
       """
        # What piece are we going to move?
        old_hole_pos = self.hole_pos.clone()
        if self.hole_pos.move(slide_direction):
            # Move was a success, now update the map
            self.pieces_map[old_hole_pos.y][old_hole_pos.x] = self.pieces_map[self.hole_pos.y][self.hole_pos.x]
            self.is_solved()
            if self.move_cb is not None:
                self.move_cb(self.hole_pos.x, self.hole_pos.y, old_hole_pos.x, old_hole_pos.y)
            return True
        return False

    def do_move_piece (self, piece):
        """ Move the piece (1 based index) into the hole, if possible
        >>> jm = SliderPuzzleMap()
        >>> jm.debug_map()
        1 2 3
        4 5 6
        7 8 *
        >>> jm.do_move_piece(6)
        True
        >>> jm.debug_map() # Moved 6
        1 2 3
        4 5 *
        7 8 6
        >>> jm.do_move_piece(2)
        False
        >>> jm.debug_map() # No move
        1 2 3
        4 5 *
        7 8 6

        Return True if a move was done, False otherwise.
        """
        for y in range(self.rowsize):
            for x in range(self.colsize):
                if self.pieces_map[y][x] == piece:
                    if self.hole_pos.x == x:
                        if abs(self.hole_pos.y-y) == 1:
                            return self.do_move(self.hole_pos.y > y and SLIDE_DOWN or SLIDE_UP)
                    elif self.hole_pos.y == y:
                        if abs(self.hole_pos.x-x) == 1:
                            return self.do_move(self.hole_pos.x > x and SLIDE_RIGHT or SLIDE_LEFT)
                    else:
                        return False
        return False

    def is_hole_at (self, x, y):
        """
        >>> jm = SliderPuzzleMap()
        >>> jm.debug_map()
        1 2 3
        4 5 6
        7 8 *
        >>> jm.is_hole_at(2,2)
        True
        >>> jm.is_hole_at(0,0)
        False
        """
        return self.hole_pos == (x,y)

    def is_solved (self):
        """
        >>> jm = SliderPuzzleMap()
        >>> jm.do_move_piece(6)
        True
        >>> jm.is_solved()
        False
        >>> jm.do_move_piece(6)
        True
        >>> jm.is_solved()
        True
        """
        if self.hole_pos != (self.colsize-1, self.rowsize-1):
            return False
        self.pieces_map[self.hole_pos.y][self.hole_pos.x] = None
        self.solved = self.pieces_map == self.solved_map
        return self.solved
        
        

    def get_cell_at (self, x, y):
        if x < 0 or x >= self.colsize or y < 0 or y >= self.rowsize or self.is_hole_at(x,y):
            return None
        return self.pieces_map[y][x]

    def debug_map (self):
        for y in range(self.rowsize):
            for x in range(self.colsize):
                if self.hole_pos == (x,y):
                    logging.debug("*")
                else:
                    logging.debug(self.pieces_map[y][x])

    def __call__ (self):
        self.debug_map()

    def _freeze (self):
        return {'pieces': self.pieces, 'rowsize': self.rowsize, 'colsize': self.colsize,
                'pieces_map': self.pieces_map, 'hole_pos_freeze': self.hole_pos._freeze()}

    def _thaw (self, obj):
        for k in obj.keys():
            if hasattr(self, k):
                setattr(self, k, obj[k])
        self.hole_pos._thaw(obj.get('hole_pos_freeze', None))


###
# Widget Definition
###

class SliderPuzzleWidget (Gtk.Table):
    __gsignals__ = {'solved' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),
                    'shuffled' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),
                    'moved' : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),}
    
    def __init__ (self, pieces=9, width=480, height=480):
        self.jumbler = SliderPuzzleMap(pieces, self.jumblermap_piece_move_cb)
        # We take this from the jumbler object because it may have altered our requested value
        Gtk.Table.__init__(self, self.jumbler.rowsize, self.jumbler.colsize)
        self.image = None #Gtk.Image()
        self.width = width
        self.height = height
        self.set_size_request(width, height)
        self.filename = None

    def prepare_pieces (self):
        """ set up a list of UI objects that will serve as pieces, ordered correctly """
        self.pieces = []
        if self.image is None:
        #    pb = self.image.get_pixbuf()
        #if self.image is None or pb is None:
            for i in range(self.jumbler.pieces):
                self.pieces.append(Gtk.Button(str(i+1)))
                self.pieces[-1].connect("button-release-event", self.process_mouse_click, i+1)
                self.pieces[-1].show()
        else:
            if isinstance(self.image, SliderCreator):
                # ask for image creation
                self.image.prepare_stringed(self.jumbler.rowsize, self.jumbler.colsize)
        
            w = self.image.get_width() / self.jumbler.colsize
            h = self.image.get_height() / self.jumbler.rowsize
            for y in range(self.jumbler.rowsize):
                for x in range(self.jumbler.colsize):
                    img = Gtk.Image()
                    img.set_from_pixbuf(self.image.subpixbuf(x*w, y*h, w-1, h-1))
                    img.show()
                    self.pieces.append(Gtk.EventBox())
                    self.pieces[-1].add(img)
                    self.pieces[-1].connect("button-press-event", self.process_mouse_click, (y*self.jumbler.colsize)+x+1)
                    self.pieces[-1].show()
            self.set_row_spacings(1)
            self.set_col_spacings(1)

    @utils.trace
    def full_refresh (self):
        # Delete everything
        self.foreach(self.remove)
        self.prepare_pieces()
        # Add the pieces in their respective places
        for y in range(self.jumbler.rowsize):
            for x in range(self.jumbler.colsize):
                pos = self.jumbler.get_cell_at(x, y)
                if pos is not None:
                    self.attach(self.pieces[pos-1], x, x+1, y, y+1)

    def process_mouse_click (self, b, e, i):
        # i is the 1 based index of the piece
        self.jumbler.do_move_piece(i)

    def process_key (self, w, e):
        if self.get_parent() == None:
            return False
        k = Gdk.keyval_name(e.keyval)
        if k in up_key:
            self.jumbler.do_move(SLIDE_UP)
            return True
        if k in down_key:
            self.jumbler.do_move(SLIDE_DOWN)
            return True
        if k in left_key:
            self.jumbler.do_move(SLIDE_LEFT)
            return True
        if k in right_key:
            self.jumbler.do_move(SLIDE_RIGHT)
            return True
        return False

    ### SliderPuzzleMap specific callbacks ###

    def jumblermap_piece_move_cb (self, hx, hy, px, py):
        if not hasattr(self, 'pieces'):
            return
        piece = self.pieces[self.jumbler.get_cell_at(px, py)-1]
        self.remove(piece)
        self.attach(piece, px, px+1, py, py+1)
        self.emit("moved")
        if self.jumbler.solved:
            self.emit("solved")

    ### Parent callable interface ###

    def get_nr_pieces (self):
        return self.jumbler.pieces

    @utils.trace
    def set_nr_pieces (self, nr_pieces):
        self.jumbler.reset(nr_pieces)
        self.resize(self.jumbler.rowsize, self.jumbler.colsize)
        self.randomize()

    @utils.trace
    def randomize (self):
        """ Jumble the SliderPuzzle """
        self.jumbler.randomize()
        self.full_refresh()
        self.emit("shuffled")

    @utils.trace
    def load_image (self, image, width=0, height=0):
        """ Loads an image from the file.
        width and height are processed as follows:
          -1 : follow the loaded image size
           0 : follow the size set on widget instantiation
           * : use that specific size"""
        if width == 0:
            width = self.width
        if height == 0:
            height = self.height
        if not isinstance(image, SliderCreator):
            self.image = utils.resize_image(image, width, height)
        else:
            self.image = image
        self.filename = True
        self.full_refresh()

    def set_image (self, image):
        # image is a pixbuf!
        self.image = image
        self.filename = True

    def set_image_from_str (self, image):
        fn = os.tempnam() 
        f = file(fn, 'w+b')
        f.write(image)
        f.close()
        i = Gtk.Image()
        i.set_from_file(fn)
        os.remove(fn)
        self.image = i.get_pixbuf()
        self.filename = True

    def show_image (self):
        """ Shows the full image, used as visual clue for solved puzzle """
        # Delete everything
        self.foreach(self.remove)
        if hasattr(self, 'pieces'):
            del self.pieces
        # Resize to a single cell and use that for the image
        self.resize(1,1)
        img = Gtk.Image()
        img.set_from_pixbuf(self.image)
        self.attach(img, 0,1,0,1)
        img.show()

    def get_image_as_png (self, cb=None):
        if self.image is None:
            return None
        rv = None
        if cb is None:
            rv = StringIO()
            cb = rv.write
        self.image.save_to_callback(cb, "png")
        if rv is not None:
            return rv.getvalue()
        else:
            return True

    def _freeze (self, journal=True):
        """ returns a json writable object representation capable of being used to restore our current status """
        if journal:
            return {'jumbler': self.jumbler._freeze(),
                    'image': self.get_image_as_png(),
                    }
        else:
            return {'jumbler': self.jumbler._freeze()}

    def _thaw (self, obj):
        """ retrieves a frozen status from a python object, as per _freeze """
        logging.debug(obj['jumbler'])
        self.jumbler._thaw(obj['jumbler'])
        if obj.has_key('image') and obj['image'] is not None:
            self.set_image_from_str(obj['image'])
            del obj['image']
        self.full_refresh()

def _test():
    import doctest
    doctest.testmod()

if __name__ == '__main__':
    _test()