-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrpsgame.py
95 lines (66 loc) · 2.29 KB
/
rpsgame.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
import random
rolls = {
"rock": {"defeats": ["scissors"], "defeated_by": ["paper"]},
"paper": {"defeats": ["rock"], "defeated_by": ["scissors"]},
"scissors": {"defeats": ["paper"], "defeated_by": ["rock"]},
}
def main():
show_header()
play_game("You", "Computer")
def show_header():
print("---------------------------")
print(" Rock Paper Scissors")
print(" Data Structures Edition")
print("---------------------------")
def play_game(player_1, player_2):
wins = {player_1: 0, player_2: 0}
roll_names = list(rolls.keys())
while not find_winner(wins, wins.keys()):
roll1 = get_roll(player_1, roll_names)
roll2 = random.choice(roll_names)
if not roll1:
print("Try again!")
continue
print(f"{player_1} roll {roll1}")
print(f"{player_2} rolls {roll2}")
winner = check_for_winning_throw(player_1, player_2, roll1, roll2)
if winner is None:
print("This round was a tie!")
else:
print(f"{winner} takes the round!")
wins[winner] += 1
# print(f"Current win status: {wins}")
print(
f"Score is {player_1}: {wins[player_1]} and {player_2}: {wins[player_2]}."
)
print()
overall_winner = find_winner(wins, wins.keys())
print(f"{overall_winner} wins the game!")
def find_winner(wins, names):
best_of = 3
for name in names:
if wins.get(name, 0) >= best_of:
return name
return None
def check_for_winning_throw(player_1, player_2, roll1, roll2):
winner = None
if roll1 == roll2:
print("The play was tied!")
outcome = rolls.get(roll1, {})
if roll2 in outcome.get("defeats"):
return player_1
elif roll2 in outcome.get("defeated_by"):
return player_2
return winner
def get_roll(player_name, roll_names):
print("Available rolls:")
for index, r in enumerate(roll_names, start=1):
print(f"{index}. {r}")
text = input(f"{player_name}, what is your roll? ")
selected_index = int(text) - 1
if selected_index < 0 or selected_index >= len(rolls):
print(f"Sorry {player_name}, {text} is out of bounds!")
return None
return roll_names[selected_index]
if __name__ == "__main__":
main()