- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrummy.py
More file actions
Latest commit
219 lines (179 loc) · 7.96 KB
/
Copy pathrummy.py
File metadata and controls
219 lines (179 loc) · 7.96 KB
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
importrandom
importitertools
classCard:
SUIT_SYMBOLS= {'Hearts': '♥', 'Diamonds': '♦', 'Clubs': '♣', 'Spades': '♠'}
RANK_ORDER= {'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 11, 'Q': 12, 'K': 13}
def__init__(self, suit, rank):
self.suit=suit
self.rank=rank
self.abbr=self.get_abbreviation()
defget_abbreviation(self):
rank_abbr=self.rank[0] ifself.rank!='10'else'10'
returnf"{rank_abbr}{self.SUIT_SYMBOLS[self.suit]}"
def__str__(self):
returnf"{self.rank} of {self.suit}"
def__lt__(self, other):
ifself.suit!=other.suit:
returnlist(self.SUIT_SYMBOLS.keys()).index(self.suit) <list(self.SUIT_SYMBOLS.keys()).index(other.suit)
returnself.RANK_ORDER[self.rank[0] ifself.rank!='10'else'10'] <self.RANK_ORDER[other.rank[0] ifother.rank!='10'else'10']
classDeck:
def__init__(self):
suits= ['Hearts', 'Diamonds', 'Clubs', 'Spades']
ranks= ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
self.cards= [Card(suit, rank) forsuitinsuitsforrankinranks]
random.shuffle(self.cards)
defdraw(self):
returnself.cards.pop() ifself.cardselseNone
classPlayer:
def__init__(self, name):
self.name=name
self.hand= []
defdraw(self, card):
self.hand.append(card)
self.sort_hand()
defdiscard(self, card):
self.hand.remove(card)
defsort_hand(self):
self.hand.sort()
classRummyGame:
def__init__(self):
self.deck=Deck()
self.players= [Player("Player 1"), Player("Player 2")]
self.discard_pile= []
self.table= []
defdeal_initial_hands(self):
for_inrange(10):
forplayerinself.players:
player.draw(self.deck.draw())
self.discard_pile.append(self.deck.draw())
defis_valid_meld(self, cards):
iflen(cards) <3:
returnFalse
ifall(card.rank==cards[0].rankforcardincards):
returnTrue
ifall(card.suit==cards[0].suitforcardincards):
ranks= ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
card_ranks= [ranks.index(card.rank) forcardincards]
card_ranks.sort()
returnall(card_ranks[i] ==card_ranks[i-1] +1foriinrange(1, len(card_ranks)))
returnFalse
defhandle_melds_and_layoffs(self, player):
whileTrue:
action=self.get_input("Do you want to put down a meld (m), lay off a card (l), or continue (c)? ").lower()
ifaction=='m':
self.put_down_meld(player)
elifaction=='l':
self.lay_off_card(player)
elifaction=='c':
break
else:
print("Invalid input. Please try again.")
defput_down_meld(self, player):
print("Your hand:", " ".join(card.abbrforcardinplayer.hand))
meld_input=self.get_input("Enter the abbreviations of the cards for the meld, separated by spaces: ").split()
meld_cards= [cardforcardinplayer.handifcard.abbrinmeld_input]
ifself.is_valid_meld(meld_cards):
self.table.append(meld_cards)
forcardinmeld_cards:
player.hand.remove(card)
print("Meld successfully put down on the table.")
else:
print("Invalid meld. Please try again.")
deflay_off_card(self, player):
print("Your hand:", " ".join(card.abbrforcardinplayer.hand))
card_input=self.get_input("Enter the abbreviation of the card to lay off: ")
matching_cards= [cardforcardinplayer.handifcard.abbr==card_input]
ifmatching_cards:
card=matching_cards[0]
meld_index=int(self.get_input("Enter the number of the meld to lay off on: ")) -1
if0<=meld_index<len(self.table):
meld=self.table[meld_index]
new_meld=meld+ [card]
ifself.is_valid_meld(new_meld):
self.table[meld_index] =new_meld
player.hand.remove(card)
print(f"Card {card.abbr} successfully laid off.")
else:
print("Invalid lay off. The resulting meld is not valid.")
else:
print("Invalid meld number. Please try again.")
else:
print("Invalid card abbreviation. Please try again.")
defget_input(self, prompt):
user_input=input(prompt)
ifuser_input.lower() =='exit':
print("Game stopped. Thanks for playing!")
exit()
returnuser_input
defplay_turn(self, player):
print(f"\n{player.name}'s turn:")
print("Your hand:", " ".join(card.abbrforcardinplayer.hand))
print("Top of discard pile:", self.discard_pile[-1].abbrifself.discard_pileelse"Empty")
print("Table:")
fori, meldinenumerate(self.table):
print(f"Meld {i+1}: {' '.join(card.abbrforcardinmeld)}")
whileTrue:
draw_from=self.get_input("Draw from deck (d) or discard pile (p): ").lower()
ifdraw_fromin ['d', 'p']:
break
print("Invalid input. Please try again.")
ifdraw_from=='p'andself.discard_pile:
card=self.discard_pile.pop()
print(f"You drew {card.abbr} from the discard pile.")
else:
ifdraw_from=='p'andnotself.discard_pile:
print("Discard pile is empty. Drawing from deck instead.")
card=self.deck.draw()
ifcardisNone:
self.reshuffle_discard_pile()
card=self.deck.draw()
print(f"You drew {card.abbr} from the deck.")
player.draw(card)
self.handle_melds_and_layoffs(player)
print("Your hand:", " ".join(card.abbrforcardinplayer.hand))
whileTrue:
discard_input=self.get_input("Enter the abbreviation of the card to discard: ")
matching_cards= [cardforcardinplayer.handifcard.abbr==discard_input]
ifmatching_cards:
discard=matching_cards[0]
break
print("Invalid input. Please enter a valid card abbreviation from your hand.")
player.discard(discard)
self.discard_pile.append(discard)
print(f"You discarded {discard.abbr}")
defreshuffle_discard_pile(self):
print("Draw pile exhausted. Reshuffling the discard pile.")
top_card=self.discard_pile.pop()
self.deck.cards=self.discard_pile
random.shuffle(self.deck.cards)
self.discard_pile= [top_card]
defcheck_winner(self, player):
temp_hand=player.hand.copy()
whiletemp_hand:
found_meld=False
foriinrange(3, len(temp_hand) +1):
formeldinitertools.combinations(temp_hand, i):
ifself.is_valid_meld(meld):
forcardinmeld:
temp_hand.remove(card)
found_meld=True
break
iffound_meld:
break
ifnotfound_meld:
returnFalse
returnTrue
defplay_game(self):
self.deal_initial_hands()
current_player=0
whileTrue:
player=self.players[current_player]
self.play_turn(player)
ifself.check_winner(player):
print(f"\n{player.name} wins!")
break
current_player= (current_player+1) %len(self.players)
print("Game over. Thanks for playing!")
if__name__=="__main__":
game=RummyGame()
game.play_game()