Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/game.py
blob: a54ac6495d7ce3dea84388119f432842f041966f (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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
# -*- coding: utf-8 -*-
#Copyright (c) 2009,12 Walter Bender
#Copyright (c) 2009 Michele Pratusevich
#Copyright (c) 2009 Vincent Le

# 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 3 of the License, or
# (at your option) any later version.

# You should have received a copy of the GNU General Public License
# along with this library; if not, write to the Free Software
# Foundation, 51 Franklin Street, Suite 500 Boston, MA 02110-1335 USA


import pygtk
pygtk.require('2.0')
import gtk
import gobject

from gettext import gettext as _

from math import sqrt

from sugar.graphics.objectchooser import ObjectChooser
from sugar.datastore import datastore
from sugar import mime

import logging
_logger = logging.getLogger('visualmatch-activity')

try:
    from sugar.graphics import style
    GRID_CELL_SIZE = style.GRID_CELL_SIZE
except ImportError:
    GRID_CELL_SIZE = 0

from constants import LOW, MEDIUM, HIGH, MATCHMASK, ROW, COL, \
    WORD_CARD_INDICIES, DEAD_DICTS, DEAD_KEYS, WHITE_SPACE, \
    NOISE_KEYS, WORD_CARD_MAP, KEYMAP, CARD_HEIGHT, CARD_WIDTH, DEAL, \
    DIFFICULTY_LEVEL, BACKGROUNDMASK, DECKSIZE, CUSTOM_CARD_INDICIES

CURSOR = '█'


from grid import Grid
from deck import Deck
from card import Card
from sprites import Sprites, Sprite
from gencards import generate_match_card, \
    generate_smiley, generate_frowny_texture,  generate_frowny_shape, \
    generate_frowny_color, generate_frowny_number


def _distance(pos1, pos2):
    ''' simple distance function '''
    return sqrt((pos1[0] - pos2[0]) * (pos1[0] - pos2[0]) + \
                (pos1[1] - pos2[1]) * (pos1[1] - pos2[1]))


def _find_the_number_in_the_name(name):
    ''' Find which element in an array (journal entry title) is a number '''
    parts = name.split('.')
    before = ''
    after = ''
    for i in range(len(parts)):
        ii = len(parts) - i - 1
        try:
            int(parts[ii])
            for j in range(ii):
                before += (parts[j] + '.')
            for j in range(ii + 1, len(parts)):
                after += ('.' + parts[j])
            return before, after, ii
        except ValueError:
            pass
    return '', '', -1


def _construct_a_name(before, i, after):
    ''' Make a numbered filename from parts '''
    return '%s%s%s' % (before, str(i), after)


class Game():
    ''' The game play -- called from within Sugar or GNOME '''

    def __init__(self, canvas, path, parent=None):
        ''' Initialize the playing surface '''
        self.path = path
        self.activity = parent

        if parent is None:  # Starting from command line
            self.sugar = False
            self.canvas = canvas
        else:  # Starting from Sugar
            self.sugar = True
            self.canvas = canvas
            parent.show_all()

        self.canvas.set_flags(gtk.CAN_FOCUS)
        self.canvas.connect('expose-event', self._expose_cb)
        self.canvas.add_events(gtk.gdk.BUTTON_PRESS_MASK)
        self.canvas.connect('button-press-event', self._button_press_cb)
        self.canvas.add_events(gtk.gdk.BUTTON_RELEASE_MASK)
        self.canvas.connect('button-release-event', self._button_release_cb)
        self.canvas.add_events(gtk.gdk.POINTER_MOTION_MASK)
        self.canvas.connect("motion-notify-event", self._mouse_move_cb)
        self.canvas.connect('key_press_event', self._keypress_cb)
        self.width = gtk.gdk.screen_width()
        self.height = gtk.gdk.screen_height() - GRID_CELL_SIZE
        self.scale = 0.8 * self.height / (CARD_HEIGHT * 5.5)
        self.card_width = CARD_WIDTH * self.scale
        self.card_height = CARD_HEIGHT * self.scale
        self.custom_paths = [None, None, None, None, None, None, None, None,
                             None]
        self.sprites = Sprites(self.canvas)
        self.press = None
        self.match_display_area = []
        self._matches_on_display = False
        self.smiley = []
        self.frowny = []
        self.failure = 0
        self.clicked = [[None, 0, 0], [None, 0, 0], [None, 0, 0]]
        self.dragpos = [0, 0]
        self.startpos = [0, 0]
        self.low_score = [-1, -1, -1]
        self.all_scores = []
        self.robot = False
        self.numberC = 0
        self.numberO = 0
        self.word_lists = None
        self.editing_word_list = False
        self.editing_custom_cards = False
        self.edit_card = None
        self.dead_key = None
        self._found_a_match = False

    def new_game(self, saved_state=None, deck_index=0):
        ''' Start a new game '''
        # If we were editing the word list, time to stop
        self.editing_word_list = False
        self.editing_custom_cards = False
        self.edit_card = None

        # If there is already a deck, hide it.
        if hasattr(self, 'deck'):
            self.deck.hide()

        # The first time through, initialize the grid, and overlays.
        if not hasattr(self, 'grid'):
            self.grid = Grid(self.width, self.height, self.card_width,
                             self.card_height)

            for i in range(0, 3):
                self.match_display_area.append(Card(self.sprites,
                                          generate_match_card(self.scale),
                                          [MATCHMASK, 0, 0, 0]))
                self.match_display_area[-1].spr.move(self.grid.match_to_xy(i))
                # self.grid.display_match(self.match_display_area[i].spr, i)

            for i in range((ROW - 1)* COL):
                self.smiley.append(
                    Card(self.sprites, generate_smiley(self.scale),
                         [BACKGROUNDMASK, 0, 0, 0]))
                self.smiley[-1].spr.move(self.grid.grid_to_xy(i))
            self.smiley.append(Card(self.sprites, generate_smiley(self.scale),
                                    [BACKGROUNDMASK, 0, 0, 0]))
            self.smiley[-1].spr.move(self.grid.match_to_xy(3))
            self.smiley[-1].spr.hide()

            # A different frowny face for each type of error
            self.frowny.append(
                Card(self.sprites, generate_frowny_shape(self.scale),
                         [BACKGROUNDMASK, 0, 0, 0]))
            self.frowny[-1].spr.move(self.grid.match_to_xy(3))
            self.frowny.append(
                Card(self.sprites, generate_frowny_color(self.scale),
                         [BACKGROUNDMASK, 0, 0, 0]))
            self.frowny[-1].spr.move(self.grid.match_to_xy(3))
            self.frowny.append(
                Card(self.sprites, generate_frowny_texture(self.scale),
                         [BACKGROUNDMASK, 0, 0, 0]))
            self.frowny[-1].spr.move(self.grid.match_to_xy(3))
            self.frowny.append(
                Card(self.sprites, generate_frowny_number(self.scale),
                         [BACKGROUNDMASK, 0, 0, 0]))
            self.frowny[-1].spr.move(self.grid.match_to_xy(3))

        self.clicked = [[None, 0, 0], [None, 0, 0], [None, 0, 0]]

        # Restore saved state on resume or share.
        if not hasattr(self, 'card_type'):
            return

        self._matches_on_display = False
        for c in self.frowny:
            c.spr.hide()
        self.smiley[-1].spr.hide()

        if saved_state is not None:
            _logger.debug('Restoring state: %s' % (str(saved_state)))
            if self.card_type == 'custom':
                self.deck = Deck(self.sprites, self.card_type,
                             [self.numberO, self.numberC], self.custom_paths,
                             self.scale, DIFFICULTY_LEVEL[self.level])
            else:
                self.deck = Deck(self.sprites, self.card_type,
                             [self.numberO, self.numberC], self.word_lists,
                             self.scale, DIFFICULTY_LEVEL[self.level])
            self.deck.hide()
            self.deck.index = deck_index
            _deck_start = ROW * COL + 3
            _deck_stop = _deck_start + self.deck.count()
            self._restore_word_list(saved_state[_deck_stop + \
                                                    3 * self.matches:])
            self.deck.restore(saved_state[_deck_start: _deck_stop])
            self.grid.restore(self.deck, saved_state[0: ROW * COL])
            self._restore_matches(saved_state[_deck_stop: _deck_stop + \
                                                  3 * self.matches])
            self._restore_clicked(saved_state[ROW * COL: ROW * COL + 3])

        elif not self.joiner():
            _logger.debug('Starting new game.')
            if self.card_type == 'custom':
                self.deck = Deck(self.sprites, self.card_type,
                                 [self.numberO, self.numberC],
                                 self.custom_paths, self.scale,
                                 DIFFICULTY_LEVEL[self.level])
            else:
                self.deck = Deck(self.sprites, self.card_type,
                                 [self.numberO, self.numberC], self.word_lists,
                                 self.scale, DIFFICULTY_LEVEL[self.level])
            self.deck.hide()
            self.deck.shuffle()
            self.grid.deal(self.deck)
            if not self._find_a_match():
                self.grid.deal_extra_cards(self.deck)
            self.matches = 0
            self.robot_matches = 0
            self.match_list = []
            self.total_time = 0

        # When sharer starts a new game, joiners should be notified.
        if self.sharer():
            self.activity._send_event('J')

        self._update_labels()
        if self._game_over():
            if hasattr(self, 'timeout_id') and self.timeout_id is not None:
                gobject.source_remove(self.timeout_id)
        else:
            if hasattr(self, 'match_timeout_id') and \
               self.match_timeout_id is not None:
                gobject.source_remove(self.match_timeout_id)
            self._timer_reset()

        for i in range((ROW - 1) * COL):
            self.smiley[i].hide_card()

    def _sharing(self):
        ''' Are we sharing? '''
        if self.sugar and hasattr(self.activity, 'chattube') and \
            self.activity.chattube is not None:
            return True
        return False

    def joiner(self):
        ''' Are you the one joining? '''
        if self._sharing() and not self.activity.initiating:
            return True
        return False

    def sharer(self):
        ''' Are you the one sharing? '''
        if self._sharing() and self.activity.initiating:
            return True
        return False

    def edit_custom_card(self):
        ''' Update the custom cards from the Journal '''
        if not self.editing_custom_cards:
            return

        # Set the card type to custom, and generate a new deck.
        for c in self.clicked:
            if c[0] is not None:
                c[0].hide()
                c[0] = None
        self.deck.hide()
        self.card_type = 'custom'
        if len(self.custom_paths) < 3:
            for i in range(len(self.custom_paths), 81):
                self.custom_paths.append(None)
        self.deck = Deck(self.sprites, self.card_type,
                         [self.numberO, self.numberC],
                         self.custom_paths,
                         self.scale, DIFFICULTY_LEVEL.index(HIGH))
        self.deck.hide()
        self.matches = 0
        self.robot_matches = 0
        self.match_list = []
        self.total_time = 0
        self.edit_card = None
        self.dead_key = None
        if hasattr(self, 'timeout_id') and self.timeout_id is not None:
            gobject.source_remove(self.timeout_id)

        # Fill the grid with custom cards.
        self.grid.restore(self.deck, CUSTOM_CARD_INDICIES)
        self.set_label('deck', '')
        self.set_label('match', '')
        self.set_label('clock', '')
        self.set_label('status', _('Edit the custom cards.'))

    def edit_word_list(self):
        ''' Update the word cards '''
        if not self.editing_word_list:
            return

        # Set the card type to words, and generate a new deck.
        for c in self.clicked:
            if c[0] is not None:
                c[0].hide()
                c[0] = None
        self.deck.hide()
        self.card_type = 'word'
        self.deck = Deck(self.sprites, self.card_type,
                         [self.numberO, self.numberC], self.word_lists,
                         self.scale, DIFFICULTY_LEVEL.index(HIGH))
        self.deck.hide()
        self.matches = 0
        self.robot_matches = 0
        self.match_list = []
        self.total_time = 0
        self.edit_card = None
        self.dead_key = None
        if hasattr(self, 'timeout_id') and self.timeout_id is not None:
            gobject.source_remove(self.timeout_id)
        # Fill the grid with word cards.
        self.grid.restore(self.deck, WORD_CARD_INDICIES)
        self.set_label('deck', '')
        self.set_label('match', '')
        self.set_label('clock', '')
        self.set_label('status', _('Edit the word cards.'))

    def _button_press_cb(self, win, event):
        ''' Look for a card under the button press and save its position. '''
        win.grab_focus()

        # If there is a match showing, hide it.
        if self._matches_on_display:
            self.match_list[-1].hide()
            self.match_list[-2].hide()
            self.match_list[-3].hide()
            # And unselect clicked cards
            self.clicked = [[None, 0, 0], [None, 0, 0], [None, 0, 0]]
            self.smiley[-1].spr.hide()
            self._matches_on_display = False

        # Keep track of starting drag position.
        x, y = map(int, event.get_coords())
        self.dragpos = [x, y]
        self.startpos = [x, y]

        # Find the sprite under the mouse.
        spr = self.sprites.find_sprite((x, y))
        if spr is None:
            return True

        # We are only interested in cards in the deck.
        if self.deck.spr_to_card(spr) is not None:
            self.press = spr
            # Save its starting position so we can restore it if necessary
            if self._where_in_clicked(spr) is None:
                i = self._none_in_clicked()
                if i is None:
                    self.press = None
                else:
                    self.clicked[i][0] = spr
                    self.clicked[i][1] = spr.get_xy()[0]
                    self.clicked[i][2] = spr.get_xy()[1]
        else:
            self.press = None
        return True

    def _mouse_move_cb(self, win, event):
        ''' Drag the card with the mouse. '''
        if self.press is None or \
           self.editing_word_list or \
           self.editing_custom_cards:
            self.dragpos = [0, 0]
            return True
        win.grab_focus()
        x, y = map(int, event.get_coords())
        dx = x - self.dragpos[0]
        dy = y - self.dragpos[1]
        self.press.set_layer(5000)
        self.press.move_relative((dx, dy))
        self.dragpos = [x, y]

    def _button_release_cb(self, win, event):
        ''' Lots of possibilities here:
        (1) We clicked on a card on the canvas, so move it to match area;
        (2) We clicked on a card in the match area, so return it to the canvas;
        (3) We dragged a card to the match area;
        (4) We dragged a card from the match area;
        (5) We dragged a card to a different position on the canvas;
        (6) We dragged a card to a different position on the match area;
        (7) We dragged a card and then changed our mind;
        '''
        win.grab_focus()

        # Maybe there is nothing to do.
        if self.press is None:
            self.dragpos = [0, 0]
            return True

        self.press.set_layer(2000)

        # Determine if it was a click, a drag, or an aborted drag
        x, y = map(int, event.get_coords())
        i = self._where_in_clicked(self.press)
        d = _distance((x, y), (self.startpos[0], self.startpos[1]))
        if d < self.card_width / 10:  # click
            move = 'click'
        elif d < self.card_width / 2:  # aborted drag
            move = 'abort'
        else:
            move = 'drag'

        # Determine status of card
        status = self.grid.spr_to_grid(self.press)
        if move == 'click':
            if self.editing_word_list:
                if self.editing_word_list:
                    # Only edit one card at a time, so unselect other cards
                    for i, a in enumerate(self.clicked):
                        if a[0] is not None and a[0] != self.press:
                            a[0].set_label(a[0].labels[0].replace(CURSOR, ''))
                            a[0] = None  # Unselect
            elif self.editing_custom_cards:
                pass
            elif status is None:  # Return card to grid
                i = self.grid.find_an_empty_slot()
                j = self._where_in_clicked(self.press)
                if i is not None:
                    self.grid.return_to_grid(self.press, i, j)
                    self.grid.grid[i] = self.deck.spr_to_card(self.press)
                    i = self._where_in_clicked(self.press)
                    self.clicked[i][0] = None
                else:
                    self.press.move((self.clicked[i][1], self.clicked[i][2]))
                for c in self.frowny:
                    c.spr.hide()
            else:
                i = self._where_in_clicked(self.press)
                if i is None:
                    self.press.move((self.startpos))
                else:
                    self.press.set_layer(5000)
                    self.grid.grid[self.grid.spr_to_grid(self.press)] = None
                    self.grid.display_match(self.press, i)
        elif move == 'abort':
            self.press.move((self.clicked[i][1], self.clicked[i][2]))
        else:  # move == 'drag'
            if status is None:
                if x > self.grid.left:  # Returning a card to the grid
                    i = self.grid.xy_to_grid((x, y))
                    if self.grid.grid[i] is not None:
                        i = self.grid.find_an_empty_slot()
                    self.press.move(self.grid.grid_to_xy(i))
                    self.grid.grid[i] = self.deck.spr_to_card(self.press)
                    i = self._where_in_clicked(self.press)
                    self.clicked[i][0] = None
                    for c in self.frowny:
                        c.spr.hide()
                else:  # Move a click to a different match slot
                    j = self.grid.xy_to_match((x, y))
                    if i == j:
                        self.press.move((self.clicked[i][1],
                                         self.clicked[i][2]))
                    else:
                        temp_spr = self.clicked[i][0]
                        self.clicked[i][0] = self.clicked[j][0]
                        self.clicked[j][0] = temp_spr
                        if self.clicked[i][0] is not None:
                            self.clicked[i][0].move(self.grid.match_to_xy(i))
                        if self.clicked[j][0] is not None:
                            self.clicked[j][0].move(self.grid.match_to_xy(j))
                    move = 'abort'
            else:
                if x < self.grid.left:  # Moving a card to the match area
                    self.grid.grid[self.grid.spr_to_grid(self.press)] = None
                    self.press.move(self.match_display_area[i].spr.get_xy())
                else:
                    j = self.grid.xy_to_grid((x, y))
                    k = self.grid.xy_to_grid((self.clicked[i][1],
                                              self.clicked[i][2]))
                    if j < 0 or k < 0 or j > 15 or k > 15 or j == k:
                        self.press.move((self.clicked[i][1],
                                         self.clicked[i][2]))
                    else:
                        tmp_card = self.grid.grid[k]
                        if self.grid.grid[j] is not None:
                            self.grid.grid[j].spr.move(self.grid.grid_to_xy(k))
                            self.press.move(self.grid.grid_to_xy(j))
                            self.grid.grid[k] = self.grid.grid[j]
                            self.grid.grid[j] = tmp_card
                        else:
                            self.press.move(self.grid.grid_to_xy(j))
                            self.grid.grid[j] = self.grid.grid[k]
                            self.grid.grid[k] = None
                    move = 'abort'
                    self.clicked[i][0] = None

        if move == 'abort':
            self.press = None
            return
        else:
            spr = self.press

        if self._sharing():
            if self.deck.spr_to_card(spr) is not None:
                self.activity._send_event(
                    'B:' + str(self.deck.spr_to_card(spr).index))
            i = self._where_in_clicked()
            if i is not None:
                self.activity._send_event('S:' + str(i))
        self.press = None
        return self._process_selection(spr)

    def _process_selection(self, spr):
        ''' After a card has been selected:
        (1) If three cards are in the match pile, check for a match
        (2) If there is not a match, return the cards to the board
        '''

        if self.editing_word_list:
            _logger.debug('editing word list')
            # Edit card label
            self.edit_card = self.deck.spr_to_card(spr)
            spr.set_label(spr.labels[0] + CURSOR)
        elif self.editing_custom_cards:
            _logger.debug('editing custom cards')
            # Only edit one card at a time, so unselect other cards
            for i, a in enumerate(self.clicked):
                if a[0] is not None and a[0] != spr:
                    a[0] = None
            # Choose an image from the Journal for a card
            self.edit_card = self.deck.spr_to_card(spr)
            self._choose_custom_card()
            # Regenerate the deck with the new card definitions
            self.deck = Deck(self.sprites, self.card_type,
                             [self.numberO, self.numberC],
                             self.custom_paths, self.scale,
                             DIFFICULTY_LEVEL[1])
            self.deck.hide()
            self.grid.restore(self.deck, CUSTOM_CARD_INDICIES)
        elif self._none_in_clicked() == None:
            # If we have three cards selected, test for a match.
            self._test_for_a_match()
            if self._matches_on_display:
                self.smiley[-1].spr.set_layer(100)
                _logger.debug('Found a match')
            else:
                self.frowny[self._failure].spr.set_layer(100)
        return True

    def _none_in_clicked(self):
        for i, a in enumerate(self.clicked):
            if a[0] is None:
                return i
        return None

    def _where_in_clicked(self, spr):
        for i, a in enumerate(self.clicked):
            if a[0] == spr:
                return i
        return None

    def _game_over(self):
        ''' Game is over when the deck is empty and no more matches. '''
        if self.deck.empty() and not self._find_a_match():
            self.set_label('deck', '')
            self.set_label('clock', '')
            self.set_label('status', '%s (%d:%02d)' %
                (_('Game over'), int(self.total_time / 60),
                 int(self.total_time % 60)))
            for i in range((ROW - 1) * COL):
                if self.grid.grid[i] == None:
                    self.smiley[i].show_card()
            self.match_timeout_id = gobject.timeout_add(
                2000, self._show_matches, 0)
            return True
        elif self.grid.cards_in_grid() == DEAL + 3 \
                and not self._find_a_match():
            self.set_label('deck', '')
            self.set_label('clock', '')
            self.set_label('status', _('unsolvable'))
            return True
        return False

    def _test_for_a_match(self):
        ''' If we have a match, then we have work to do. '''
        if self._match_check([self.deck.spr_to_card(self.clicked[0][0]),
                              self.deck.spr_to_card(self.clicked[1][0]),
                              self.deck.spr_to_card(self.clicked[2][0])],
                             self.card_type):

            # Stop the timer.
            if hasattr(self, 'timeout_id'):
                if self.timeout_id is not None:
                    gobject.source_remove(self.timeout_id)
                self.total_time += gobject.get_current_time() - self.start_time

            # Increment the match counter and add the match to the match list.
            self.matches += 1
            for i in self.clicked:
                self.match_list.append(i[0])

            # Deal three new cards.
            self.grid.replace(self.clicked, self.deck)
            self._matches_on_display = True
            self.set_label('deck', '%d %s' %
                           (self.deck.cards_remaining(), _('cards')))

            # Test to see if the game is over.
            if self._game_over():
                gobject.source_remove(self.timeout_id)
                if self.low_score[self.level] == -1:
                    self.low_score[self.level] = self.total_time
                elif self.total_time < self.low_score[self.level]:
                    self.low_score[self.level] = self.total_time
                    self.set_label('status', '%s (%d:%02d)' %
                        (_('New record'), int(self.total_time / 60),
                         int(self.total_time % 60)))
                self.all_scores.append(self.total_time)
                if not self.sugar:
                    self.activity.save_score()
                return True

            # Consolidate the grid.
            self.grid.consolidate()

            # Test to see if we need to deal extra cards.
            if not self._find_a_match():
                self.grid.deal_extra_cards(self.deck)

            # Keep playing.
            self._update_labels()
            self._timer_reset()

        else:
            self._matches_on_display = False

    def _keypress_cb(self, area, event):
        ''' Keypress: editing word cards or selecting cards to play '''
        k = gtk.gdk.keyval_name(event.keyval)
        u = gtk.gdk.keyval_to_unicode(event.keyval)
        if self.editing_word_list and self.edit_card is not None:
            if k in NOISE_KEYS:
                self.dead_key = None
                return True
            if k[0:5] == 'dead_':
                self.dead_key = k
                return True
            label = self.edit_card.spr.labels[0]
            if len(label) > 0:
                c = label.count(CURSOR)
                if c == 0:
                    oldleft = label
                    oldright = ''
                elif len(label) == 1:  # Only CURSOR
                    oldleft = ''
                    oldright = ''
                else:
                    try:  # Why are getting a ValueError on occasion?
                        oldleft, oldright = label.split(CURSOR)
                    except ValueError:
                        oldleft = label
                        oldright = ''
            else:
                oldleft = ''
                oldright = ''
            newleft = oldleft
            if k == 'BackSpace':
                if len(oldleft) > 1:
                    newleft = oldleft[:len(oldleft) - 1]
                else:
                    newleft = ''
            elif k == 'Delete':
                if len(oldright) > 0:
                    oldright = oldright[1:]
            elif k == 'Home':
                oldright = oldleft + oldright
                newleft = ''
            elif k == 'Left':
                if len(oldleft) > 0:
                    oldright = oldleft[len(oldleft) - 1:] + oldright
                    newleft = oldleft[:len(oldleft) - 1]
            elif k == 'Right':
                if len(oldright) > 0:
                    newleft = oldleft + oldright[0]
                    oldright = oldright[1:]
            elif k == 'End':
                newleft = oldleft + oldright
                oldright = ''
            elif k == 'Return':
                newleft = oldleft + RETURN
            else:
                if self.dead_key is not None:
                    u = DEAD_DICTS[DEAD_KEYS.index(self.dead_key[5:])][k]
                if k in WHITE_SPACE:
                    u = 32
                if unichr(u) != '\x00':
                    newleft = oldleft + unichr(u)
                else:
                    newleft = oldleft + k
            label = newleft + CURSOR + oldright
            self.edit_card.spr.set_label(label)
            (i, j) = WORD_CARD_MAP[self.edit_card.index]
            self.word_lists[i][j] = label.replace(CURSOR, '')
            self.dead_key = None
        else:
            if k in KEYMAP:
                return self._process_selection(
                           self.grid.grid_to_spr(KEYMAP.index(k)))
        return True

    def _expose_cb(self, win, event):
        ''' Callback to handle window expose events '''
        self.do_expose_event(event)
        return True

    # Handle the expose-event by drawing
    def do_expose_event(self, event):

        # Create the cairo context
        cr = self.canvas.window.cairo_create()

        # Restrict Cairo to the exposed area; avoid extra work
        cr.rectangle(event.area.x, event.area.y,
                event.area.width, event.area.height)
        cr.clip()

        # Refresh sprite list
        if cr is not None:
            self.sprites.redraw_sprites(cr=cr)

    def _destroy_cb(self, win, event):
        ''' This is the end '''
        gtk.main_quit()

    def _update_labels(self):
        ''' Write strings to a label in the toolbar. '''
        self.set_label('deck', '%d %s' %
            (self.deck.cards_remaining(), _('cards')))
        self.set_label('status', '')
        if self.matches == 1:
            if self.robot_matches > 0:
                self.set_label('match', '%d (%d) %s' % (
                    self.matches - self.robot_matches, self.robot_matches,
                    _('match')))
            else:
                self.set_label('match', '%d %s' % (self.matches, _('match')))
        else:
            if self.robot_matches > 0:
                self.set_label('match', '%d (%d) %s' % (
                    self.matches - self.robot_matches, self.robot_matches,
                    _('matches')))
            else:
                self.set_label('match', '%d %s' % (self.matches, _('matches')))

    def set_label(self, label, s):
        ''' Update the toolbar labels '''
        if self.sugar:
            if label == 'deck':
                self.activity.deck_label.set_text(s)
            elif label == 'status':
                self.activity.status_label.set_text(s)
            elif label == 'clock':
                self.activity.clock_label.set_text(s)
            elif label == 'match':
                self.activity.match_label.set_text(s)
        else:
            if hasattr(self, 'win') and label is not 'clock':
                self.win.set_title('%s: %s' % (_('Visual Match'), s))

    def _restore_clicked(self, saved_selected_indices):
        ''' Restore the selected cards upon resume or share. '''
        j = 0
        for i in saved_selected_indices:
            _logger.debug('restoring %s' % (str(i)))
            if i is None:
                self.clicked[j][0] = None
            else:
                self.clicked[j][0] = self.deck.index_to_card(i).spr
                k = self.grid.spr_to_grid(self.clicked[j][0])
                self.clicked[j][0].move(self.grid.match_to_xy(j))
                self.clicked[j][1] = self.grid.match_to_xy(j)[0]
                self.clicked[j][2] = self.grid.match_to_xy(j)[1]
                self.clicked[j][0].set_layer(2000)
            j += 1
        self._process_selection(None)

    def _restore_matches(self, saved_match_list_indices):
        ''' Restore the match list upon resume or share. '''
        j = 0
        self.match_list = []
        for i in saved_match_list_indices:
            if i is not None:
                self.match_list.append(self.deck.index_to_card(i).spr)
        '''
        if self.matches > 0:
            l = len(self.match_list)
            for j in range(3):
                self.grid.display_match(self.match_list[l - 3 + j], j)
            self._matches_on_display = True
        '''

    def _restore_word_list(self, saved_word_list):
        ''' Restore the word list upon resume or share. '''
        if len(saved_word_list) == 9:
            for i in range(3):
                for j in range(3):
                    self.word_lists[i][j] = saved_word_list[i * 3 + j]

    def _counter(self):
        ''' Display of seconds since start_time. '''
        seconds = int(gobject.get_current_time() - self.start_time)
        self.set_label('clock', str(seconds))
        if self.robot and self.robot_time < seconds:
            self._find_a_match(robot_match=True)
        else:
            self.timeout_id = gobject.timeout_add(1000, self._counter)

    def _timer_reset(self):
        ''' Reset the timer for the robot '''
        self.start_time = gobject.get_current_time()
        self.timeout_id = None
        self._counter()

    def _show_matches(self, i):
        ''' Show all the matches as a simple animation. '''
        if i < self.matches:
            for j in range(3):
                self.grid.display_match(self.match_list[i * 3 + j], j)
            self.match_timeout_id = gobject.timeout_add(
                2000, self._show_matches, i + 1)

    def _find_a_match(self, robot_match=False):
        ''' Check to see whether there are any matches on the board. '''
        if robot_match:
            # Before robot finds a match: restore any cards in match area
            if self._matches_on_display:
                self.match_list[-1].hide()
                self.match_list[-2].hide()
                self.match_list[-3].hide()
                # And unselect clicked cards
                self.clicked = [[None, 0, 0], [None, 0, 0], [None, 0, 0]]
                self.smiley[-1].spr.hide()
                self._matches_on_display = False
            else:
                for j in range(3):
                    if self.clicked[j][0] is not None:
                        k = self.grid.xy_to_grid((self.clicked[j][1],
                                                  self.clicked[j][2]))
                        self.clicked[j][0].move((self.clicked[j][1],
                                                 self.clicked[j][2]))
                        self.grid.grid[k] = self.deck.spr_to_card(
                            self.clicked[j][0])
                        self.clicked[j][0] = None

        a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
        for i in Permutation(a):  # TODO: really should be combination
            cardarray = [self.grid.grid[i[0]],
                         self.grid.grid[i[1]],
                         self.grid.grid[i[2]]]
            if self._match_check(cardarray, self.card_type):
                if robot_match:
                    # Move robot match to match area
                    for j in range(3):
                        self.clicked[j][0] = self.grid.grid[i[j]].spr
                        self.grid.grid[i[j]].spr.move(
                            self.grid.match_to_xy(j))
                        self.grid.grid[i[j]] = None
                    self.robot_matches += 1
                    self._test_for_a_match()
                    self._matches_on_display = True
                return True
        return False

    def _match_check(self, cardarray, card_type):
        ''' For each attribute, either it is the same or different. '''
        for a in cardarray:
            if a is None:
                return False

        if (cardarray[0].shape + cardarray[1].shape + cardarray[2].shape) % 3\
               != 0:
            self._failure = 0
            return False
        if (cardarray[0].color + cardarray[1].color + cardarray[2].color) % 3\
               != 0:
            self._failure = 1
            return False
        if (cardarray[0].fill + cardarray[1].fill + cardarray[2].fill) % 3\
               != 0:
            self._failure = 2
            return False
        # Special case: only check number when shapes are the same
        if card_type == 'word':
            if cardarray[0].shape == cardarray[1].shape and \
                  cardarray[0].shape == cardarray[2].shape and \
                  (cardarray[0].num + cardarray[1].num + cardarray[2].num) % 3\
                  != 0:
                return False
        else:
            if (cardarray[0].num + cardarray[1].num + cardarray[2].num) % 3\
                   != 0:
                self._failure = 3
                return False
        return True

    def _choose_custom_card(self):
        ''' Select a custom card from the Journal '''
        chooser = None
        name = None
        if hasattr(mime, 'GENERIC_TYPE_IMAGE'):
            # See #2398
            if 'image/svg+xml' not in \
                    mime.get_generic_type(mime.GENERIC_TYPE_IMAGE).mime_types:
                mime.get_generic_type(
                    mime.GENERIC_TYPE_IMAGE).mime_types.append('image/svg+xml')
            chooser = ObjectChooser(parent=self.activity,
                                    what_filter=mime.GENERIC_TYPE_IMAGE)
        else:
            try:
                chooser = ObjectChooser(parent=self, what_filter=None)
            except TypeError:
                chooser = ObjectChooser(None, self.activity,
                    gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)

        if chooser is not None:
            try:
                result = chooser.run()
                if result == gtk.RESPONSE_ACCEPT:
                    jobject = chooser.get_selected_object()
                    if jobject and jobject.file_path:
                        name = jobject.metadata['title']
                        mime_type = jobject.metadata['mime_type']
                        _logger.debug('result of choose: %s (%s)' % \
                                          (name, str(mime_type)))
            finally:
                chooser.destroy()
                del chooser

            if name is not None:
                self._find_custom_paths(jobject)

    def _find_custom_paths(self, jobject):
        ''' Associate a Journal object with a card '''
        found_a_sequence = False
        if self.custom_paths[0] is None:
            basename, suffix, i = _find_the_number_in_the_name(
                jobject.metadata['title'])
            ''' If this is the first card, try to find paths for other custom
            cards based on the name; else just load the card. '''
            if i >= 0:
                dsobjects, nobjects = datastore.find(
                    {'mime_type': [str(jobject.metadata['mime_type'])]})
                self.custom_paths = []
                if nobjects > 0:
                    for j in range(DECKSIZE):
                        for i in range(nobjects):
                            if dsobjects[i].metadata['title'] == \
                                    _construct_a_name(basename, j + 1, suffix):
                                self.custom_paths.append(dsobjects[i])
                                break

                if len(self.custom_paths) < 9:
                    for i in range(3, 81):
                        self.custom_paths.append(
                            self.custom_paths[int(i / 27)])
                elif len(self.custom_paths) < 27:
                    for i in range(9, 81):
                        self.custom_paths.append(
                            self.custom_paths[int(i / 9)])
                elif len(self.custom_paths) < 81:
                    for i in range(9, 81):
                        self.custom_paths.append(
                            self.custom_paths[int(i / 3)])
                found_a_sequence = True
                self.activity.metadata['custom_object'] = jobject.object_id
                self.activity.metadata['custom_mime_type'] = \
                    jobject.metadata['mime_type']

        if not found_a_sequence:
            grid_index = self.grid.spr_to_grid(self.edit_card.spr)
            self.custom_paths[grid_index] = jobject
            self.activity.metadata['custom_' + str(grid_index)] = \
                jobject.object_id

        self.card_type = 'custom'
        self.activity.button_custom.set_icon('new-custom-game')
        self.activity.button_custom.set_tooltip(_('New custom game'))
        return


class Permutation:
    '''Permutaion class for checking for all possible matches on the grid '''

    def __init__(self, elist):
        self._data = elist[:]
        self._sofar = []

    def __iter__(self):
        return self.next()

    def next(self):
        for e in self._data:
            if e not in self._sofar:
                self._sofar.append(e)
                if len(self._sofar) == 3:
                    yield self._sofar[:]
                else:
                    for v in self.next():
                        yield v
                self._sofar.pop()