0

I am writing a program for a rock paper scissors game. Currently I am using the random command for the computer to choose between the three options. I want to add a fourth option, but instead of it being an even chance between the four I'd like to be a 1% chance to get the fourth option. Is there a way to assign a specific % chance to these options?

Here is my code currently:

import random
user_action = input("Choose: Rock, Paper, Scissors")
possible_actions = ["Rock", "Paper", "Scissors"]
computer_action = random.choice(possible_actions)
print(f"\n You Chose {user_action}, Computer Chose {computer_action}.\n")

if user_action == computer_action:
    print(f"Both player chose {user_action}. You Tied!")
elif user_action == "Rock":
    if computer_action == "Scissors":
        print("Rock smashes scissors! You win!")
    else:
        print("Paper covers rock, you lose!")
elif user_action == "Paper":
    if computer_action == "Rock":
        print("Paper covers rock, You Win!")
    else:
        print("Scissors cut the paper into shreds! You lose!")
elif user_action == "Scissors":
    if computer_action == "Paper":
        print("Scissors cut the paper into shreds! You win!")
    else:
        print("Rock smashes scissors! You lose!")
desertnaut
  • 57,590
  • 26
  • 140
  • 166
RyanCSB
  • 11

3 Answers3

1

The random.choices method lets you assign weights to the alternatives.

n = random.choices( possible_actions, weights=[33,33,33,1], k=1 )

You might consider creating a matrix data structure that has the results. That way your mainline code could be down to one or two lines:

result = results[user_action][computer_action]
if result == 'tie':
   ...
elif result == 'userwin':
   ...
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
0
import numpy as np

numberList = ["Rock", "Paper", "Scissors", "Instant Win"]

choice = np.random.choice(numberList, 1, p=[0.33, 0.33, 0.33, 
0.01])
print(choice)

This should work and should be easy to integrate to the code

0

If you wished to achieve this "manually," you might use a list comprehension to generate a weighted list and then randomly choose from that list.

>>> list(zip([1,2], [3,4]))
[(1, 3), (2, 4)]
>>> [c 
...  for a, b in zip([1,2], [3,4]) 
...  for c in [a] * b]
[1, 1, 1, 2, 2, 2, 2]
>>> import random
>>> random.choice(
...   [c 
...    for a, b in zip([1,2], [3,4]) 
...    for c in [a] * b]
... )
2
Chris
  • 26,361
  • 5
  • 21
  • 42