-
Notifications
You must be signed in to change notification settings - Fork 0
/
CardGameCreator.py
2622 lines (2433 loc) · 118 KB
/
CardGameCreator.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
from Tkinter import *
from eventBasedAnimationClass import EventBasedAnimationClass
import math, random, sys
from threading import *
import tkMessageBox
import tkSimpleDialog
class CardGameDialog(tkSimpleDialog.Dialog):
"""Custom Dialog boxes, which the user uses to specify
attribute of the game."""
def __init__(self,canvas,dialogType,minMax=False,
canPass=True,seedText=("",),numberOfPlayers=4):
"""Initializes a dialog"""
self.dialogType = dialogType
self.canPass = canPass
self.result = ""
self.entrys = []
self.numberOfPlayers = numberOfPlayers
self.seedText = seedText
if (minMax): (self.minBid,self.maxBid) = minMax
# Next 3 Lines:
# http://svn.python.org/projects/python/trunk/Lib/lib-tk/tkSimpleDialog.py
import Tkinter
parent = Tkinter._default_root
tkSimpleDialog.Dialog.__init__(self, parent)
def body(self, master):
"""Initializes the body of the dialog: labels, text fields, etc."""
if self.dialogType == "bid": self.initBidDialog(master)
elif self.dialogType == "trump": self.initTrumpDialog(master)
elif self.dialogType == "bidtrump": self.initBidTrumpDialog(master)
elif self.dialogType == "omitCards": self.initOmitCardsDialog(master)
elif self.dialogType == "points": self.initPointsDialog(master)
elif self.dialogType == "startingPlayer":self.initStartingPlayer(master)
elif self.dialogType == "pickTrump": self.initPickTrumpDialog(master)
elif self.dialogType == "partners": self.initPartnersDialog(master)
elif self.dialogType == "pickBid": self.initPickBidDialog(master)
elif self.dialogType == "cardOrder": self.initCardOrderDialog(master)
elif self.dialogType == "playerNames":self.initPlayerNamesDialog(master)
elif self.dialogType=="illegalSuits":self.initIllegalSuitsDialog(master)
elif self.dialogType == "winner": self.initWinnerDialog(master)
elif self.dialogType == "pass": self.initPassDialog(master)
elif self.dialogType == "dealOrder": self.initDealOrderDialog(master)
elif self.dialogType == "loadPreset": self.initLoadPresetDialog(master)
elif self.dialogType == "savePreset": self.initSavePresetDialog(master)
elif self.dialogType == "numberOfPlayers":
self.initNumberOfPlayersPresetDialog(master)
elif self.dialogType == "cardsPerPlayer":
self.initCardsPerPlayerPresetDialog(master)
elif self.dialogType == "afterRound":
self.initAfterRoundPresetDialog(master)
return self.entrys[0] # initial focus
def initEntries(self, numOfEntrys, rowCol, master):
"""Initializes the number and locations of Entrys in the dialog"""
for num in xrange(numOfEntrys):
text = StringVar()
self.entrys.append(Entry(master,textvariable=text))
self.entrys[-1].grid(row=rowCol[num][0],column=rowCol[num][1])
text.set(self.seedText[num])
def initBidDialog(self, master):
"""Initializes the bid dialog, used to bid during gameplay"""
Label(master, text="Bid:").grid(row=0)
self.initEntries(1,[(0,1)],master)
def initTrumpDialog(self, master):
"""Initializes the trump dialog, used to set trump during gameplay"""
Label(master, text="Trump:").grid(row=0)
self.initEntries(1,[(0,1)],master)
def initBidTrumpDialog(self, master):
"""Initializes the bidTrump dialog, used to bid a number and a trump"""
Label(master, text="Bid:").grid(row=0)
Label(master, text="Trump:").grid(row=1)
self.initEntries(2,[(0,1),(1,1)],master)
def initOmitCardsDialog(self, master):
"""Initializes the omitCards dialog"""
instructions =("Write suits and/or values to omit separated by a" +
" comma. Ex: 'hearts, clubs 2-7, spades A, clubs Q, K'."+
"\nNOTE: WRITE SUIT BEFORE VALUE")
Label(master, text=instructions).grid(row=0)
self.initEntries(1,[(1,0)],master)
def initPointsDialog(self, master):
"""Initializes the points dialog"""
instructions=("Write suits and/or values, followed by a point value,"+
" separated by commas. Ex: 'hearts 1, spades Q 13, J 1'."+
"\nNOTE: WRITE SUIT BEFORE VALUE")
Label(master, text=instructions).grid(row=0)
self.initEntries(1,[(1,0)],master)
def initStartingPlayer(self, master):
"""Initializes the startingPlayer dialog"""
instructions = ("Write a single suit and value to indicate which card"+
" must start.EX: 'clubs 2'\nOtherwise, write 'dealer'"+
" to indicate that the person to the left of the"+
" dealer starts, or 'winner' for the winner of the"+
" bid to start. \nNOTE: WRITE SUIT BEFORE VALUE")
Label(master, text=instructions).grid(row=0)
self.initEntries(1,[(1,0)],master)
def initPickTrumpDialog(self, master):
"""Initializes the pickTrump dialog,
used to pick trump before gameplay"""
instructions = ("Write a single suit to be trump. If you want the"+
" winner of the bid to set trump,\nwrite 'winner'"+
" (you MUST HAVE A BID for this to work.)\n If"+
" you want a random trump, write 'random'.")
Label(master, text=instructions).grid(row=0)
self.initEntries(1,[(1,0)],master)
def initPartnersDialog(self, master):
"""Initializes the partners dialog"""
instructions = "How are partners determined? EX: 'across'"
Label(master, text=instructions).grid(row=0)
self.initEntries(1,[(1,0)],master)
def initPickBidDialog(self, master):
"""Initializes the pickBid dialog, used to pick bid before gameplay"""
Label(master, text="Min Bid:").grid(row=0, column=0)
Label(master, text="Max Bid:").grid(row=1, column=0)
instructions = ("BidType:'oneByOne' if everyone bids only once,"+
" 'round' if people keep bidding in a circle \nuntil"+
" everyone passes, and 'faceOff' if two people bid"+
" back and forth until one passes.")
Label(master, text=instructions).grid(row=2, column=0)
Label(master, text="Can Pass?: (Y/N)").grid(row=3, column=0)
instructions = ("Can the player before, after, no one, or everyone"+
" match the bid? EX: 'after'")
Label(master, text=instructions).grid(row=4, column=0)
self.initEntries(5,[(0,1),(1,1),(2,1),(3,1),(4,1)],master)
def initCardOrderDialog(self, master):
"""Initializes the cardOrder dialog, used to
pick which cards are higher than others"""
instructions=("Write the order of cards, lowest to highest: EX:"+
" '2,3,4,5,6,7,8,9,10,J,Q,K,A'")
Label(master, text=instructions).grid(row=0)
self.initEntries(1,[(1,0)],master)
def initPlayerNamesDialog(self, master):
"""Initializes the playerNames dialog"""
Label(master, text="Enter Player Names:").grid(row=0, column=1)
if self.numberOfPlayers == 3:
self.initEntries(3,[(1,1),(2,2),(2,0)],master)
elif self.numberOfPlayers == 4:
self.initEntries(4,[(1,1),(2,2),(3,1),(2,0)],master)
elif self.numberOfPlayers == 5:
self.initEntries(5,[(1,1),(2,2),(3,2),(3,0),(2,0)],master)
def initIllegalSuitsDialog(self,master):
"""Initializes the illegalSuits dialog"""
instructions=("Write suits that the user cannot play until a card\n"+
"from that suit has first been discarded. EX: 'clubs, hearts'")
Label(master, text=instructions).grid(row=0)
self.initEntries(1,[(1,0)],master)
def initWinnerDialog(self, master):
"""Initializes the winner dialog"""
instructions=("Designate how someone wins the game. Possible options:"+
" 'leastPoints', 'mostPoints','points>=Bid',\n"+
"'points<=Bid', 'points==Bid', 'mostTricks', "+
"'leastTricks', 'tricks==bid', 'tricks>=bid', \n"+
"'tricks<=bid'. NOTE: You MUST HAVE points/bid for the"+
"corresponding option to work!")
Label(master, text=instructions).grid(row=0)
self.initEntries(1,[(1,0)],master)
def initPassDialog(self, master):
"""Initializes the pass dialog"""
Label(master, text="Number of cards to pass?").grid(row=0)
instructions = "Direction(s)? EX: 'left, right, across, none'"
Label(master, text=instructions).grid(row=2)
self.initEntries(2,[(1,0),(3,0)],master)
def initDealOrderDialog(self,master):
"""Initializes the dealOrder dialog"""
Label(master, text="Number of cards to deal before bid?").grid(row=0)
Label(master, text="Number of cards to deal after bid?").grid(row=2)
self.initEntries(2,[(1,0),(3,0)],master)
def initLoadPresetDialog(self,master):
"""Initializes the loadPreset dialog"""
instructions =("Write the name of your preset file"+
" (one word, no special characters.)")
Label(master, text=instructions).grid(row=0)
self.initEntries(1,[(1,0)],master)
def initSavePresetDialog(self,master):
"""Initializes the loadPreset dialog"""
instructions =("Write a single word, no special characters, for your"+
" preset file name. You will need this to load your"+
" preset file later.")
Label(master, text=instructions).grid(row=0)
self.initEntries(1,[(1,0)],master)
def initNumberOfPlayersPresetDialog(self, master):
"""Initializes the numberOfPlayers dialog"""
instructions = "How many players (min=3, max=5) will be in the game?"
Label(master, text=instructions).grid(row=0)
self.initEntries(1,[(1,0)],master)
def initCardsPerPlayerPresetDialog(self, master):
"""Initializes the cardsPerPlayer dialog"""
instructions = "How many cards should each player recieve?"
Label(master, text=instructions).grid(row=0)
self.initEntries(1,[(1,0)],master)
def initAfterRoundPresetDialog(self, master):
"""Initializes the afterRound dialog"""
instructions = ("By how many cards should the number of cards per"+
" player change per round? Can be positive or negative"+
" numbers. Ex: '-1'")
Label(master, text=instructions).grid(row=0)
self.initEntries(1,[(1,0)],master)
def destroy(self):
"""Destroys the dialog if applicable"""
if (self.dialogType == "trump" and self.entrys[0].get() == ""):
warning="Sorry, you must set a trump, or 'no' for no trump"
tkMessageBox.showwarning("Opps!",warning)
return
elif (self.dialogType == "bid" and not self.canPass and
self.entrys[0].get() == ""):
tkMessageBox.showwarning("Cannot Pass","You cannot pass.")
else:
tkSimpleDialog.Dialog.destroy(self)
def validate(self):
"""Determines whether the entered bid/trump is legal"""
if self.dialogType == "bid": return self.isBidLegal()
elif self.dialogType == "trump": return self.isTrumpLegal()
elif self.dialogType == "bidtrump": self.isBidTrumpLegal()
else: return 1
def isBidLegal(self):
"""Determines whether the entered bid is legal"""
if (self.entrys[0].get().isdigit() and
self.minBid <= int(self.entrys[0].get()) <= self.maxBid):
return 1
else:
errorMessage = "Please enter only a number between %d and %d"
errorMessage = errorMessage % (self.minBid,self.maxBid)
tkMessageBox.showwarning("Invalid Bid", errorMessage)
return 0
def isTrumpLegal(self):
"""Determines whether the entered trump is legal"""
if (self.entrys[0].get()[0].lower() in ["d","c","h","s","n"]): return 1
else:
tkMessageBox.showwarning("Invalid Trump",
"Please enter only a valid suit or no trump")
return 0
def isBidTrumpLegal(self):
"""Determines whether the entered bid and trump is legal"""
if (self.entrys[0].get().isdigit()):
if (self.entrys[1].get()[0].lower() in ["d","c","h","s","n"]):
return 1
else:
tkMessageBox.showwarning("Invalid Trump",
"Please enter only a valid suit or no trump")
return 0
else:
tkMessageBox.showwarning("Invalid Bid",
"Please enter only a number")
return 0
def apply(self):
"""Sets the Dialog's reuslt attribute, so the text can be
read/interpreted by the game"""
result = []
for entry in self.entrys:
result.append(entry.get())
self.result = result
class Button(object):
"""Custom button class"""
def __init__(self, bbox, callback, text="Button", color="white",
font="Arial 20 bold"):
"""Initializes the button"""
self.bbox = bbox
self.callback = callback
self.text = text
self.color = color
self.font = font
(self.width,self.height) = (bbox[2]-bbox[0],bbox[3]-bbox[1])
self.highlighted = False
def isClickInsideBox(self,x,y):
"""Determines whether the user clicked the button"""
bbox = self.bbox
if (bbox[0]<x<bbox[2] and bbox[1]<y<bbox[3]):
self.highlighted = True
return True
else: return False
def clicked(self):
"""Calls the button's callback function"""
self.callback()
def draw(self, canvas):
"""Draws the button"""
(x0,y0,x2,y2) = self.bbox
(x1,y1,x3,y3) = (x2,y0,x0,y2)
(cx,cy) = ((x0+x2)/2,(y0+y2)/2)
cornerRad = self.width/5
# Bbox which includes rounded corners
bbox = (x0,y0,x0+cornerRad,y0,x1-cornerRad,y1,x1,y1,x1,y1+cornerRad,
x1,y2-cornerRad,x2,y2,x2-cornerRad,y2,x3+cornerRad,y2,x3,y3,
x3,y3-cornerRad,x3,y0+cornerRad)
color = self.color if self.highlighted == False else "white"
canvas.create_polygon(*bbox, fill=color, smooth=True, outline="black")
canvas.create_text(cx,cy,text=self.text,font=self.font)
class DragAndDrop(Button):
"""Let's the user drag and drop a button, and perform an action upon drop"""
def draw(self, canvas,cx="",cy=""):
"""Draws the dragAndDrop"""
canvas.delete(self.text.replace(" ",""))
if not cx==cy=="":
(x0,y0,x2,y2) = (cx-self.width/2,cy-self.height/2,
cx+self.width/2,cy+self.height/2)
else: (x0,y0,x2,y2) = self.bbox
(x1,y1,x3,y3) = (x2,y0,x0,y2)
(cx,cy) = ((x0+x2)/2,(y0+y2)/2)
cornerRad = self.width/5
# Bbox which includes rounded corners
bbox = (x0,y0,x0+cornerRad,y0,x1-cornerRad,y1,x1,y1,x1,y1+cornerRad,
x1,y2-cornerRad,x2,y2,x2-cornerRad,y2,x3+cornerRad,y2,x3,y3,
x3,y3-cornerRad,x3,y0+cornerRad)
canvas.create_polygon(*bbox, fill=self.color, smooth=True,
outline="black",tag=self.text.replace(" ",""))
canvas.create_text(cx,cy,text=self.text,font="Arial 20 bold",
tag=self.text.replace(" ",""))
self.bbox = (x0,y0,x2,y2)
class Card(object):
"""A single card with a suit and value"""
cardCount = 0
def __init__(self, suit, value, valueOrder=""):
"""Initializes the card"""
self.suit = suit
self.value = value
self.aboutToPass = False
self.points = 0
(self.maxWidth, self.maxHeight) = (100,140)
# self.rotation = 0
if valueOrder == "":
self.valueOrder = {2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",
9:"9",10:"10",11:"J",12:"Q",13:"K",14:"A"}
else: self.valueOrder = valueOrder
self.valueConversion = {2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",
9:"9",10:"10",11:"J",12:"Q",13:"K",14:"A"}
self.bbox = None
self.playerWhoOwnsTheCard = None
self.ID = Card.cardCount
Card.cardCount += 1
def drawCard(self, canvas, imageDict,highlighted=False):
"""Draws the card"""
tag=str(self) + str(self.ID)
canvas.delete(tag)
(x0,y0,x1,y1,x2,y2,x3,y3) = self.bbox
(cx,cy) = ((x0+x2)/2, (y0+y2)/2)
cornerRad = self.width/5
# Bbox which includes rounded corners
bbox = (x0,y0,x0+cornerRad,y0,x1-cornerRad,y1,x1,y1,x1,y1+cornerRad,
x1,y2-cornerRad,x2,y2,x2-cornerRad,y2,x3+cornerRad,y2,x3,y3,
x3,y3-cornerRad,x3,y0+cornerRad)
if highlighted:
canvas.create_polygon(*bbox, fill="white", outline="black",
smooth=True,width=10,tag=tag)
else: canvas.create_polygon(*bbox, fill="white", outline="black",
smooth=True,tag=tag)
value = self.valueConversion[self.value]
suitImage = imageDict[self.suit]
fontSize = self.width*40/125
font = "Arial %d" %fontSize
canvas.create_text(x0+(cx-x0)/3,y0+(cy-y0)/3,text=value,anchor=CENTER,
font=font,tag=tag)
canvas.create_text(x2-(x2-cx)/3,y2-(y2-cy)/3,text=value,anchor=CENTER,
font=font,tag=tag)
canvas.create_image(cx, cy, image=suitImage, anchor=CENTER,tag=tag)
def move(self, dx, dy):
"""Moves the card"""
bbox = self.bbox
bbox = (bbox[0]+dx, bbox[1]+dy, bbox[2]+dx, bbox[3]+dy,
bbox[4]+dx, bbox[5]+dy, bbox[6]+dx, bbox[7]+dy)
self.bbox = bbox
@staticmethod
def heightFromWidth(width):
"""Returns the card's height, given a width"""
return int(3.5*width/2.5)
@staticmethod
def widthFromHeight(height):
"""Returns the card's width, given a height"""
return int(2.5*height/3.5)
def isXYInsideCard(self, x, y):
"""Determines whether the mouse is on top of or clicked a card"""
# if self.bbox == None: return False
(x0,y0,x1,y1,x2,y2,x3,y3) = self.bbox
if (x0<x<x2 and y0<y<y2):
return True
return False
def __str__(self):
"""Converts Card to string"""
return "(%d,%d)" % (self.suit, self.value)
def __repr__(self):
"""Converts Card to repr, used for debugging"""
return "(%d, %d)" % (self.suit, self.value)
def setDimensions(self, x0, y0, width):
"""Sets dimensions of the card"""
self.width = width
self.height = height = int(3.5*width/2.5)
self.bbox = (x0,y0,x0+width,y0,x0+width,y0+height,x0,y0+height)
def adjustPosition(self,x0,y0):
"""Moves the card up if the user wants to pass it"""
(width,height) = (self.width,self.height)
if self.aboutToPass == False:
self.bbox = (x0,y0,x0+width,y0,x0+width,y0+height,x0,y0+height)
else:
dy = -20
self.bbox = (x0,y0+dy,x0+width,y0+dy,x0+width,
y0+height+dy,x0,y0+height+dy)
def resetCard(self):
"""Returns the card to the deck"""
self.bbox = self.playerWhoOwnsTheCard = None
self.points = 0
def __gt__(self, other):
"""Determines which card is greater, used to sort hand"""
selfVal = self.valueOrder[self.valueConversion[self.value]]
otherVal = self.valueOrder[self.valueConversion[other.value]]
if (self.suit > other.suit):
return True
if (self.suit == other.suit and selfVal > otherVal):
return True
return False
def __eq__(self,other):
if (type(other) == Card):
if (self.suit == other.suit and self.value == other.value):
return True
elif (type(other) == tuple):
if (self.suit == other[0] and self.value == other[1]):
return True
return False
def __ge__(self,other):
"""Determines which card is greater, used to sort hand"""
return self > other or self == other
def __lt__(self,other):
"""Determines which card is lesser, used to sort hand"""
return not self >= other
def __le__(Self,other):
"""Determines which card is lesser, used to sort hand"""
return not self > other
class Player(object):
"""Player, contains all the information about a specific player's cards,
tricks, points, etc."""
def __init__(self, name, playerNum):
"""Initializes the player"""
self.hand = []
self.tricks = []
self.name = name
self.playerNum = playerNum
self.passCardIndices = []
self.recievedCards = []
self.bid = False
self.partnerPoints = 0
def resetPlayer(self):
"""Resets player's attributes between rounds"""
self.hand = []
self.tricks = []
self.passCardIndices = []
self.recievedCards = []
self.bid = False
self.partnerPoints = 0
def getsDealtCard(self, card):
"""Player recieves a card"""
card.playerWhoOwnsTheCard = self.playerNum
self.hand.append(card)
self.sortHand()
def __str__(self):
"""Converts player to string"""
text = (self.name + " | Hand: " + str(self.hand) + "\n" + "Tricks: " +
str(self.tricks))
return text
def playsCardAtIndex(self, index):
"""Player plays a card"""
return self.hand.pop(index)
def sortHand(self):
"""Sorts the player's hand"""
self.hand.sort()
def numberOfCards(self):
"""Returns number of cards the player has"""
return len(self.hand)
def pointsInHand(self):
"""Returns the total points in a player's hand"""
totalPoints = 0
for card in self.hand:
totalPoints += card.points
return totalPoints
def pointsInTricks(self):
"""Returns the total points in a player's tricks"""
totalPoints = 0
for trick in self.tricks:
for card in trick:
totalPoints += card.points
return totalPoints
def points(self):
"""Determines the number of points a player and his/her partner have"""
return self.pointsInTricks() + self.partnerPoints
def suitsInHand(self):
"""Returns the suits the player has in hand"""
suits = set()
for card in self.hand:
suits.add(card.suit)
return suits
def bids(self, bid):
"""Sets the player's bid"""
self.bid = bid
def passCards(self):
"""Sets the cards the player will pass"""
cards = []
self.passCardIndices.sort()
for index in xrange(len(self.passCardIndices)):
card = self.hand.pop(self.passCardIndices[index]-index)
card.aboutToPass = False
cards.append(card)
self.passCardIndices = []
return cards
def recievesCards(self, cards):
"""The player recieves cards that another player passed"""
for card in cards:
card.playerWhoOwnsTheCard = self.playerNum
self.recievedCards.append(card)
def addCardsToHand(self):
"""The player adds the recieve cards to his/her hand"""
for card in self.recievedCards:
self.hand.append(card)
self.sortHand()
class Menu(EventBasedAnimationClass):
"""The initial menu the user sees, allows a user to view help or create a
game."""
def __init__(self):
"""Initializes the menu class"""
self.width = 1000
self.height = 700
self.buttons = {}
self.cards = []
self.helpCards = []
self.subview = None
self.name = "Card Game Creator"
self.isShowingHelp = False
super(Menu, self).__init__(self.width, self.height)
def initAnimation(self):
"""Binds events and sets the suit images"""
self.root.bind("<Button>", lambda event: self.onMousePressed(event))
self.root.bind("<ButtonRelease-1>",
lambda event: self.onMouseReleased(event))
self.canvas.bind("<Motion>", lambda event: self.mouseMotion(event))
self.imageDict = {0:PhotoImage(file='diamonds.gif').subsample(3,3),
1:PhotoImage(file='clubs.gif').subsample(3,3),
2:PhotoImage(file='hearts.gif').subsample(3,3),
3:PhotoImage(file='spades.gif').subsample(3,3)}
self.redrawAll()
def redrawAll(self):
"""Redraws the canvas, background, and buttons"""
self.canvas.delete(ALL)
if self.isShowingHelp:
self.drawHelp()
self.drawHelpCards()
else:
self.drawTitle()
self.drawCards()
self.drawButtons()
def drawHelp(self):
"""Draws the help menu"""
helpText = ""
with open('helpText.txt','rt') as doc: helpText = doc.read()
helpText = self.splitText(helpText, 60)
(cx,cy) = (self.width/2,self.height/2)
self.canvas.create_text(cx,cy,text=helpText,font="Arial 20 bold")
self.buttons = {}
(cx,cy) = (self.width/2,self.height-50)
(width,height) = (300,75)
self.buttons["back"] = Button((cx-width/2,cy-height/2,cx+width/2,
cy+height/2),lambda:self.back(),"Back",
"green","Arial 40 bold")
self.buttons["back"].draw(self.canvas)
cy = 75
self.canvas.create_text(self.width/2,cy,text="Help",
font="Arial 60 bold")
def splitText(self, text, charPerLine):
"""Splits the help text into lines of a given length"""
for charI in xrange(1,len(text)/charPerLine):
charI = charI*charPerLine + charI - 1
if "\n" in text[text.find("\n", charI-charPerLine)+1:charI]:
continue
splitI = text.find(" ", charI)
print charI, splitI
text = text[:splitI+1] + "\n" + text[splitI+1:]
print repr(text)
return text
def back(self):
"""Returns from help screen to menu"""
self.buttons.pop("back")
self.isShowingHelp = False
def drawHelpCards(self):
"""Draw the cards on the sides of the help screen"""
if len(self.helpCards) == 0:
height = 175
width = Card.widthFromHeight(height)
(x0,y0,x1,y1) = (0,0,width,self.height)
self.createHelpCards(x0,y0,x1,y1)
(x0,y0,x1,y1) = (self.width-width,0,self.width,self.height)
self.createHelpCards(x0,y0,x1,y1)
for card in self.helpCards:
card.drawCard(self.canvas,self.imageDict)
def createHelpCards(self,x0,y0,x1,y1):
"""Creates and positions the cards displayed on the help screen"""
width = x1-x0
height = Card.heightFromWidth(width)
numOfCards = (y1-y0)/height
print numOfCards
valueOrder = {2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",
9:"9",10:"10",11:"J",12:"Q",13:"K",14:"A"}
for card in xrange(numOfCards):
(suit,value) = (random.randint(0,3),random.randint(2,14))
self.helpCards.append(Card(suit,value,valueOrder))
self.helpCards[-1].setDimensions(x0,y0+card*height,width)
def drawTitle(self):
"""Draws the title of the game"""
cy = 50
self.canvas.create_text(self.width/2,cy,text=self.name,
font="Arial 60 bold")
def drawCards(self):
"""Draws the card in the background of the menu"""
if len(self.cards) == 0:
height = 200
width = Card.widthFromHeight(height)
(x0,y0,x1,y1) = (0,100,self.width,300)
self.createCards(x0,y0,x1,y1)
(x0,y0,x1,y1) = (0,300,width*2,500)
self.createCards(x0,y0,x1,y1)
(x0,y0,x1,y1) = (self.width-width*2,300,self.width,500)
self.createCards(x0,y0,x1,y1)
(x0,y0,x1,y1) = (0,500,self.width,700)
self.createCards(x0,y0,x1,y1)
for card in self.cards:
card.drawCard(self.canvas,self.imageDict)
def createCards(self,x0,y0,x1,y1):
"""Creates and positions the cards in the background of the menu"""
height = y1-y0
width = Card.widthFromHeight(height)
numOfCards = (x1-x0)/width
valueOrder = {2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",
9:"9",10:"10",11:"J",12:"Q",13:"K",14:"A"}
for card in xrange(numOfCards):
(suit,value) = (random.randint(0,3),random.randint(2,14))
self.cards.append(Card(suit,value,valueOrder))
self.cards[-1].setDimensions(x0+card*width,y0,width)
def drawButtons(self):
"""Creates and draws the two menu buttons"""
if ("createGame" not in self.buttons):
(cx,cy) = (self.width/2-50,350)
(width,height) = (300,75)
self.buttons["createGame"] = Button((cx-width/2,cy-height/2,
cx+width/2,cy+height/2),
lambda:self.createGame(),
"Create Game","green",
"Arial 40 bold")
if ("help" not in self.buttons):
(cx,cy) = (self.width/2+50,450)
(width,height) = (300,75)
self.buttons["help"] = Button((cx-width/2,cy-height/2,cx+width/2,
cy+height/2),lambda:self.help(),
"Help","green","Arial 40 bold")
for key in self.buttons:
button = self.buttons[key]
button.draw(self.canvas)
def onMousePressed(self, event):
"""Checks if user clicked a button"""
print "mousepressed"
(x,y) = (event.x, event.y)
try:
for key in self.buttons:
button = self.buttons[key]
if (button.isClickInsideBox(x,y)): button.clicked()
except Exception,e: print str(e)
def onMouseReleased(self, event):
"""Un-highlights the buttons"""
for key in self.buttons:
button = self.buttons[key]
button.highlighted = False
self.redrawAll()
def mouseMotion(self, event):
"""Overrides the mouse motion binding in any subviews"""
pass
def createGame(self):
"""Moves to the next menu when a user clicks the createGame button"""
self.canvas.delete(ALL)
self.timerDelay = None
thread = Thread(target = lambda: self.checkIfSubviewIsDone())
thread.start()
self.subview = DefineRulesMenu(self.canvas,self.root)
def help(self):
"""Processes button click when a user clicks help"""
self.isShowingHelp = True
self.redrawAll()
def checkIfSubviewIsDone(self):
"""Continually checks if the subview (the DefineRulesMenu) is done, and
if so, removes them and re-draws the menu"""
try:
if (self.subview.done):
print "yayyyy!!!"
self.subview = None
self.timerDelay = 250
for key in self.buttons:
button = self.buttons[key]
button.highlighted = False
self.initAnimation()
else:
thread = Thread(target = lambda: self.checkIfSubviewIsDone())
thread.start()
except Exception,e:
#print str(e)
thread = Thread(target = lambda: self.checkIfSubviewIsDone())
thread.start()
class DefineRulesMenu(object):
"""The next-level menu, where a user is able to drag and drop rules together
to create his/her own game"""
def __init__(self, canvas, root):
"""Initializes the menu, including the area for the users to drop rules
to."""
self.width = canvas.winfo_width()
self.height = canvas.winfo_height()
self.canvas = canvas
self.root = root
self.dragAndDrops = {}
self.buttons = {}
self.subview = None
self.done = False
self.currentlyDragging = ""
self.rules = {}
(vOffset, hOffset, width) = (100,50,700)
self.rulesBbox = (self.width-width-hOffset,vOffset,self.width-hOffset,
vOffset,self.width-hOffset,self.height-vOffset,
self.width-width-hOffset,self.height-vOffset)
(vOffset, width) = (100,200)
self.optionsBbox = (0,vOffset,width,vOffset,width,self.height-vOffset,
0,self.height-vOffset)
self.initAnimation()
def initAnimation(self):
"""Binds all events"""
self.root.bind("<Button>", lambda event: self.onMousePressed(event))
self.root.bind("<ButtonRelease-1>",
lambda event: self.onMouseReleased(event))
self.canvas.bind("<Motion>", lambda event: self.mouseMotion(event))
self.redrawAll()
def onMousePressed(self, event):
"""Checks if user clicked a button or a dragAndDrop"""
(x,y) = (event.x, event.y)
try:
for key in self.dragAndDrops:
dragAndDrop = self.dragAndDrops[key]
if (dragAndDrop.isClickInsideBox(x,y)):
self.currentlyDragging = key
for key in self.buttons:
button = self.buttons[key]
if (button.isClickInsideBox(x,y)):
button.clicked()
except Exception,e: print str(e)
def onMouseReleased(self, event):
"""Checks if the user released a dragAndDrop"""
(x,y) = (event.x,event.y)
if self.currentlyDragging != "":
if (self.rulesBbox[0]<x<self.rulesBbox[4] and
self.rulesBbox[1]<y<self.rulesBbox[5]):
self.dragAndDrops[self.currentlyDragging].clicked()
else:
self.dragAndDrops.pop(self.currentlyDragging)
if self.currentlyDragging in self.rules:
self.rules.pop(self.currentlyDragging)
self.redrawAll()
self.currentlyDragging = ""
for key in self.buttons:
button = self.buttons[key]
button.highlighted = False
self.redrawAll()
def mouseMotion(self, event):
"""If the user is dragging a dragAndDrop, this moves it"""
(x,y) = (event.x, event.y)
if (self.currentlyDragging != ""):
dragAndDrop = self.dragAndDrops[self.currentlyDragging]
dragAndDrop.draw(self.canvas,x,y)
def redrawAll(self):
"""Redraws all buttons, boxes, and dragAndDrops"""
self.drawBackgroundInfo()
self.drawDragAndDrops()
self.drawButtons()
def drawBackgroundInfo(self):
"""Draws the background boxes and text."""
canvas = self.canvas
(x0,y0,x1,y1,x2,y2,x3,y3) = self.rulesBbox
(cx,cy,cornerRad) = ((x2+x0)/2,y0+20,50)
bbox = (x0,y0,x0+cornerRad,y0,x1-cornerRad,y1,x1,y1,x1,y1+cornerRad,
x1,y2-cornerRad,x2,y2,x2-cornerRad,y2,x3+cornerRad,y2,x3,y3,
x3,y3-cornerRad,x3,y0+cornerRad)
canvas.create_polygon(*bbox, fill="green", smooth=True, outline="black")
canvas.create_text(cx,cy,text="Rules",font="Arial 20 bold")
(x0,y0,x1,y1,x2,y2,x3,y3) = self.optionsBbox
(cx,cy,cornerRad) = ((x2+x0)/2,y0+20,50)
bbox = (x0,y0,x0+cornerRad,y0,x1-cornerRad,y1,x1,y1,x1,y1+cornerRad,
x1,y2-cornerRad,x2,y2,x2-cornerRad,y2,x3+cornerRad,y2,x3,y3,
x3,y3-cornerRad,x3,y0+cornerRad)
canvas.create_polygon(*bbox, fill="grey", smooth=True, outline="black")
canvas.create_text(cx,cy,text="Options",font="Arial 20 bold")
canvas.create_text(483,45,text="Presets:",
font="Arial 20 bold")
(cx,cy) = ((self.optionsBbox[4]+self.rulesBbox[0])/2, self.height-50)
canvas.create_text(cx,cy,text="Drag and Drop", font="Arial 40 bold")
def drawButtons(self):
"""Creates and draws all the buttons in this menu"""
(width,height) = (100,50)
offset = 20
if ("clear" not in self.buttons):
voffset,hoffset = 20,500
self.buttons["createGame"] = Button((hoffset,
self.height-height-voffset,width+hoffset,
self.height-voffset),lambda:self.clear(),"Clear",
"green")
if ("heartsPreset" not in self.buttons):
self.buttons["heartsPreset"] = Button((self.width-width-offset,
offset,self.width-offset,height+offset),
lambda:self.readInPreset('heartsPreset.txt'),
"Hearts","green")
if ("twentyNinePreset" not in self.buttons):
voffset,hoffset = 20, 140
self.buttons["twentyNinePreset"] = Button((self.width-width-hoffset,
voffset,self.width-hoffset,height+voffset),
lambda:self.readInPreset('twentyNinePreset.txt'),
"29","green")
if ("loadPreset" not in self.buttons):
voffset,hoffset = 20, 260
self.buttons["loadPreset"] = Button((self.width-width-hoffset,
voffset,self.width-hoffset,height+voffset),
lambda:self.loadPreset(),"Load","green")
if ("savePreset" not in self.buttons):
voffset,hoffset = 20, 380
self.buttons["savePreset"] = Button((self.width-width-hoffset,
voffset,self.width-hoffset,height+voffset),
lambda:self.savePreset(),"Save","green")
(width,height) = (200,50)
if ("back" not in self.buttons):
self.buttons["back"] = Button((offset,offset,width+offset,
height+offset),lambda:self.back(),"Back","green")
if ("playerNames" not in self.buttons):
voffset,hoffset = 20, 240
self.buttons["playerNames"] = Button((hoffset,voffset,width+hoffset,
height+voffset),lambda:self.playerNames(),
"Player Names","green")
if ("startGame" not in self.buttons):
self.buttons["startGame"] = Button((self.width-width-offset,
self.height-height-offset,self.width-offset,
self.height-offset),lambda:self.startGame(),
"Start Game","green")
for key in self.buttons:
button = self.buttons[key]
button.draw(self.canvas)
def drawDragAndDrops(self):
"""Creates and draws all the dragAndDrops on this menu"""
(width,height) = (150,30)
self.names = ["Anna","Katie","William","Amal","Varun"]
if ("omitCards" not in self.dragAndDrops):
(cx,cy) = (self.width/2,self.height/2)
(vOffset,hOffset) = (150+height*0,25)
self.omitCardsText = [""]
if "omitCards" in self.rules: self.rules.pop("omitCards")
self.dragAndDrops["omitCards"] = DragAndDrop((hOffset,vOffset,
hOffset+width,vOffset+height),
lambda:self.omitCards(),"Omit Cards","grey")
if ("points" not in self.dragAndDrops):
(cx,cy) = (self.width/2,self.height/2)
(vOffset,hOffset) = (150+height*1,25)
self.pointsText = [""]
if "points" in self.rules: self.rules.pop("points")
self.dragAndDrops["points"] = DragAndDrop((hOffset,vOffset,
hOffset+width,vOffset+height),
lambda:self.points(),"Points","grey")
if ("passCards" not in self.dragAndDrops):
(cx,cy) = (self.width/2,self.height/2)
(vOffset,hOffset) = (150+height*2,25)
self.passCardsText = ["",""]
if "passCards" in self.rules: self.rules.pop("passCards")
self.dragAndDrops["passCards"] = DragAndDrop((hOffset,vOffset,
hOffset+width,vOffset+height),
lambda:self.passCards(),"Pass","grey")
if ("playerWhoStarts" not in self.dragAndDrops):
(cx,cy) = (self.width/2,self.height/2)
(vOffset,hOffset) = (150+height*3,25)
self.playerWhoStartsText = [""]
if "playerWhoStarts" in self.rules: self.rules.pop("playerWhoStarts")
self.dragAndDrops["playerWhoStarts"] = DragAndDrop((hOffset,vOffset,
hOffset+width,vOffset+height),
lambda:self.playerWhoStarts(),
"Starting Player","grey")
if ("suitsLegalityDict" not in self.dragAndDrops):
(cx,cy) = (self.width/2,self.height/2)
(vOffset,hOffset) = (150+height*4,25)
self.suitsLegalityDictText = [""]
if "suitsLegalityDict" in self.rules:
self.rules.pop("suitsLegalityDict")
self.dragAndDrops["suitsLegalityDict"] = DragAndDrop((hOffset,
vOffset,hOffset+width,vOffset+height),
lambda:self.suitsLegalityDict(),
"Illegal Suits","grey")
if ("winner" not in self.dragAndDrops):
(cx,cy) = (self.width/2,self.height/2)
(vOffset,hOffset) = (150+height*5,25)
self.winnerText = [""]
if "winner" in self.rules: self.rules.pop("winner")
self.dragAndDrops["winner"] = DragAndDrop((hOffset,vOffset,
hOffset+width,vOffset+height),
lambda:self.winner(),"Winner","grey")
if ("trump" not in self.dragAndDrops):
(cx,cy) = (self.width/2,self.height/2)
(vOffset,hOffset) = (150+height*6,25)
self.trumpText = [""]
if "trump" in self.rules: self.rules.pop("trump")
self.dragAndDrops["trump"] = DragAndDrop((hOffset,vOffset,
hOffset+width,vOffset+height),
lambda:self.trump(),"Trump","grey")
if ("bid" not in self.dragAndDrops):