Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a simple "Rock Paper Scissors" game bot

Tags:

python

This is what I came up with for my rock-paper-scissors game:

import random 

from time import sleep 

print "Please select: " 
print "1  Rock" 
print "2  Paper" 
print "3  Scissors" 

player = input ("Choose from 1-3: ") 

if player == 1: 
    print "You choose Rock" 
    sleep (2) 
    print "CPU chooses Paper" 
    sleep (.5) 
    print "You lose, and you will never win!" 

elif player == 2: 
    print "You choose Paper" 
    sleep (2) 
    print "CPU chooses Scissors" 
    sleep (.5) 
    print "You lose, and you will never win!" 

else: 
    print "You choose Scissors" 
    sleep (2) 
    print "CPU chooses Rock" 
    sleep (.5) 
    print "You lose, and you will never win!"

and what I want the program to do is to RANDOMLY choose 1 out of the three options (rock paper scissors) no matter what the user inputs. How can I accomplish this?

like image 480
Test Avatar asked Jan 17 '09 14:01

Test


People also ask

How does rock, paper, scissors AI work?

Each “game” in the app is composed of a series of “rounds” where the player and the AI each make a choice between rock, paper, or scissors, and the winner is determined. The game ends when either the player or the computer win a specified number of rounds.

How do you make a rock, paper, scissors function in Python?

It's a tie!") 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 cuts paper!


2 Answers

Well, you've already imported the random module, that's a start.

Try the random.choice function.

>>> from random import choice
>>> cpu_choice = choice(('rock', 'paper', 'scissors'))
like image 59
sykora Avatar answered Oct 10 '22 01:10

sykora


import random

ROCK, PAPER, SCISSORS = 1, 2, 3
names = 'ROCK', 'PAPER', 'SCISSORS'

def beats(a, b):
    if (a,b) in ((ROCK, PAPER), (PAPER, SCISSORS), (SCISSORS, ROCK)): 
        return False

    return True


print "Please select: " 
print "1  Rock" 
print "2  Paper" 
print "3  Scissors" 

player = int(input ("Choose from 1-3: "))
cpu = random.choice((ROCK, PAPER, SCISSORS))

if cpu != player:
    if beats(player, cpu):
        print "player won"
    else:
        print "cpu won"
else:
    print "tie!"

print names[player-1], "vs", names[cpu-1]
like image 7
gumuz Avatar answered Oct 10 '22 00:10

gumuz