Skip to content

Commit e21871c

Browse files
committed
added error handling and best of
1 parent dc63fa3 commit e21871c

File tree

1 file changed

+24
-5
lines changed

1 file changed

+24
-5
lines changed

days/13-15-text-games/rps_classes.py

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@ def __init__(self, name, wins=0):
1717
self.wins = wins
1818

1919

20+
class EvenNumberException(Exception):
21+
pass
22+
23+
2024
# parses the csv for possible actions and victories
2125
victories = defaultdict(list)
2226
with open("data/battle-table.csv", "r") as csvfile:
@@ -37,8 +41,7 @@ def main():
3741
name = input("Enter your name: ")
3842
player1 = Player(name)
3943
player2 = Player("Computer")
40-
BEST_OF_NUM = 3
41-
print(f"Welcome {player1.name}. Let's play best of {BEST_OF_NUM} rounds.")
44+
BEST_OF_NUM = best_of(player1)
4245
game_loop(player1, player2, BEST_OF_NUM)
4346
get_final_score(player1, player2, BEST_OF_NUM)
4447

@@ -48,6 +51,22 @@ def print_header():
4851
print(" 15-way Rock Paper Scissors")
4952
print("=" * 30)
5053

54+
def best_of(player1):
55+
print(f"Welcome {player1.name}!\n")
56+
while True:
57+
try:
58+
best_of_num = int(input("Enter an odd number of rounds to play:"))
59+
if best_of_num % 2 == 0:
60+
raise EvenNumberException
61+
print(f"OK {player1.name}, let's play best of {best_of_num} rounds. Good Luck!\n")
62+
break
63+
except ValueError:
64+
print("You did not enter an number.\n")
65+
except EvenNumberException:
66+
print("You entered an even number which means the match could end in a tie.\n")
67+
68+
return best_of_num
69+
5170

5271
def game_loop(player1, player2, BEST_OF_NUM):
5372
while max([player1.wins, player2.wins]) < BEST_OF_NUM - 1:
@@ -58,7 +77,7 @@ def game_loop(player1, player2, BEST_OF_NUM):
5877
print(f"Invalid selection. Enter a value in range {range_str}")
5978
continue
6079

61-
print(f"You choose {p1_turn.action}")
80+
print(f"You chose {p1_turn.action}")
6281
print("The computer is thinking.")
6382
time.sleep(0.5)
6483
print("1...")
@@ -68,7 +87,7 @@ def game_loop(player1, player2, BEST_OF_NUM):
6887
print("3...")
6988
time.sleep(0.25)
7089
p2_turn = get_computers_selection()
71-
print(f"The Computer choose {p2_turn.action}")
90+
print(f"The Computer chose {p2_turn.action}")
7291
determine_winner(p1_turn, p2_turn, player1, player2, victories)
7392
get_score(player1, player2)
7493
input("Press ENTER to move to the next round.")
@@ -109,7 +128,7 @@ def get_final_score(player1, player2, BEST_OF_NUM):
109128
print(f"\n{player1.name} won {player1.wins} times.")
110129
print(f"{player2.name} won {player2.wins} times.", end="\n\n")
111130
if player1.wins == BEST_OF_NUM - 1:
112-
print("You won the match! Thanks for playing!")
131+
print(f"You won the match! Thanks for playing!")
113132
if player2.wins == BEST_OF_NUM - 1:
114133
print("The Computer won the math! Better luck next time.")
115134

0 commit comments

Comments
 (0)