-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathrpsgame.py
181 lines (125 loc) · 4.18 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
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
import datetime
import random
import json
import os
rolls = {}
def main():
log("App starting up...")
load_rolls()
show_header()
show_leaderboard()
player1, player2 = get_players()
log(f"{player1} has logged in.")
play_game(player1, player2)
log("Game over.")
def show_header():
print("---------------------------")
print(" Rock Paper Scissors")
print(" File I/O Edition")
print("---------------------------")
def show_leaderboard():
leaders = load_leaders()
sorted_leaders = list(leaders.items())
sorted_leaders.sort(key=lambda l: l[1], reverse=True)
print()
print("---------------------------")
print("LEADERS:")
for name, wins in sorted_leaders[0:5]:
print(f"{wins:,} -- {name}")
print("---------------------------")
print()
def get_players():
p1 = input("Player 1, what is your name? ")
p2 = "Computer"
return p1, p2
def play_game(player_1, player_2):
log(f"New game starting between {player_1} and {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
log(f"Round: {player_1} roll {roll1} and {player_2} rolls {roll2}")
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:
msg = "This round was a tie!"
print(msg)
log(msg)
else:
msg = f"{winner} takes the round!"
print(msg)
log(msg)
wins[winner] += 1
msg = f"Score is {player_1}: {wins[player_1]} and {player_2}: {wins[player_2]}."
print(msg)
log(msg)
print()
overall_winner = find_winner(wins, wins.keys())
msg = f"{overall_winner} wins the game!"
print(msg)
log(msg)
record_win(overall_winner)
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]
def load_rolls():
global rolls
directory = os.path.dirname(__file__)
filename = os.path.join(directory, "rolls.json")
with open(filename, "r", encoding="utf-8") as fin:
rolls = json.load(fin)
log(f"Loaded rolls: {list(rolls.keys())} from {os.path.basename(filename)}.")
def load_leaders():
directory = os.path.dirname(__file__)
filename = os.path.join(directory, "leaderboard.json")
if not os.path.exists(filename):
return {}
with open(filename, "r", encoding="utf-8") as fin:
return json.load(fin)
def record_win(winner_name):
leaders = load_leaders()
if winner_name in leaders:
leaders[winner_name] += 1
else:
leaders[winner_name] = 1
directory = os.path.dirname(__file__)
filename = os.path.join(directory, "leaderboard.json")
with open(filename, "w", encoding="utf-8") as fout:
json.dump(leaders, fout)
def log(msg):
directory = os.path.dirname(__file__)
filename = os.path.join(directory, "rps.log")
with open(filename, "a", encoding="utf-8") as fout:
fout.write(f"[{datetime.datetime.now().date().isoformat()}] ")
fout.write(msg)
fout.write("\n")
if __name__ == "__main__":
main()