1
+ import random
2
+
3
+ def display_rules ():
4
+ print ("Rock vs paper->paper wins" )
5
+ print ("Rock vs scissors->Rock wins" )
6
+ print ("Paper vs scissors->scissors wins" )
7
+
8
+ def get_user_choice ():
9
+ valid_choices = ['r' , 'p' , 's' ]
10
+ while True :
11
+ user_input = input ("Choose Rock (r), Paper (p), or Scissors (s): " ).lower ()
12
+ if user_input in valid_choices :
13
+ return user_input
14
+ else :
15
+ print ("Invalid input. Please try again." )
16
+
17
+ def get_computer_choice ():
18
+ choices = ['r' , 'p' , 's' ]
19
+ return random .choice (choices )
20
+
21
+ def determine_winner (user , computer ):
22
+ if user == computer :
23
+ return "tie"
24
+ elif (user == 'r' and computer == 's' ) or \
25
+ (user == 'p' and computer == 'r' ) or \
26
+ (user == 's' and computer == 'p' ):
27
+ return "user"
28
+ else :
29
+ return "computer"
30
+
31
+ def display_winner (winner , user , computer ):
32
+ if winner == "tie" :
33
+ print ("It's a tie!" )
34
+ elif winner == "user" :
35
+ print (f"You win! { get_choice_name (user )} beats { get_choice_name (computer )} " )
36
+ else :
37
+ print (f"Computer wins! { get_choice_name (computer )} beats { get_choice_name (user )} " )
38
+
39
+ def get_choice_name (choice ):
40
+ if choice == 'r' :
41
+ return "Rock"
42
+ elif choice == 'p' :
43
+ return "Paper"
44
+ else :
45
+ return "Scissors"
46
+
47
+ def update_score (winner , user_score , computer_score ):
48
+ if winner == "user" :
49
+ user_score += 1
50
+ else :
51
+ computer_score += 1
52
+ return user_score , computer_score
53
+
54
+ def main ():
55
+ display_rules ()
56
+ user_score = 0
57
+ computer_score = 0
58
+ while True :
59
+ user_choice = get_user_choice ()
60
+ computer_choice = get_computer_choice ()
61
+ winner = determine_winner (user_choice , computer_choice )
62
+ display_winner (winner , user_choice , computer_choice )
63
+ user_score , computer_score = update_score (winner , user_score , computer_score )
64
+ print (f"Score: User { user_score } - Computer { computer_score } " )
65
+ print ("Do you want to play again? (Y/N)" )
66
+ ans = input ().lower ()
67
+ if ans != 'y' :
68
+ break
69
+ print ("Thanks for playing!" )
70
+
71
+ if __name__ == "__main__" :
72
+ main ()
0 commit comments