-
Notifications
You must be signed in to change notification settings - Fork 105
/
Copy pathstack.py
3355 lines (2919 loc) · 118 KB
/
stack.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
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
#!/usr/bin/env python
# -*- mode: python; coding: utf-8; -*-
# ---------------------------------------------------------------------------
#
# Copyright (C) 1998-2003 Markus Franz Xaver Johannes Oberhumer
# Copyright (C) 2003 Mt. Hood Playing Card Co.
# Copyright (C) 2005-2009 Skomoroh
#
# 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.
#
# 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, see <http://www.gnu.org/licenses/>.
#
# ---------------------------------------------------------------------------
from pysollib.mfxutil import Image, ImageTk, USE_PIL
from pysollib.mfxutil import Struct, SubclassResponsibility, kwdefault
from pysollib.mygettext import _
from pysollib.pysoltk import ANCHOR_NW, ANCHOR_SE
from pysollib.pysoltk import CURSOR_DOWN_ARROW, CURSOR_DRAG
from pysollib.pysoltk import EVENT_HANDLED, EVENT_PROPAGATE
from pysollib.pysoltk import MfxCanvasGroup, MfxCanvasImage
from pysollib.pysoltk import MfxCanvasRectangle, MfxCanvasText
from pysollib.pysoltk import after_cancel, after_idle
from pysollib.pysoltk import bind, unbind_destroy
from pysollib.pysoltk import get_text_width
from pysollib.pysoltk import markImage
from pysollib.settings import DEBUG
from pysollib.settings import TOOLKIT
from pysollib.util import ACE, KING
from pysollib.util import ANY_RANK, ANY_SUIT, NO_RANK
# ************************************************************************
# * Let's start with some test methods for cards.
# * Empty card-lists return false.
# ************************************************************************
# check that all cards are face-up
def cardsFaceUp(cards):
if not cards:
return False
for c in cards:
if not c.face_up:
return False
return True
# check that all cards are face-down
def cardsFaceDown(cards):
if not cards:
return False
for c in cards:
if c.face_up:
return False
return True
# check that cards are face-up and build down by rank
def isRankSequence(cards, mod=8192, dir=-1):
if not cardsFaceUp(cards):
return False
c1 = cards[0]
for c2 in cards[1:]:
if (c1.rank + dir) % mod != c2.rank:
return False
c1 = c2
return True
# check that cards are face-up and build down by alternate color
def isAlternateColorSequence(cards, mod=8192, dir=-1):
if not cardsFaceUp(cards):
return False
c1 = cards[0]
for c2 in cards[1:]:
if (c1.rank + dir) % mod != c2.rank or c1.color == c2.color:
return False
c1 = c2
return True
# check that cards are face-up and build down by same color
def isSameColorSequence(cards, mod=8192, dir=-1):
if not cardsFaceUp(cards):
return False
c1 = cards[0]
for c2 in cards[1:]:
if (c1.rank + dir) % mod != c2.rank or c1.color != c2.color:
return False
c1 = c2
return True
# check that cards are face-up and build down by same suit
def isSameSuitSequence(cards, mod=8192, dir=-1):
if not cardsFaceUp(cards):
return False
c1 = cards[0]
for c2 in cards[1:]:
if (c1.rank + dir) % mod != c2.rank or c1.suit != c2.suit:
return False
c1 = c2
return True
# check that cards are face-up and build down by any suit but own
def isAnySuitButOwnSequence(cards, mod=8192, dir=-1):
if not cardsFaceUp(cards):
return False
c1 = cards[0]
for c2 in cards[1:]:
if (c1.rank + dir) % mod != c2.rank or c1.suit == c2.suit:
return False
c1 = c2
return True
def getNumberOfFreeStacks(stacks):
return len([s for s in stacks if not s.cards])
# collect the top cards of several stacks into a pile
def getPileFromStacks(stacks, reverse=False):
cards = []
for s in stacks:
if not s.cards or not s.cards[-1].face_up:
return None
cards.append(s.cards[-1])
return (reversed(cards) if reverse else cards)
class Stack:
# A generic stack of cards.
#
# This is used as a base class for all other stacks (e.g. the talon,
# the foundations and the row stacks).
#
# The default event handlers turn the top card of the stack with
# its face up on a (single or double) click, and also support
# moving a subpile around.
# constants
MIN_VISIBLE_XOFFSET = 3
MIN_VISIBLE_YOFFSET = 3
SHRINK_FACTOR = 2.
def __init__(self, x, y, game, cap={}):
# Arguments are the stack's nominal x and y position (the top
# left corner of the first card placed in the stack), and the
# game object (which is used to get the canvas; subclasses use
# the game object to find other stacks).
#
# link back to game
#
id = len(game.allstacks)
game.allstacks.append(self)
x = int(round(x))
y = int(round(y))
mapkey = (x, y)
# assert not game.stackmap.has_key(mapkey) ## can happen in PyJonngg
game.stackmap[mapkey] = id
#
# setup our pseudo MVC scheme
#
model, view = self, self
#
# model
#
model.id = id
model.game = game
model.cards = []
#
model.is_filled = False
# capabilites - the game logic
model.cap = Struct(
suit=-1, # required suit for this stack (-1 is ANY_SUIT)
color=-1, # required color for this stack (-1 is ANY_COLOR)
rank=-1, # required rank for this stack (-1 is ANY_RANK)
base_suit=-1, # base suit for this stack (-1 is ANY_SUIT)
base_color=-1, # base color for this stack (-1 is ANY_COLOR)
base_rank=-1, # base rank for this stack (-1 is ANY_RANK)
dir=0, # direction - stack builds up/down
mod=8192, # modulo for wrap around (typically 13 or 8192)
max_move=0, # can move at most # cards at a time
max_accept=0, # can accept at most # cards at a time
max_cards=999999, # total number of cards may not exceed this
# not commonly used:
min_move=1, # must move at least # cards at a time
min_accept=1, # must accept at least # cards at a time
# total number of cards this stack at least requires
min_cards=0,
)
model.cap.update(cap)
assert isinstance(model.cap.suit, int)
assert isinstance(model.cap.color, int)
assert isinstance(model.cap.rank, int)
assert isinstance(model.cap.base_suit, int)
assert isinstance(model.cap.base_color, int)
assert isinstance(model.cap.base_rank, int)
#
# view
#
self.init_coord = (x, y)
view.x = x
view.y = y
view.canvas = game.canvas
view.CARD_XOFFSET = 0
view.CARD_YOFFSET = 0
view.INIT_CARD_OFFSETS = (0, 0)
view.INIT_CARD_YOFFSET = 0 # for reallocateCards
view.group = MfxCanvasGroup(view.canvas)
if (TOOLKIT == 'kivy'):
if hasattr(view.group, 'stack'):
view.group.stack = self
view.shrink_face_down = 1
# image items
view.images = Struct(
bottom=None, # canvas item
redeal=None, # canvas item
redeal_img=None, # the corresponding PhotoImage
shade_img=None,
)
# other canvas items
view.items = Struct(
bottom=None, # dummy canvas item
shade_item=None,
)
# text items
view.texts = Struct(
ncards=None, # canvas item
# by default only used by Talon:
rounds=None, # canvas item
redeal=None, # canvas item
redeal_str=None, # the corresponding string
# for use by derived stacks:
misc=None, # canvas item
)
view.top_bottom = None # the highest of all bottom items
cardw, cardh = game.app.images.CARDW, game.app.images.CARDH
dx, dy = cardw+view.canvas.xmargin, cardh+view.canvas.ymargin
view.is_visible = view.x >= -dx and view.y >= -dy
view.is_open = -1
view.can_hide_cards = -1
view.max_shadow_cards = -1
view.current_cursor = ''
view.cursor_changed = False
def destruct(self):
# help breaking circular references
unbind_destroy(self.group)
def prepareStack(self):
self.prepareView()
if self.is_visible:
self.initBindings()
def _calcMouseBind(self, binding_format):
return self.game.app.opt.calcCustomMouseButtonsBinding(binding_format)
# bindings {view widgets bind to controller}
def initBindings(self):
group = self.group
bind(group, self._calcMouseBind("<{mouse_button1}>"),
self.__clickEventHandler)
# bind(group, "<B1-Motion>", self.__motionEventHandler)
bind(group, "<Motion>", self.__motionEventHandler)
bind(group, self._calcMouseBind("<ButtonRelease-{mouse_button1}>"),
self.__releaseEventHandler)
bind(group, self._calcMouseBind("<Control-{mouse_button1}>"),
self.__controlclickEventHandler)
bind(group, self._calcMouseBind("<Shift-{mouse_button1}>"),
self.__shiftclickEventHandler)
bind(group, self._calcMouseBind("<Double-{mouse_button1}>"),
self.__doubleclickEventHandler)
bind(group, self._calcMouseBind("<{mouse_button3}>"),
self.__rightclickEventHandler)
bind(group, self._calcMouseBind("<{mouse_button2}>"),
self.__middleclickEventHandler)
bind(group, self._calcMouseBind("<Control-{mouse_button3}>"),
self.__middleclickEventHandler)
# bind(group, self._calcMouseBind(
# "<Control-{mouse_button2}>"), self.__controlmiddleclickEventHandler)
# bind(group, self._calcMouseBind("<Shift-{mouse_button3}>"),
# self.__shiftrightclickEventHandler)
# bind(group, self._calcMouseBind("<Double-{mouse_button2}>"), "")
bind(group, "<Enter>", self.__enterEventHandler)
bind(group, "<Leave>", self.__leaveEventHandler)
def prepareView(self):
# assertView(self)
if (self.CARD_XOFFSET == 0 and self.CARD_YOFFSET == 0):
assert self.cap.max_move <= 1
# prepare some variables
ox, oy = self.CARD_XOFFSET, self.CARD_YOFFSET
if isinstance(ox, (int, float)):
self.CARD_XOFFSET = (ox,)
else:
self.CARD_XOFFSET = tuple([int(round(x)) for x in ox])
if isinstance(oy, (int, float)):
self.CARD_YOFFSET = (oy,)
else:
self.CARD_YOFFSET = tuple([int(round(y)) for y in oy])
# preserve offsets
# for resize()
self.INIT_CARD_OFFSETS = (self.CARD_XOFFSET, self.CARD_YOFFSET)
self.INIT_CARD_YOFFSET = self.CARD_YOFFSET # for reallocateCards
if self.can_hide_cards < 0:
self.can_hide_cards = self.is_visible
if self.cap.max_cards < 3:
self.can_hide_cards = 0
elif [_f for _f in self.CARD_XOFFSET if _f]:
self.can_hide_cards = 0
elif [_f for _f in self.CARD_YOFFSET if _f]:
self.can_hide_cards = 0
elif self.canvas.preview:
self.can_hide_cards = 0
if self.is_open < 0:
self.is_open = False
if (self.is_visible and
(abs(self.CARD_XOFFSET[0]) >= self.MIN_VISIBLE_XOFFSET or
abs(self.CARD_YOFFSET[0]) >= self.MIN_VISIBLE_YOFFSET)):
self.is_open = True
if self.max_shadow_cards < 0:
self.max_shadow_cards = 999999
# if abs(self.CARD_YOFFSET[0])
# != self.game.app.images.CARD_YOFFSET:
# # don't display a shadow if the YOFFSET of the stack
# # and the images don't match
# self.max_shadow_cards = 1
if (self.game.app.opt.shrink_face_down and
isinstance(ox, (int, float)) and
isinstance(oy, (int, float))):
# no shrink if xoffset/yoffset too small
f = self.SHRINK_FACTOR
if ((ox == 0 and oy >= self.game.app.images.CARD_YOFFSET//f) or
(oy == 0 and
ox >= self.game.app.images.CARD_XOFFSET//f)):
self.shrink_face_down = f
# bottom image
if self.is_visible:
self.prepareBottom()
# stack bottom image
def prepareBottom(self):
assert self.is_visible and self.images.bottom is None
img = self.getBottomImage()
if img is not None:
self.images.bottom = MfxCanvasImage(self.canvas, self.x, self.y,
image=img, anchor=ANCHOR_NW,
group=self.group)
self.top_bottom = self.images.bottom
# invisible stack bottom
# We need this if we want to get any events for an empty stack (which
# is needed by the quickPlayHandler in some games like Montana)
def prepareInvisibleBottom(self):
assert self.is_visible and self.items.bottom is None
images = self.game.app.images
self.items.bottom = MfxCanvasRectangle(self.canvas, self.x, self.y,
self.x + images.CARDW,
self.y + images.CARDH,
fill="", outline="", width=0,
group=self.group)
self.top_bottom = self.items.bottom
# sanity checks
def assertStack(self):
assert self.cap.min_move > 0
assert self.cap.min_accept > 0
assert not hasattr(self, "suit")
#
# Core access methods {model -> view}
#
# Add a card add the top of a stack. Also update display. {model -> view}
def addCard(self, card, unhide=1, update=1):
model, view = self, self
model.cards.append(card)
card.tkraise(unhide=unhide)
if view.can_hide_cards and len(model.cards) >= 3:
# we only need to display the 2 top cards
model.cards[-3].hide(self)
card.item.addtag(view.group)
view._position(card)
if update:
view.updateText()
self.closeStack()
return card
def insertCard(self, card, position, unhide=1, update=1):
model, view = self, self
model.cards.insert(position, card)
for c in model.cards[position:]:
c.tkraise(unhide=unhide)
if (view.can_hide_cards and len(model.cards) >= 3 and
len(model.cards)-position <= 2):
# we only need to display the 2 top cards
model.cards[-3].hide(self)
card.item.addtag(view.group)
for c in model.cards[position:]:
view._position(c)
if update:
view.updateText()
self.closeStack()
return card
# Remove a card from the stack. Also update display. {model -> view}
def removeCard(self, card=None, unhide=1, update=1, update_positions=0):
model, view = self, self
assert len(model.cards) > 0
if card is None:
card = model.cards[-1]
# optimized a little bit (compare with the else below)
card.item.dtag(view.group)
if unhide and self.can_hide_cards:
card.unhide()
if len(self.cards) >= 3:
model.cards[-3].unhide()
del model.cards[-1]
else:
card.item.dtag(view.group)
if unhide and view.can_hide_cards:
# Note: the 2 top cards ([-1] and [-2]) are already unhidden.
card.unhide()
if len(model.cards) >= 3:
if card is model.cards[-1] or model is self.cards[-2]:
# Make sure that 2 top cards will be un-hidden.
model.cards[-3].unhide()
card_index = model.cards.index(card)
model.cards.remove(card)
if update_positions:
for c in model.cards[card_index:]:
view._position(c)
if update:
view.updateText()
self.unshadeStack()
self.is_filled = False
return card
# Get the top card {model}
def getCard(self):
if self.cards:
return self.cards[-1]
return None
# get the largest moveable pile {model} - uses canMoveCards()
def getPile(self):
if self.cap.max_move > 0:
cards = self.cards[-self.cap.max_move:]
while len(cards) >= self.cap.min_move:
if self.canMoveCards(cards):
return cards
del cards[0]
return None
# Position the card on the canvas {view}
def _position(self, card):
x, y = self.getPositionFor(card)
card.moveTo(x, y)
# find card
def _findCard(self, event):
model, view = self, self
if event is not None and model.cards:
# ask the canvas
return view.canvas.findCard(self, event)
return -1
# find card
def _findCardXY(self, x, y, cards=None):
model = self
if cards is None:
cards = model.cards
images = self.game.app.images
cw, ch = images.getSize()
index = -1
for i in range(len(cards)):
c = cards[i]
r = (c.x, c.y, c.x + cw, c.y + ch)
if r[0] <= x < r[2] and r[1] <= y < r[3]:
index = i
return index
# generic model update (can be used for undo/redo - see move.py)
def updateModel(self, undo, flags):
pass
# copy model data - see Hint.AClonedStack
def copyModel(self, clone):
clone.id = self.id
clone.game = self.game
clone.cap = self.cap
def getRankDir(self, cards=None):
if cards is None:
cards = self.cards[-2:]
if len(cards) < 2:
return 0
dir = (cards[-1].rank - cards[-2].rank) % self.cap.mod
if dir > self.cap.mod // 2:
return dir - self.cap.mod
return dir
#
# Basic capabilities {model}
# Used by various subclasses.
#
def basicIsBlocked(self):
# Check if the stack is blocked (e.g. Pyramid or Mahjongg)
return False
def basicAcceptsCards(self, from_stack, cards):
# Check that the limits are ok and that the cards are face up
if from_stack is self or self.basicIsBlocked():
return False
cap = self.cap
mylen = len(cards)
if mylen < cap.min_accept or mylen > cap.max_accept:
return False
mylen += len(self.cards)
# note: we don't check cap.min_cards here
if mylen > cap.max_cards:
return False
def _check(c, suit, color, rank):
return ((suit >= 0 and c.suit != suit) or
(color >= 0 and c.color != color) or
(rank >= 0 and c.rank != rank))
for c in cards:
if not c.face_up or _check(c, cap.suit, cap.color, cap.rank):
return False
if self.cards:
# top card of our stack must be face up
return self.cards[-1].face_up
# check required base
return not _check(cards[0], cap.base_suit, cap.base_color,
cap.base_rank)
def basicCanMoveCards(self, cards):
# Check that the limits are ok and the cards are face up
if self.basicIsBlocked():
return False
cap = self.cap
mylen = len(cards)
if mylen < cap.min_move or mylen > cap.max_move:
return False
mylen = len(self.cards) - mylen
# note: we don't check cap.max_cards here
if mylen < cap.min_cards:
return False
return cardsFaceUp(cards)
#
# Capabilities - important for game logic {model}
#
def acceptsCards(self, from_stack, cards):
# Do we accept receiving `cards' from `from_stack' ?
return False
def canMoveCards(self, cards):
# Can we move these cards when assuming they are our top-cards ?
return False
def canFlipCard(self):
# Can we flip our top card ?
return False
def canDropCards(self, stacks):
# Can we drop the top cards onto one of the foundation stacks ?
return (None, 0) # return the stack and the number of cards
#
# State {model}
#
def resetGame(self):
# Called when starting a new game.
self.CARD_YOFFSET = self.INIT_CARD_YOFFSET
self.items.shade_item = None
self.images.shade_img = None
# self.items.bottom = None
# self.images.bottom = None
def __repr__(self):
# Return a string for debug print statements.
return "%s(%d)" % (self.__class__.__name__, self.id)
#
# Atomic move actions {model -> view}
#
def flipMove(self, animation=False):
# Flip the top card.
if animation:
self.game.singleFlipMove(self)
else:
self.game.flipMove(self)
def moveMove(self, ncards, to_stack, frames=-1, shadow=-1):
# Move the top n cards.
self.game.moveMove(
ncards, self, to_stack, frames=frames, shadow=shadow)
self.fillStack()
def fillStack(self):
self.game.fillStack(self)
def closeStack(self):
pass
#
# Playing move actions. Better not override.
#
def playFlipMove(self, sound=True, animation=False):
if sound:
self.game.playSample("flip", 5)
self.flipMove(animation=animation)
if not self.game.checkForWin():
self.game.autoPlay()
self.game.finishMove()
def playMoveMove(self, ncards, to_stack, frames=-1, shadow=-1, sound=True):
if sound:
if to_stack in self.game.s.foundations:
self.game.playSample("drop", priority=30)
else:
self.game.playSample("move", priority=10)
self.moveMove(ncards, to_stack, frames=frames, shadow=shadow)
if not self.game.checkForWin():
# let the player put cards back from the foundations
if self not in self.game.s.foundations:
self.game.autoPlay()
self.game.finishMove()
#
# Appearance {view}
#
def _getBlankBottomImage(self):
return self.game.app.images.getBlankBottom()
def _getReserveBottomImage(self):
return self.game.app.images.getReserveBottom()
def _getSuitBottomImage(self):
return self.game.app.images.getSuitBottom(self.cap.base_suit)
def _getNoneBottomImage(self):
return None
def _getTalonBottomImage(self):
return self.game.app.images.getTalonBottom()
def _getBraidBottomImage(self):
return self.game.app.images.getBraidBottom()
def _getLetterImage(self):
return self.game.app.images.getLetter(self.cap.base_rank)
getBottomImage = _getBlankBottomImage
def getPositionFor(self, card):
model, view = self, self
x, y = view.x, view.y
if view.can_hide_cards:
return x, y
ix, iy, lx, ly = 0, 0, len(view.CARD_XOFFSET), len(view.CARD_YOFFSET)
d = self.shrink_face_down
for c in model.cards:
if c is card:
break
if c.face_up:
x += self.CARD_XOFFSET[ix]
y += self.CARD_YOFFSET[iy]
else:
x += self.CARD_XOFFSET[ix]//d
y += self.CARD_YOFFSET[iy]//d
ix = (ix + 1) % lx
iy = (iy + 1) % ly
return int(x), int(y)
def getPositionForNextCard(self):
model, view = self, self
x, y = view.x, view.y
if view.can_hide_cards:
return x, y
if not self.cards:
return x, y
ix, iy, lx, ly = 0, 0, len(view.CARD_XOFFSET), len(view.CARD_YOFFSET)
d = self.shrink_face_down
for c in model.cards:
if c.face_up:
x += self.CARD_XOFFSET[ix]
y += self.CARD_YOFFSET[iy]
else:
x += self.CARD_XOFFSET[ix]//d
y += self.CARD_YOFFSET[iy]//d
ix = (ix + 1) % lx
iy = (iy + 1) % ly
return int(x), int(y)
def getOffsetFor(self, card):
model, view = self, self
if view.can_hide_cards:
return 0, 0
lx, ly = len(view.CARD_XOFFSET), len(view.CARD_YOFFSET)
i = list(model.cards).index(card)
return view.CARD_XOFFSET[i % lx], view.CARD_YOFFSET[i % ly]
# Fully update the view of a stack - updates
# hiding, card positions and stacking order.
# Avoid calling this as it is rather slow.
def refreshView(self):
model, view = self, self
cards = model.cards
if not view.is_visible or len(cards) < 2:
return
if view.can_hide_cards:
# hide all lower cards
for c in cards[:-2]:
# print "refresh hide", c, c.hide_stack
c.hide(self)
# unhide the 2 top cards
for c in cards[-2:]:
# print "refresh unhide 1", c, c.hide_stack
c.unhide()
# print "refresh unhide 1", c, c.hide_stack
# update the card postions and stacking order
item = cards[0].item
x, y = view.x, view.y
ix, iy, lx, ly = 0, 0, len(view.CARD_XOFFSET), len(view.CARD_YOFFSET)
for c in cards[1:]:
c.item.tkraise(item)
item = c.item
if not view.can_hide_cards:
d = self.shrink_face_down
if c.face_up:
x += self.CARD_XOFFSET[ix]
y += self.CARD_YOFFSET[iy]
else:
x += int(self.CARD_XOFFSET[ix]/d)
y += int(self.CARD_YOFFSET[iy]/d)
ix = (ix + 1) % lx
iy = (iy + 1) % ly
c.moveTo(x, y)
def updateText(self):
if self.game.preview > 1 or self.texts.ncards is None:
return
t = ""
format = "%d"
if self.texts.ncards.text_format is not None:
format = self.texts.ncards.text_format
if format == "%D":
format = ""
if self.cards:
format = "%d"
if format:
t = format % len(self.cards)
# if 0:
# visible = 0
# for c in self.cards:
# if c.isHidden():
# assert c.hide_stack is not None
# else:
# visible = visible + 1
# assert c.hide_stack is None
# t = t + " (%d)" % visible
self.texts.ncards.config(text=t)
def updatePositions(self):
# compact the stack when a cards goes off screen
if self.reallocateCards():
for c in self.cards:
self._position(c)
def reallocateCards(self):
# change CARD_YOFFSET if a cards is off-screen
# returned False if CARD_YOFFSET is not changed, otherwise True
if not self.game.app.opt.compact_stacks:
return False
if TOOLKIT != 'tk':
return False
if self.CARD_XOFFSET != (0,):
return False
if len(self.CARD_YOFFSET) != 1:
return False
if self.CARD_YOFFSET[0] <= 0:
return False
if len(self.cards) <= 1:
return False
if not self.canvas.winfo_ismapped():
return False
yoffset = self.CARD_YOFFSET[0]
# 1/2 of a card is visible
cardh = self.game.app.images.getSize()[0] // 2
num_face_up = len([c for c in self.cards if c.face_up])
num_face_down = len(self.cards) - num_face_up
stack_height = int(self.y +
num_face_down * yoffset // self.shrink_face_down +
num_face_up * yoffset +
cardh)
visible_height = self.canvas.winfo_height()
if USE_PIL and self.game.app.opt.auto_scale:
# use visible_height only
game_height = 0
else:
game_height = self.game.height + 2*self.canvas.ymargin
height = max(visible_height, game_height)
# print 'reallocateCards:', stack_height, height, \
# visible_height, game_height
if stack_height > height:
# compact stack
n = num_face_down // self.shrink_face_down + num_face_up
dy = float(height - self.y - cardh) / n
if dy < yoffset:
# print 'compact:', dy
self.CARD_YOFFSET = (dy,)
return True
elif stack_height < height:
# expande stack
if self.CARD_YOFFSET == self.INIT_CARD_YOFFSET:
return False
n = num_face_down // self.shrink_face_down + num_face_up
dy = float(height - self.y - cardh) / n
dy = min(dy, self.INIT_CARD_YOFFSET[0])
# print 'expande:', dy
self.CARD_YOFFSET = (dy,)
return True
return False
def resize(self, xf, yf, widthpad=0, heightpad=0):
# resize and move stack
# xf, yf - a multiplicative factor (from the original values)
# print 'Stack.resize:', self, self.is_visible, xf, yf
x0, y0 = self.init_coord
if (x0 > 0):
x0 += widthpad
if (y0 > 0):
y0 += heightpad
x, y = int(round(x0*xf)), int(round(y0*yf))
self.x, self.y = x, y
# offsets
xoffset = tuple(int(round(i*xf)) for i in self.INIT_CARD_OFFSETS[0])
yoffset = tuple(int(round(i*yf)) for i in self.INIT_CARD_OFFSETS[1])
self.CARD_XOFFSET = xoffset
self.CARD_YOFFSET = yoffset
self.INIT_CARD_YOFFSET = yoffset
# print '* resize offset:', self.INIT_CARD_XOFFSET,
# move cards
for c in self.cards:
cx, cy = self.getPositionFor(c)
c.moveTo(cx, cy)
# ---
if not self.is_visible:
return
# bottom and shade
if self.images.bottom:
img = self.getBottomImage()
self.images.bottom['image'] = img
self.images.bottom.moveTo(x, y)
if self.items.bottom:
c = self.items.bottom.coords()
c = ((int(round(c[0]*xf)), int(round(c[1]*yf))),
(int(round(c[2]*xf)), int(round(c[3]*yf))))
self.items.bottom.coords(c)
if self.items.shade_item:
c = self.cards[-1]
img = self.game.app.images.getHighlightedCard(
c.deck, c.suit, c.rank)
if img:
self.items.shade_item['image'] = img
self.items.shade_item.moveTo(x, y)
# move the items
def move(item):
ix, iy = item.init_coord
x = int(round((ix + widthpad) * xf))
y = int(round((iy + heightpad) * yf))
item.moveTo(x, y)
# images
if self.images.redeal:
move(self.images.redeal)
# texts
if self.texts.ncards:
move(self.texts.ncards)
if self.texts.rounds:
move(self.texts.rounds)
if self.texts.redeal:
move(self.texts.redeal)
if self.texts.misc:
move(self.texts.misc)
def basicShallHighlightSameRank(self, card):
# by default all open stacks are available for highlighting
assert card in self.cards
if not self.is_visible or not card.face_up:
return False
if card is self.cards[-1]:
return True
if not self.is_open:
return False
# dx, dy = self.getOffsetFor(card)
# if ((dx == 0 and dy <= self.MIN_VISIBLE_XOFFSET) or
# (dx <= self.MIN_VISIBLE_YOFFSET and dy == 0)):
# return False
return True
def basicShallHighlightMatch(self, card):
# by default all open stacks are available for highlighting
return self.basicShallHighlightSameRank(card)
def highlightSameRank(self, event):
i = self._findCard(event)
if i < 0:
return 0
card = self.cards[i]
if not self.basicShallHighlightSameRank(card):
return 0
col_1 = self.game.app.opt.colors['samerank_1']
col_2 = self.game.app.opt.colors['samerank_2']
info = [(self, card, card, col_1)]
for s in self.game.allstacks:
for c in s.cards:
if c is card:
continue
# check the rank
if c.rank != card.rank:
continue
# ask the target stack
if s.basicShallHighlightSameRank(c):
info.append((s, c, c, col_2))
self.game.stats.highlight_samerank += 1
return self.game._highlightCards(
info, self.game.app.opt.timeouts['highlight_samerank'])
def highlightMatchingCards(self, event):
i = self._findCard(event)
if i < 0:
return 0
card = self.cards[i]
if not self.basicShallHighlightMatch(card):
return 0
col_1 = self.game.app.opt.colors['cards_1']
col_2 = self.game.app.opt.colors['cards_2']
c1 = c2 = card
info = []
found = 0
for s in self.game.allstacks:
# continue if both stacks are foundations
if (self in self.game.s.foundations and
s in self.game.s.foundations):
continue
# for all cards
for c in s.cards:
if c is card:
continue
# ask the target stack
if not s.basicShallHighlightMatch(c):
continue
# ask the game
if self.game.shallHighlightMatch(self, card, s, c):
found = 1
if s is self:
# enlarge rectangle for neighbours
j = self.cards.index(c)
if i - 1 == j:
c1 = c
continue
if i + 1 == j:
c2 = c
continue
info.append((s, c, c, col_1))
if found:
if info:
self.game.stats.highlight_cards += 1
info.append((self, c1, c2, col_2))
return self.game._highlightCards(