Rock paper scissors in python with "algorithm"

Joined
Feb 27, 2022
Messages
1
Reaction score
0
I have been making this game in python, thanks to the documentation that has been given to me in class, but now they have asked me to modify a series of things, the problem is that when I implement it to my code it stops working since the new thing that indicates is not very clear to me. I have serious problems with this code. Since I have to create a get_winner_action and a get_random_computer_action() , I don't know where to start. I would be grateful if you could help me or explain since it is not clear to me.
```
#!/usr/bin/python3 import random #1.15-------------------------------------------------------------- from enum import IntEnum class GameAction(IntEnum): Piedra = 0 Papel = 1 Tijeras = 2 #1.15-------------------------------------------------------------- #1.17------------------------------------------------------------------ def get_user_action(): # Scalable to more options (beyond rock, paper and scissors...) game_choices = [f"{game_action.name}[{game_action.value}]" for game_action in GameAction] game_choices_str = ", ".join(game_choices) user_selection = int(input(f"\nPick a choice ({game_choices_str}): ")) user_action = GameAction(user_selection) return user_action #1.17------------------------------------------------------------------ #1.18------------------------------------------------------------------ def get_computer_action(): computer_selection = random.randint(0, len(GameAction) - 1) computer_action = GameAction(computer_selection) print(f"Computer picked {computer_action.name}.") return computer_action #1.18------------------------------------------------------------------ #1.19------------------------------------------------------------------ def play_another_round(): another_round = input("\nAnother round? (y/n): ") return another_round.lower() == 'y' #1.19------------------------------------------------------------------ #1.16------------------------------------------------------------------ def main(): while True: try: user_action = get_user_action() except ValueError as e: range_str = f"[0, {len(GameAction) - 1}]" print(f"Invalid selection. Pick a choice in range {range_str}!") continue computer_action = get_computer_action() assess_game(user_action, computer_action) if not play_another_round(): break #1.16------------------------------------------------------------------ def assess_game(user_action, computer_action): if user_action == computer_action: print(f"User and computer picked {user_action}. Draw game!") # You picked PIEDRA elif user_action == PIEDRA: if computer_action == TIJERAS: print("PIEDRA smashes TIJERAS. You won!") else: print("PAPEL covers PIEDRA. You lost!") # You picked PAPEL elif user_action == PAPEL: if computer_action == PIEDRA: print("PAPEL covers PIEDRA. You won!") else: print("TIJERAS cuts PAPEL. You lost!") # You picked TIJERAS elif user_action == TIJERAS: if computer_action == PIEDRA: print("PIEDRA smashes TIJERAS. You lost!") else: print("TIJERAS cuts PAPEL. You won!") if __name__ == "__main__": main() #1.20------------------------------------------------------------------ def main(): game_history = [] user_actions_history = [] while True: try: user_action = get_user_action() user_actions_history.append(user_action) except ValueError as e: range_str = f"[0, {len(GameAction) - 1}]" print(f"Invalid selection. Pick a choice in range {range_str}!") continue computer_action = get_computer_action(user_actions_history, game_history) game_result = assess_game(user_action, computer_action) game_history.append(game_result) if not play_another_round(): break #1.20------------------------------------------------------------------ #1.21------------------------------------------------------------------ class GameResult(IntEnum): Victory = 0 Defeat = 1 Tie = 2 Victories = { GameAction.Piedra: GameAction.Papel, GameAction.Papel: GameAction.Tijeras, GameAction.Tijeras: GameAction.Piedra } #1.21------------------------------------------------------------------ NUMBER_RECENT_ACTIONS = 5 def get_computer_action(user_actions_history, game_history): # No previous user actions =>random computer choice if not user_actions_history or not game_history: computer_action = = get_random_computer_action() # Alternative AI functionality # Choice that would beat the user’s most frequent recent choice else: most_frequent_recent_computer_action = \ GameAction(mode(user_actions_history[-NUMBER_RECENT_ACTIONS:])) computer_action = get_winner_action(most_frequent_recent_computer_action) print(f"Computer picked {computer_action.name}.") return computer_action

```
The problem is that I don't know how I can create the get_winner since I don't understand it, how I can create the function.[ICODE][ICODE][/ICODE][/ICODE]
 
Last edited:
Joined
May 11, 2022
Messages
60
Reaction score
6
Python:
import random


def actionChoices():
   choices =[]
   standard = input("For standard Rock Paper Scissors type Y")
   if standard == "Y":
      choices = ["Rock","Paper","Scissors"]
   else:
      check = True
      while check:
         options =int(input("number of actions? "))
         if options%2 == 0:
             print("the number of options must be odd \n")
             continue
         else:
             check = False
      for i in range(0,options):
          optionName = input("option name? ")
          choices += [optionName]
   return choices


def get_user_action(choices):
   action =""
   for i in range(0,len(choices)):
      action += choices[i] + " "
   choose = (input("make your selection "+action+"? " +"or "+ "0 -" +str(len(choices)-1)+"? "))
   try:
      choose = int(choose)
   except ValueError:
      return choose
   return choose
def get_computer_action(choices):
     choose = random.randint(0,len(choices)-1)
     return choose
  
def numberRounds():
    round = int(input("how many rounds would you like to play? "))
    return round


def assess_game(choices,user,cpu,size):
    half = size//2
    if user == cpu:
       print("You chose " +choices[user] +" cpu chose "+choices[cpu]+" tie!")
       return
    check = False
    for i in range(1,half+1):
       result = (user +i)%size
       if cpu == result:
          check = True
          break
    if check:
       print("You chose " +choices[user] +" cpu chose "+choices[cpu]+" cpu wins!")
    else:
       print("you chose " +choices[user] +" cpu chose "+choices[cpu]+" you win!")
    
def main():
    while True:
        choices = actionChoices()
        rounds = numberRounds()
        count = 0
        check1 = False
        while count < rounds:
            user_action = get_user_action(choices)
            if type(user_action) == str:
               if user_action not in choices:
                  print( "invalid selection")
                  continue
               else:
                  user_action = choices.index(user_action)
            if type(user_action) == int:
               if user_action < 0 or user_action > len(choices)-1:
                  print( "invalid selection")
                  continue
            cpu = get_computer_action(choices)
            assess_game(choices,user_action,cpu,len(choices))
            count += 1
            if count == rounds:
               chk = input("would you like to quit? Y/N ")
               if chk =="Y":
                  check1 = True
                  break
               check2 = input("would you like to reset settings? Y/N ")
               if check2 == "Y":
                  break
               else:
                  count = 0
                  rounds = numberRounds()
        if check1:
           break
  
main()
so i made the code much more readable. i hope you can take it from here.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,056
Messages
2,570,440
Members
47,101
Latest member
DoloresHol

Latest Threads

Top