-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·379 lines (315 loc) · 12.8 KB
/
main.py
File metadata and controls
executable file
·379 lines (315 loc) · 12.8 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
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Zombie Dice - Eat brains. Don't get shotgunned"""
__version__ = "1.0.0-dev"
__status__ = "Development"
__author__ = "Alexandre Calil Martins Fonseca"
__email__ = "alexandre@xandao.dev"
__credits__ = "Steve Jackson Games"
__license__ = "MIT"
import random
from typing import List, Optional
# Constants
MIN_PLAYERS = 2
MAX_PLAYERS = 99
MIN_NAME_LENGTH = 3
MAX_NAME_LENGTH = 13
MAX_SCORE = 13
MAX_SHOOTERS_PER_TURN = 3
INITIAL_AMOUNT_OF_DICES = 13
N_OF_DICES_TO_ROLL = 3
DICES_FACES = {
"green": tuple(["shotgun"] * 1 + ["footprint"] * 2 + ["brain"] * 3),
"yellow": tuple(["shotgun"] * 2 + ["footprint"] * 2 + ["brain"] * 2),
"red": tuple(["shotgun"] * 3 + ["footprint"] * 2 + ["brain"] * 1),
}
COLORS = {
# ANSI Escape Sequences
"GREEN": "\033[92m",
"YELLOW": "\033[93m",
"RED": "\033[91m",
"BLUE": "\033[94m",
"PURPLE": "\033[95m",
"BOLD": "\033[1m",
"UNDERLINE": "\033[4m",
"END": "\033[0m",
}
ACTIONS = {
"roll": {
"description": f"[{COLORS['GREEN']}r{COLORS['END']}] to pick and roll 3 dices",
"key": "r",
},
"finish": {
"description": f"[{COLORS['RED']}f{COLORS['END']}] to finish my turn",
"key": "f",
},
}
class Dice:
def __init__(self, color: str):
self.color = color
self.face = ""
def roll(self):
self.face = random.choice(DICES_FACES[self.color])
def __str__(self):
return self.face
def __repr__(self):
return f"Dice('{self.color}', '{self.face}')"
dices_box = [Dice("green") for _ in range(6)] + [Dice("yellow") for _ in range(4)] + [Dice("red") for _ in range(3)]
class Player:
def __init__(self, name: str):
self.name = name
self.score = 0
self.dices = []
def return_dices(self, dices: Optional[List[Dice]] = None) -> None:
if dices is None:
dices_box.extend(self.dices)
self.dices = []
else:
# Check if dices are from the player
for dice in dices:
if dice not in self.dices:
raise ValueError("Dices are not from the player")
dices_box.extend(dices)
self.dices = [dice for dice in self.dices if dice not in dices]
assert len(dices_box) <= INITIAL_AMOUNT_OF_DICES, "More dices than existing amount!"
def reset_score(self):
self.score = 0
def __str__(self):
return self.name
def __repr__(self):
return f"Player('{self.name}', {self.score})"
def main():
introduce_game()
n_of_players = get_valid_number_of_players()
players_name = get_valid_players_name(n_of_players)
players = [Player(name) for name in players_name]
introduce_players(players_name)
start_game(players)
def introduce_game() -> None:
boldAndUnderline = COLORS["BOLD"] + COLORS["UNDERLINE"]
print(
f"""
{boldAndUnderline}
Welcome to 🧟 {COLORS["GREEN"]}Zombie{COLORS["END"]}{boldAndUnderline} 🎲 Dice!
{COLORS["END"]}
"""
)
def get_valid_number_of_players() -> int:
while True:
try:
try:
n_of_players = int(input(f"How many 🧟 zombies will play ({MIN_PLAYERS}-{MAX_PLAYERS})? "))
except ValueError:
print("You must enter a number of players!")
raise ValueError("Not a valid number of players")
if n_of_players < MIN_PLAYERS:
print(f"You need at least {MIN_PLAYERS} zombies!")
raise ValueError("Too few players")
if n_of_players > MAX_PLAYERS:
print(f"You can play at most {MAX_PLAYERS} zombies!")
raise ValueError("Too many players")
except ValueError:
continue
else:
break
return n_of_players
def get_valid_players_name(n_of_players: int) -> list:
players = []
print(f"Insert each 🧠 brain eater name below. Empty for generic name.")
for index in range(n_of_players):
readable_index = index + 1
name = input(f"Zombie {readable_index}: ").strip()
while True:
if name in players:
print(f"{name} is already in the game! Try another one.")
elif len(name) < MIN_NAME_LENGTH and len(name) != 0:
print(f"Name too short! It must be at least {MIN_NAME_LENGTH} characters long.")
elif len(name) > MAX_NAME_LENGTH:
print(f"Name too long! It must be at most {MAX_NAME_LENGTH} characters long.")
else:
break
name = input(f"Zombie {readable_index}: ").strip()
if name == "":
name = f"Zombie {readable_index}"
players.append(name)
return players
def introduce_players(players_name: List[str]) -> None:
players_string = COLORS["RED"] + ", ".join(players_name[:-1]) + f" and {players_name[-1]}" + COLORS["END"]
print(f"🧟 Grrr!!! Have fun {players_string}")
def start_game(players: List[Player]):
# if someone reaches 13 points, the game ends and show the score
# if a tie happens, this two players will play against each other 1 round
print("Let's start the game!")
while True:
game_round(players)
players_with_max_score = [player for player in players if player.score >= MAX_SCORE]
if len(players_with_max_score) == 1:
players_with_max_score.sort(key=lambda player: player.score, reverse=True)
print(f"\n🧟🏆 {players_with_max_score[0].name} wins the game! 🎉 🎉 🎉\n")
print("Scoreboard:")
for i, player in enumerate(players_with_max_score):
print(f" 🏆 {i + 1}: {player.name} scored {player.score} points")
break
elif len(players_with_max_score) > 1:
print(
"🤔 A tie happened! Running a game between tie-players "
+ COLORS["RED"]
+ ", ".join([str(name) for name in players_with_max_score[:-1]])
+ f" and {players_with_max_score[-1]}"
+ COLORS["END"]
)
for player in players_with_max_score:
player.reset_score()
tiebreaker_round(players_with_max_score)
players_with_max_score.sort(key=lambda player: player.score, reverse=True)
print("Scoreboard:")
for i, player in enumerate(players_with_max_score):
print(f" 🏆 {i + 1}: {player.name} scored {player.score} points")
break
else:
print(f"No one has reached {MAX_SCORE} points yet! Next round!")
def game_round(players: List[Player]):
for player in players:
player_turn(player)
def tiebreaker_round(tied_players: List[Player]):
for player in tied_players:
player_turn(player)
def player_turn(player: Player) -> None:
brains = 0
shotguns = 0
footprints = 0
print("═" * 100)
print(f"{COLORS['BOLD']}It's your turn {player}{COLORS['END']} 🧟")
valid_actions = [ACTIONS["roll"], ACTIONS["finish"]]
while True:
while True:
key = input(f"{player}, {', '.join(action['description'] for action in valid_actions)}: ").strip().lower()
action = get_valid_action(key, valid_actions)
if action != None:
break
if action == ACTIONS["roll"]:
result = roll_action(player)
brains += result["brains"]
shotguns += result["shotguns"]
footprints += result["footprints"]
print(f"ℹ️ {player}, you have {brains} points and {shotguns} shotguns in this round.")
# Any condition that ends the turn, but conservers the player's score
if result["finish"]:
finish_action(player, brains)
break
# Stop if the player got 3 shotguns
if shotguns >= MAX_SHOOTERS_PER_TURN:
print("☠️ Busted, you got too many shotguns. The score of this turn is lost. ☠️")
finish_action(player, 0)
break
# If player reaches the max score, the game ends
if brains + player.score >= MAX_SCORE:
finish_action(player, brains)
break
elif action == ACTIONS["finish"]:
finish_action(player, brains)
break
print("─" * 100)
player.return_dices()
def get_valid_action(key: str, valid_actions: list) -> Optional[dict]:
for action in valid_actions:
if key == action["key"]:
return action
print(f"❌ Invalid action! Available actions: {', '.join(action['description'] for action in valid_actions)}")
return None
def roll_action(player: Player) -> None:
footprints_to_roll_again = []
dices = []
brains = 0
shotguns = 0
footprints = 0
# Compute footprints of the player to roll again
footprint_match = lambda dice: dice.face == "footprint" and len(footprints_to_roll_again) <= N_OF_DICES_TO_ROLL
footprints_to_roll_again = [dice for dice in player.dices if footprint_match(dice)]
player.dices = [dice for dice in player.dices if dice not in footprints_to_roll_again]
# Pick dices to roll again, considering the number of footprints
n_of_dices_to_pick = N_OF_DICES_TO_ROLL - len(footprints_to_roll_again)
try:
dices = pick_dices(n_of_dices_to_pick)
except ValueError:
print("↪️ The cup is empty!")
brains_to_return = []
brains_to_return = [dice for dice in player.dices if dice.face == "brain"]
if len(brains_to_return) > 0:
print(f"🤤 Returning your brains to the cup, you will not lose any points.")
player.return_dices(brains_to_return)
dices = pick_dices(n_of_dices_to_pick)
else:
print(f"⏭️ Out of dices in the box, turn is over. Your score will be saved.")
return {"finish": True, "brains": 0, "shotguns": 0, "footprints": 0}
# Show picked dices
print(f"🤌 🎲 Picked {len(dices)} dices: ", end="")
for dice in dices:
if dice.color == "red":
print(f"{COLORS['RED']}{dice.color} dice{COLORS['END']}; ", end="")
elif dice.color == "yellow":
print(f"{COLORS['YELLOW']}{dice.color} dice{COLORS['END']}; ", end="")
elif dice.color == "green":
print(f"{COLORS['GREEN']}{dice.color} dice{COLORS['END']}; ", end="")
print("")
# Show footprints to roll again
if len(footprints_to_roll_again) > 0:
print(f"👣 You have {len(footprints_to_roll_again)} footprints to roll again: ", end="")
for dice in footprints_to_roll_again:
if dice.color == "red":
print(f"{COLORS['RED']}{dice.color} dice{COLORS['END']}; ", end="")
elif dice.color == "yellow":
print(f"{COLORS['YELLOW']}{dice.color} dice{COLORS['END']}; ", end="")
elif dice.color == "green":
print(f"{COLORS['GREEN']}{dice.color} dice{COLORS['END']}; ", end="")
print("")
# Extend the picked dices to the dices that will be rolled again
dices.extend(footprints_to_roll_again)
# Roll the dices and compute the points
for dice in dices:
dice.roll()
if dice.face == "brain":
brains += 1
elif dice.face == "shotgun":
shotguns += 1
elif dice.face == "footprint":
footprints += 1
# Show the rolled dices
print(f"✊🎲 You rolled: ", end="")
for dice in dices:
if dice.color == "red":
print(
f"{COLORS['RED']}{dice.color} dice{COLORS['END']} -> {COLORS['BOLD']}{dice.face}{COLORS['END']}; ",
end="",
)
elif dice.color == "yellow":
print(
f"{COLORS['YELLOW']}{dice.color} dice{COLORS['END']} -> {COLORS['BOLD']}{dice.face}{COLORS['END']}; ",
end="",
)
elif dice.color == "green":
print(
f"{COLORS['GREEN']}{dice.color} dice{COLORS['END']} -> {COLORS['BOLD']}{dice.face}{COLORS['END']}; ",
end="",
)
print("")
# Add dices to the player's hand
player.dices.extend(dices)
return {"finish": False, "brains": brains, "shotguns": shotguns, "footprints": footprints}
def pick_dices(n_of_dices: int) -> List[Dice]:
total_dices = len(dices_box)
if n_of_dices > total_dices:
raise ValueError("Unavailable amount of dices!")
picked_dices = random.sample(dices_box, n_of_dices)
for dice in picked_dices:
dices_box.remove(dice)
return picked_dices
def finish_action(player: Player, add_score: int) -> None:
player.score += add_score
print(f"{player} you have {player.score} points!")
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\nBye!")
exit(0)