-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyatzy.py
285 lines (209 loc) · 7.5 KB
/
yatzy.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
import random
from collections import Counter
from copy import deepcopy
from dataclasses import dataclass, field
from enum import Enum, auto
from statistics import mode
from typing import Callable
DICE_SIDES = 6
DICES = 5
MAX_THROWS = 3
YATZY_SCORE = 50
class ScoreBox(Enum):
ONES = auto()
TWOS = auto()
THREES = auto()
FOURS = auto()
FIVES = auto()
SIXES = auto()
PAIR = auto()
TWO_PAIR = auto()
THREE_OF_A_KIND = auto()
FOUR_OF_A_KIND = auto()
SMALL_STRAIGHT = auto()
LARGE_STRAIGHT = auto()
FULL_HOUSE = auto()
CHANCE = auto()
YATZY = auto()
def throw_dices(dices: list[int], held_dices: list[int] | None = None) -> list[int]:
# Only throw the dices that were not held
for i, _ in enumerate(dices):
if not held_dices or i not in held_dices:
dices[i] = random.randint(1, DICE_SIDES)
return dices
def number_sum(dices: list[int], number: int) -> int:
return dices.count(number) * number
def ones(dices: list[int]) -> int:
return number_sum(dices, 1)
def twos(dices: list[int]) -> int:
return number_sum(dices, 2)
def threes(dices: list[int]) -> int:
return number_sum(dices, 3)
def fours(dices: list[int]) -> int:
return number_sum(dices, 4)
def fives(dices: list[int]) -> int:
return number_sum(dices, 5)
def sixes(dices: list[int]) -> int:
return number_sum(dices, 6)
def pair(dices: list[int]) -> int:
counts = Counter(dices)
pairs = [value * 2 for value, count in counts.items() if count >= 2]
return max(pairs) if pairs else 0
def two_pair(dices: list[int]) -> int:
counts = Counter(dices)
pairs = [value * 2 for value, count in counts.items() if count >= 2]
return sum(pairs) if len(pairs) >= 2 else 0
def n_of_a_kind(dices: list[int], n: int) -> int:
most_common = mode(dices)
count = dices.count(most_common)
return most_common * n if count >= n else 0
def three_of_a_kind(dices: list[int]) -> int:
return n_of_a_kind(dices, 3)
def four_of_a_kind(dices: list[int]) -> int:
return n_of_a_kind(dices, 4)
def small_straight(dices: list[int]) -> int:
return 15 if sorted(dices) == [1, 2, 3, 4, 5] else 0
def large_straight(dices: list[int]) -> int:
return 20 if sorted(dices) == [2, 3, 4, 5, 6] else 0
def full_house(dices: list[int]) -> int:
if len(set(dices)) == 2 and dices.count(dices[0]) in {2, 3}:
return sum(dices)
return 0
def chance(dices: list[int]) -> int:
return sum(dices)
def yatzy(dices: list[int]) -> int:
return YATZY_SCORE if len(set(dices)) == 1 else 0
SCORE_BOX_FUNCTION_MAP: dict[ScoreBox, Callable] = {
ScoreBox.ONES: ones,
ScoreBox.TWOS: twos,
ScoreBox.THREES: threes,
ScoreBox.FOURS: fours,
ScoreBox.FIVES: fives,
ScoreBox.SIXES: sixes,
ScoreBox.PAIR: pair,
ScoreBox.TWO_PAIR: two_pair,
ScoreBox.THREE_OF_A_KIND: three_of_a_kind,
ScoreBox.FOUR_OF_A_KIND: four_of_a_kind,
ScoreBox.SMALL_STRAIGHT: small_straight,
ScoreBox.LARGE_STRAIGHT: large_straight,
ScoreBox.FULL_HOUSE: full_house,
ScoreBox.CHANCE: chance,
ScoreBox.YATZY: yatzy,
}
SCORE_BOXES: dict[int, Callable] = {
score_box.value: SCORE_BOX_FUNCTION_MAP[score_box] for score_box in ScoreBox
}
def readable_score_box(score_box: ScoreBox) -> str:
return " ".join(word.capitalize() for word in score_box.name.split("_"))
@dataclass(slots=True)
class Player:
name: str
score: int = 0
upper_score: int = 0
available_score_boxes: dict[int, Callable] = field(
default_factory=lambda: deepcopy(SCORE_BOXES)
)
def print_available_score_boxes(self):
for index in self.available_score_boxes.keys():
score_box_name = readable_score_box(ScoreBox(index))
print(f"{index}: {score_box_name}")
def choose_held_dices(dices: list[int]) -> list[int]:
held_dices = []
valid_input: bool = False
while not valid_input:
print(f"\nDices: {dices}")
valid_input = True # Changes to False if wrong input is inserted
kept_dices: str = input("Dices to keep: ")
for character in kept_dices:
try:
dice_index = int(character) - 1
if dice_index > DICES:
valid_input = False
break
held_dices.append(dice_index)
except ValueError:
valid_input = False
break
if not valid_input:
print("Invalid input")
print(
"Insert numbers for dices. F.ex. '1235' will throw again dices 1, 2, 3, and 5"
)
return held_dices
def output_player_score(player: Player) -> None:
print(
f"{player.name} has {player.score} points in total (upper total: {player.upper_score})"
)
def update_player_score(player: Player, dices: list[int]) -> None:
while True:
try:
chosen_score_box = int(input("Choose: "))
score_box_function = player.available_score_boxes.pop(chosen_score_box)
break
except (ValueError, KeyError):
print("Invalid selection, try again")
# Calculate points for the score box
score: int = score_box_function(dices)
player.score += score
if 1 <= chosen_score_box <= 6:
player.upper_score += score
# Output score information
score_box_name = readable_score_box(ScoreBox(chosen_score_box))
print(f"\n{player.name} added {score} points to {score_box_name.lower()}")
output_player_score(player)
def take_turn(player: Player):
print(f"\n{player.name}'s turn")
dices = [1] * 5
held_dices: list[int] | None = None
for throw in range(0, MAX_THROWS):
dices = throw_dices(dices, held_dices)
if throw + 1 >= MAX_THROWS:
break
# What dices to keep?
held_dices = choose_held_dices(dices)
if len(held_dices) >= DICES:
break
# Choose what score box to put points to
print(f"\nDices: {dices}")
print("Available score boxes:")
player.print_available_score_boxes()
update_player_score(player, dices)
def define_winner(players: list[Player]) -> Player:
assert len(players) > 0, "Defining winner requires at least one player"
return max(players, key=lambda player: player.score)
def output_scoreboard(players: list[Player]) -> None:
print("\nSCOREBOARD:")
for player in players:
output_player_score(player)
def add_players() -> list[Player]:
players: list[Player] = []
while True:
player_name: str = input("Player name: ")
players.append(Player(player_name))
print(f"{player_name} added to the game")
if not player_wants_to_add_another_player():
break
players.append(Player("Iina"))
return players
def player_wants_to_add_another_player() -> bool:
while True:
answer: str = input("Add another player? (Y/N) ")
if answer.upper() == "N":
return False
if answer.upper() == "Y":
return True
print(f"Invalid option '{answer}'")
def main():
players: list[Player] = add_players()
while True:
# Players take turns unti the game is over
for player in players:
if not player.available_score_boxes:
# Output the scores and who won the game
output_scoreboard(players)
winner = define_winner(players)
print(f"{winner.name} won with {winner.score} points!")
return
take_turn(player)
if __name__ == "__main__":
main()