I'm having a problem with my python program and I've spent too many time trying to fix it but I can't. I was hoping you could help me.
Anyway, the problem is in:
def choose_winnerPvsP(p1,p2):
When I run it the part of Player vs Computer woks perfectly, but the part of Player vs Player gives me this error: "Local variable player_1score referenced before assignment"
I can't understand why the if's are never checked.
PS: I'm a beginner and I know that the code could be more compact, but for now I just want this thing working. Thanks in advance
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from random import *
from time import sleep
import sys
import os
os.system("cls") #ou "clear" se estiver em linux
print "******Welcome to Rock Paper Scissors Game!******\n"
playerOrComputer = str(raw_input("Would you like to play against a friend or a computer?(F or C) \n" ))
p1_score = 0
p2_score = 0
def player_turn(nome_player):
print "What do you want to do, " + nome_player + "?"
pchoice = str(raw_input("ROCK (R) PAPER (P) SCISSORS (S) or Quit\n>> "))
if pchoice == "R" or pchoice == "r":
print "You chosed ROCK"
elif pchoice == "P" or pchoice == "p":
print "You chosed PAPER"
elif pchoice == "S" or pchoice == "s":
print "You chosed SCISSORS"
elif pchoice == "quit" or pchoice == "Quit":
sys.exit()
else:
print "I didn't understand! Please repeat."
player_turn()
return pchoice
def player_turn2p(nome_player1,p2):
print "What do you want to do, " + nome_player1 + "?"
pchoice1 = str(raw_input("ROCK (R) PAPER (P) SCISSORS (S)\n>> "))
if pchoice1 == "R" or pchoice1 == "r":
pchoice1 = "ROCK"
print "You chosed ROCK"
sleep(1)
os.system("cls")
elif pchoice1 == "P" or pchoice1 == "p":
pchoice1 = "PAPER"
print "You chosed PAPER"
sleep(1)
os.system("cls")
elif pchoice1 == "S" or pchoice1 == "s":
pchoice1 = "SCISSORS"
print "You chosed SCISSORS"
sleep(1)
os.system("cls")
elif pchoice1 == "quit" or pchoice == "Quit":
sys.exit()
else:
print "I didn't understand!"
player_turn2p(nome_player1,p2)
print "What do you want to do, " + p2 + "?"
pchoice2 = str(raw_input("ROCK (R) PAPER (P) SCISSORS (S)\n>> "))
if pchoice2 == "R" or pchoice2 == "r":
print p2 + " chosed ROCK\n" + nome_player1 + " chosed " + pchoice1
elif pchoice2 == "P" or pchoice2 == "p":
print p2 + " chosed PAPER\n" + nome_player1 + " chosed " + pchoice1
elif pchoice2 == "S" or pchoice2 == "s":
print p2 + " chosed SCISSORS\n" + nome_player1 + " chosed " + pchoice1
elif pchoice1 == "quit" or pchoice == "Quit":
sys.exit()
else:
print "I didn't understand!"
player_turn2p(nome_player1,p2)
return pchoice1, pchoice2
def computer_turn():
choicecomp = randint(1,3)
if choicecomp == 1:
choicecomp = "ROCK"
elif choicecomp == 2:
choicecomp = "PAPER"
elif choicecomp == 3:
choicecomp = "SCISSORS"
return choicecomp
#1-Rock 2-Paper 3-Scissors
def choose_winnerPvsP(p1,p2):
player_choice1, player_choice2= player_turn2p(p1,p2)
if player_choice1 == "R" and player_choice2 == "R" or player_choice1 == "r" and player_choice2 == "r" or player_choice1 == "R" and player_choice2 == "r" or player_choice1 == "r" and player_choice2 == "R":
player_1score = "lose"
player_2score = "win"
print "******It's a draw!******"
elif player_choice1 == "R" and player_choice2 == "P" or player_choice1 == "r" and player_choice2 == "p" or player_choice1 == "R" and player_choice2 == "p" or player_choice1 == "r" and player_choice2 == "P":
player_1score = "lose"
player_2score = "win"
print "******" + p2 + " wins!******"
elif player_choice1 == "R" and player_choice2 == "S" or player_choice1 == "r" and player_choice2 == "s" or player_choice1 == "R" and player_choice2 == "s" or player_choice1 == "r" and player_choice2 == "S":
player_1score = "win"
player_2score = "lose"
print "******" + p1 + " wins!******"
elif player_choice1 == "P" and player_choice2 == "R" or player_choice1 == "p" and player_choice2 == "r" or player_choice1 == "P" and player_choice2 == "r" or player_choice1 == "p" and player_choice2 == "R":
player_1score = "win"
player_2score = "lose"
print "******" + p1 + " wins!******"
elif player_choice1 == "P" and player_choice2 == "P" or player_choice1 == "p" and player_choice2 == "p" or player_choice1 == "P" and player_choice2 == "p" or player_choice1 == "p" and player_choice2 == "P":
player_1score = "draw"
player_2score = "draw"
print "******It's a draw!******"
elif player_choice1 == "P" and player_choice2 == "S" or player_choice1 == "p" and player_choice2 == "s" or player_choice1 == "P" and player_choice2 == "s" or player_choice1 == "p" and player_choice2 == "S":
player_1score = "lose"
player_2score = "win"
print "******" + p2 + " wins!******"
elif player_choice1 == "S" and player_choice2 == "R" or player_choice1 == "s" and player_choice2 == "r" or player_choice1 == "S" and player_choice2 == "r" or player_choice1 == "s" and player_choice2 == "R":
player_1score = "lose"
player_2score = "win"
print "******" + p2 + " wins!******"
elif player_choice1 == "S" and player_choice2 == "P" or player_choice1 == "s" and player_choice2 == "p" or player_choice1 == "S" and player_choice2 == "p" or player_choice1 == "s" and player_choice2 == "P":
player_1score = "win"
player_2score = "lose"
print "******" + p1 + " wins!******"
elif player_choice1 == "S" and player_choice2 == "S" or player_choice1 == "s" and player_choice2 == "s" or player_choice1 == "S" and player_choice2 == "s" or player_choice1 == "s" and player_choice2 == "S":
player_1score = "draw"
player_2score = "draw"
print "******It's a draw!******"
return player_1score, player_2score
def choose_winnerPvsC(player_name,player_choice, computer_choice):
if player_choice == "R" and computer_choice == "ROCK" or player_choice == "r" and computer_choice == "ROCK":
computer_score = "draw"
player_score = "draw"
print "******It's a draw!****** "
elif player_choice == "R" and computer_choice == "PAPER" or player_choice == "r" and computer_choice == "PAPER":
computer_score = "win"
player_score = "lose"
print "******I win!****** "
elif player_choice == "R" and computer_choice == "SCISSORS" or player_choice == "r" and computer_choice == "SCISSORS":
player_score = "win"
computer_score = "lose"
print "******" + player_name + " wins!****** "
elif player_choice == "P" and computer_choice == "ROCK" or player_choice == "p" and computer_choice == "ROCK":
player_score = "win"
computer_score = "lose"
print "******" + player_name + " wins!****** "
elif player_choice == "P" and computer_choice == "PAPER" or player_choice == "p" and computer_choice == "PAPER":
computer_score = "draw"
player_score = "draw"
print "******It's a draw!******"
elif player_choice == "P" and computer_choice == "SCISSORS" or player_choice == "p" and computer_choice == "SCISSORS":
computer_score = "win"
player_score = "lose"
print "******I win!****** "
elif player_choice == "S" and computer_choice == "ROCK" or player_choice == "s" and computer_choice == "ROCK":
computer_score = "win"
player_score = "lose"
print "******I win!****** "
elif player_choice == "S" and computer_choice == "PAPER" or player_choice == "s" and computer_choice == "PAPER":
player_score = "win"
computer_score = "lose"
print "******" + player_name + " wins!****** "
elif player_choice == "S" and computer_choice == "SCISSORS" or player_choice == "s" and computer_choice == "SCISSORS":
computer_score = "draw"
player_score = "draw"
print "******It's a draw!****** "
return player_score, computer_score
def loopPvsP():
p1score = 0
p2score = 0
while True:
player_1score, player_2score = choose_winnerPvsP(p1,p2)
if player_1score == "win":
p1score += 1
elif player_2score == "win":
p2score += 1
print p1 + ":",p1score
print p2 + ":",p2score
if p1score == 5:
print "-+-+-+-+-"+ p1.upper() + "IS THE BIG WINNER!!-+-+-+-+-"
break
elif p2score == 5:
print "-+-+-+-+-"+ p2.upper() + "IS THE BIG WINNER!!-+-+-+-+-"
break
def loopPvsC():
pscore = 0
cscore = 0
while True:
pchoice = player_turn(p1c)
choicecomp = computer_turn()
print "I chosed "+ choicecomp + "!"
player_score, computer_score = choose_winnerPvsC(p1c,pchoice, choicecomp)
if computer_score == "win":
cscore += 1
elif player_score == "win":
pscore += 1
print "Computer:",cscore
print p1c + ":",pscore
if pscore == 5:
print "-+-+-+-+-YOU ARE THE BIG WINNER!!-+-+-+-+-"
break
elif cscore == 5:
print "-+-+-+-+-I'M THE BIG WINNER!!-+-+-+-+-"
break
if playerOrComputer == "f" or playerOrComputer == "F":
p1 = str(raw_input("Player 1: "))
p2 = str(raw_input("Player 2: "))
os.system("cls")
loopPvsP()
elif playerOrComputer == "c" or playerOrComputer == "C":
p1c = str(raw_input("Player: "))
os.system("cls")
loopPvsC()
else:
print "That's not what I asked!"
Meh. Debuggers are overrated -- I go years without using one in Python. Just add a final else clause to your big if/elif statement:
else:
print "Did not find answer"
print repr(player_choice), repr(computer_choice)
If that doesn't hit, then it means you have a typo somewhere else, perhaps. Anyway, you can certainly add more debugging statements -- one to each elif clause, if need be.
Which brings up another point -- you have a lot of if/elif clauses.
You might want to investigate things like dicts with values you can add together, or functions you can call, to reduce the number of if/else statements you need.
Related
I am making a rock paper scissors program in python.
I have written a function which should return the result of a game but it only returns the else condition, what do?
Here is the code of the program.
import random
def emove():
computer=["r","p","s"]
return(random.choice(computer))
def winner():
if user == "r" and emove == "p":
return("Computer won!")
elif user == "p" and emove == "r":
return("You won!")
elif user == "p" and emove == "s":
return("Computer won!")
elif user == "s" and emove == "p":
return("You won!")
elif user == "r" and emove == "s":
return("You won!")
elif user == "s" and emove == "p":
return("You won!")
elif user == emove:
return("Tie")
else:
return("Wrong input")
user=input("Welcome to Rock Paper Scissors, to play enter the initial letter of the choice you make:").lower()
while user:
print("Computer chose",emove(),",you chose", (user), winner() )
playagain = input("Play again? (y/n): ").lower()
if playagain =="n":
print("Thanks for playing")
break
emove is a function , so emove == "p" always return Flase
So I suggest you the following minor changes:
import random
def emove():
computer=["r","p","s"]
return(random.choice(computer))
def winner():
if user == "r" and em == "p":
return("Computer won!")
elif user == "p" and em == "r":
return("You won!")
elif user == "p" and em == "s":
return("Computer won!")
elif user == "s" and em == "p":
return("You won!")
elif user == "r" and em == "s":
return("You won!")
elif user == "s" and em == "p":
return("You won!")
elif user == em:
return("Tie")
else:
return("Wrong input")
user=input("Welcome to Rock Paper Scissors, to play enter the initial letter of the choice you make:").lower()
while user:
em=emove()
print("Computer chose",em,",you chose", (user), winner() )
playagain = input("Play again? (y/n): ").lower()
if playagain =="n":
print("Thanks for playing")
break
Because you are missing function parantheses emove() inside winner() function.
def winner():
print(user,emove())
var = emove() # storing random choice in variable.
if user == "r" and var == "p":
return ("Computer won!")
elif user == "p" and var == "r":
return ("You won!")
elif user == "p" and var == "s":
return ("Computer won!")
elif user == "s" and var == "p":
return ("You won!")
elif user == "r" and var == "s":
return ("You won!")
elif user == "s" and var == "p":
return ("You won!")
elif user == var:
return ("Tie")
else:
return ("Wrong input")
Your code is almost right, but you have a few things wrong with your implementation. Here is a version of your code that I think does everything you desire:
import random
def computer_move():
computer = ["r", "p", "s"]
return (random.choice(computer))
def winner(emove):
if user == "r" and emove == "p":
return ("Computer won!")
elif user == "p" and emove == "r":
return ("You won!")
elif user == "p" and emove == "s":
return ("Computer won!")
elif user == "s" and emove == "p":
return ("You won!")
elif user == "r" and emove == "s":
return ("You won!")
elif user == "s" and emove == "p":
return ("You won!")
elif user == emove:
return ("Tie")
else:
return ("Wrong input")
while True:
user = input("Welcome to Rock Paper Scissors, to play enter the initial letter of the choice you make:").lower()
emove = computer_move()
print("Computer chose", emove, ",you chose", user, winner(emove))
playagain = input("Play again? (y/n): ").lower()
if playagain == "n":
print("Thanks for playing")
break
I define a variable named 'computerChoice' in a function and then attempt to use it in another variable but it says that 'computerChoice' is undefined... Being new to Python, I am not sure why this is happening so I hope that you could help answer my question!
def computerDecision():
import random
for x in range(1):
num = random.randint(1,4)
if num == 1:
computerChoice = 'rock'
elif num == 2:
computerChoice = 'paper'
elif num == 3:
computerChoice = 'scissors'
def determineWinner():
if userInput == computerChoice:
print("You both chose " + computerChoice)
print("DRAW!")
elif userInput == 'rock' and computerChoice == 'paper':
print("The computer chose " + computerChoice)
print("COMPUTER WINS!")
elif userInput == 'rock' and computerChoice == 'scissors':
print("The computer chose " + computerChoice)
print('USER WINS!')
elif userInput == 'paper' and computerChoice == 'rock':
print("The computer chose " + computerChoice)
print("USER WINS!")
elif userInput == 'paper' and computerChoice == 'scissors':
print("The computer chose " + computerChoice)
print("COMPUTER WINS!")
elif userInput == 'scissors' and computerChoice == 'rock':
print("The computer chose " + computerChoice)
print("COMPUTER WINS!")
elif userInput == 'scissors' and computerChoice == 'paper':
print("The computer chose " + computerChoice)
print("USER WINS!")
The computerChoice variable is restricted in scope to the function in which it was defined. This is to prevent functions from interfering with one another. You can declare it to be global (accessible from anywhere) with the keyword global:
global computerChoice
This is probably not what you want, however, as your functions do not need to interact with each other. You can just make computerDecision() return its choice.
import random
def computerDecision():
for x in range(1):
num = random.randint(1,4)
if num == 1:
return 'rock'
elif num == 2:
return 'paper'
elif num == 3:
return 'scissors'
def determineWinner():
computerChoice = computerDecision()
if userInput == computerChoice:
print("You both chose " + computerChoice)
print("DRAW!")
elif userInput == 'rock' and computerChoice == 'paper':
print("The computer chose " + computerChoice)
print("COMPUTER WINS!")
elif userInput == 'rock' and computerChoice == 'scissors':
print("The computer chose " + computerChoice)
print('USER WINS!')
elif userInput == 'paper' and computerChoice == 'rock':
print("The computer chose " + computerChoice)
print("USER WINS!")
elif userInput == 'paper' and computerChoice == 'scissors':
print("The computer chose " + computerChoice)
print("COMPUTER WINS!")
elif userInput == 'scissors' and computerChoice == 'rock':
print("The computer chose " + computerChoice)
print("COMPUTER WINS!")
elif userInput == 'scissors' and computerChoice == 'paper':
print("The computer chose " + computerChoice)
print("USER WINS!")
Also note that computerDecision() can be redefined more simply, as just return random.choice(("rock", "paper", "scissors")).
I am just beginning to use python and could use some help! I was working on a rock, paper, scissors game and I wanted to add a restart option once either the human or computer reaches 3 wins.
I have looked all over for some answers but from all the other code I looked at seemed way out of my league or extremely different from what I wrote. I haven't tried using def and classes, which I saw a lot of, and made it look very simple. I know I'm probably going about this in a really round about way but I just want to finish this without completely copying someone's code.
import random
moves = ["Rock", "Paper", "Scissors"]
player_score = 0
computer_score = 0
draws = 0
keep_playing = True
while keep_playing == True:
cmove = random.choice(moves)
pmove = input("What is your move: Rock, Paper, or Scissors?")
print("The computer chose", cmove)
#Logic to game
if cmove == pmove:
print("It's a DRAW!")
elif pmove == "Rock" and cmove == "Scissors":
print("--Player Wins!--")
elif pmove == "Rock" and cmove == "Paper":
print("--Computer Wins!--")
elif cmove == "Paper" and cmove == "Rock":
print("--Player Wins!--")
elif pmove == "Paper" and cmove == "Scissors":
print("--Computer Wins!--")
elif pmove == "Scissors" and cmove == "Paper":
print("--Player Wins!--")
elif pmove == "Scissors" and cmove == "Rock":
print("--Computer Wins!--")
#Scoreboard
if pmove == cmove:
draws = draws + 1
print("Player:" + str(player_score) + ' | ' + "Computer:" + str(computer_score) + ' | ' + "Draws:" + str(draws))
if pmove == "Rock" and cmove == "Scissors":
player_score = player_score + 1
print("Player:" + str(player_score) + ' | ' + "Computer:" + str(computer_score) + ' | ' + "Draws:" + str(draws))
if pmove == "Rock" and cmove == "Paper":
computer_score = computer_score + 1
print("Player:" + str(player_score) + ' | ' + "Computer:" + str(computer_score) + ' | ' + "Draws:" + str(draws))
if pmove == "Paper" and cmove == "Rock":
player_score = player_score + 1
print("Player:" + str(player_score) + ' | ' + "Computer:" + str(computer_score) + ' | ' + "Draws:" + str(draws))
if pmove == "Paper" and cmove == "Scissors":
computer_score = computer_score + 1
print("Player:" + str(player_score) + ' | ' + "Computer:" + str(computer_score) + ' | ' + "Draws:" + str(draws))
if pmove == "Scissors" and cmove == "Paper":
player_score = player_score + 1
print("Player:" + str(player_score) + ' | ' + "Computer:" + str(computer_score) + ' | ' + "Draws:" + str(draws))
if pmove == "Scissors" and cmove == "Rock":
computer_score = computer_score + 1
print("Player:" + str(player_score) + ' | ' + "Computer:" + str(computer_score) + ' | ' + "Draws:" + str(draws))
#Win/lose restart point?
if player_score == 3:
print("-----You Win!-----")
break
if computer_score == 3:
print("-----You Lose!-----")
break
I want the code to end saying, "You Win!" or "You Lose!"and then ask for an input to whether or not they want to restart and then it resets the scores and keeps going or if they say no it breaks.
You already have the loop to do this. So when you want to "restart" your game, you really just need to reset the scores.
Starting from your win/lose conditions:
#Win/lose restart point?
if player_score == 3:
print("-----You Win!-----")
replay = input("Would you like to play again?")
if replay.upper().startswith('Y'):
player_score = 0
computer_score = 0
draws = 0
else:
keep_playing = False
if computer_score == 3:
print("-----You Lose!-----")
if replay.upper().startswith('Y'):
player_score = 0
computer_score = 0
draws = 0
else:
keep_playing = False
You need to get user input in the while loop and set keep_playing accordingly.
while keep_playing == True:
cmove = random.choice(moves)
pmove = input("What is your move: Rock, Paper, or Scissors?")
print("The computer chose", cmove)
#Logic to game
if cmove == pmove:
print("It's a DRAW!")
elif pmove == "Rock" and cmove == "Scissors":
print("--Player Wins!--")
elif pmove == "Rock" and cmove == "Paper":
print("--Computer Wins!--")
elif cmove == "Paper" and cmove == "Rock":
print("--Player Wins!--")
elif pmove == "Paper" and cmove == "Scissors":
print("--Computer Wins!--")
elif pmove == "Scissors" and cmove == "Paper":
print("--Player Wins!--")
elif pmove == "Scissors" and cmove == "Rock":
print("--Computer Wins!--")
# new code
play_again = input("Would you like to play again?")
keep_playing = play_again.lower().startswith('y') # this will be set to False if the user's input doesn't start with 'y', the loop will exit
I need to calculate difference between 'player_number' and 'comp_number' but it says:
TypeError: unsupported operand type(s) for Sub: 'NoneType' and 'int'
I understand this error. My code generates player_number is None type that is why I can not subtract it.
How can I handle this problem? Any ideas?
Here is my code:
def name_to_number(name):
if name == "rock":
name = 0
elif name == "paper":
name = 1
elif name == "Spock":
name = 2
elif name == "lizard":
name = 3
elif name == "scissors":
name = 4
else:
print 'Name is not listed:',name
def number_to_name(number):
if number == 0:
print "rock"
elif number == 1:
print "Spock"
elif number == 2:
print "paper"
elif number == 3:
print "lizard"
elif number == 4:
print "scissors"
else:
print 'Your number is not valid:',number
def rpsls(player_choice):
if player_choice == "rock":
print 'Player choses', player_choice
player_number = name_to_number(player_choice)
elif player_choice == "Spock":
print 'Player choses',player_choice
player_number = name_to_number(player_choice)
elif player_choice == "paper":
print 'Player choses',player_choice
player_number = name_to_number(player_choice)
elif player_choice == "lizard":
print 'Player choses',player_choice
player_number = name_to_number(player_choice)
elif player_choice == "scissors":
print 'Player choses',player_choice
player_number = name_to_number(player_choice)
else:
print "Name not in list",player_choice
import random
comp_number = random.randrange(0,4)
if comp_number == 0:
print "Computer choses",number_to_name(0)
elif comp_number == 1:
print "Computer choses",number_to_name(1)
elif comp_number == 2:
print "Computer choses",number_to_name(2)
elif comp_number == 3:
print "Computer choses",number_to_name(3)
elif comp_number == 4:
print "Computer choses",number_to_name(4)
diffrence = player_number - comp_number
if diffrence % 5 == 1 or 2:
print 'Player wins!'
elif (diffrence % 5) == 3 or 4:
print 'Computer wins!'
else:
print 'Game tie'
rpsls("rock")
You have this assigment
player_number = name_to_number(player_choice)
But none of your if/elif/else cases in name_to_number use the return keyword. To return a value from this function, you would do
def name_to_number(name):
if name == "rock":
return 0
elif name == "paper":
return 1
elif name == "Spock":
return 2
elif name == "lizard":
return 3
elif name == "scissors":
return 4
else:
print 'Name is not listed:',name
The same goes for your number_to_name function
Untested Fix. 'return' statement was missing. Using the same variable name for a string and an int is not nice programming style.
def name_to_number(name):
number = -1
if name == "rock":
number = 0
elif name == "paper":
number = 1
elif name == "Spock":
number = 2
elif name == "lizard":
number = 3
elif name == "scissors":
number = 4
else:
print 'Name is not listed:',name
return number #This line was missing
i have the following code for a rock paper scissors game:
import random
def rps():
computerchoice = random.randint(1,3)
if computerchoice == 1:
computerchoice = "rock"
elif computerchoice == 2:
computerchoice = "paper"
elif computerchoice == 3:
computerchoice = "scissors"
choice = raw_input("Rock, paper, or scissors?:")
choice = choice.lower()
if choice != "rock":
if choice != "paper":
if choice != "scissors":
print "Check your spelling and try again."
rps()
else:
pass
else:
pass
else:
print "The computer chose " + computerchoice + "."
if choice == computerchoice:
print "It's a draw!"
elif choice + computerchoice == "rockpaper":
print "Computer wins, paper covers rock!"
elif choice + computerchoice == "rockscissors":
print "Player wins, rock crushes scissors!"
elif choice + computerchoice == "paperrock":
print "Player wins, paper covers rock!"
elif choice + computerchoice == "paperscissors":
print "Computer wins, scissors cut paper!"
elif choice + computerchoice == "scissorsrock":
print "Computer wins, rock crushes scissors!"
elif choice + computerchoice == "scissorspaper":
print "Player wins, scissors cuts paper!"
rps()
Whenever i run it, it works fine if i pick rock, but if i pick paper or scissors, the code stops. It wont throw any kind of error, it just stops. Please help me!
This should be closer to what you need:
import random
def rps():
computerchoice = random.randint(1,3)
if computerchoice == 1:
computerchoice = "rock"
elif computerchoice == 2:
computerchoice = "paper"
elif computerchoice == 3:
computerchoice = "scissors"
choice = raw_input("Rock, paper, or scissors?:")
choice = choice.lower()
if choice not in ["scissors","paper","rock"]: # check if choice is valid
rps()
print "The computer chose " + computerchoice + "."
if choice == computerchoice: # move on to your comparison checks
choice + computerchoice
print "It's a draw!"
elif choice + computerchoice == "rockpaper":
print "Computer wins, paper covers rock!"
elif choice + computerchoice == "rockscissors":
print "Player wins, rock crushes scissors!"
elif choice + computerchoice == "paperrock":
print "Player wins, paper covers rock!"
elif choice + computerchoice == "paperscissors":
print "Computer wins, scissors cut paper!"
elif choice + computerchoice == "scissorsrock":
print "Computer wins, rock crushes scissors!"
elif choice + computerchoice == "scissorspaper":
print "Player wins, scissors cuts paper!"
rps()
The problem is from the first choice if statement:
if choice != "rock":
if choice != "paper":
if choice != "scissors":
when rock is selected it jumps to the else statement without evaluating the other two if statements. A more intuitive but admittedly non-Pythonic way is to have a series of nested if statements:
import random
def rps():
computerchoice = random.randint(1,3)
if computerchoice == 1:
computerchoice = "rock"
elif computerchoice == 2:
computerchoice = "paper"
elif computerchoice == 3:
computerchoice = "scissors"
choice = raw_input("Rock, paper, or scissors?:")
choice = choice.lower()
print "The computer chose " + computerchoice + "."
if choice == 'rock':
if computerchoice == 'rock':
print 'Draw: you both picked rock'
elif computerchoice == 'scissors':
print 'You win! Rock beats scissors'
elif computerchoice == 'paper':
print 'You lose. Try again'
elif choice == 'paper':
if computerchoice == 'rock':
print 'You win!'
elif computerchoice == 'scissors':
print 'You lose.'
elif computerchoice == 'paper':
print 'You draw.'
elif choice == 'scissors':
if computerchoice == 'rock':
print 'You lose.'
elif computerchoice == 'scissors':
print 'You draw.'
elif computerchoice == 'paper':
print 'You win.'
else:
print 'I am sorry, I could not make out what you typed. Try again'
rps()
rps()
Loop just your input. Don't recursively call the whole game again. Also setup a variable to test against for valid choices. Also if you break out the win conditions you can add to it easily. Maybe something like this
import random
CHOICES = {'rock': 'crushes', 'paper': 'covers', 'scissors': 'cuts'}
def win(p1, p2):
if p1 == p2:
return 0
if p1 == 'rock':
return 2 if p2 == 'paper' else 1
if p1 == 'paper':
return 2 if p2 == 'scissors' else 1
if p1 == 'scissors':
return 2 if p2 == 'rock' else 1
def rps():
computerchoice = random.choice(CHOICES.keys())
choice = raw_input("Rock, paper, or scissors?:").lower()
while choice not in CHOICES:
print "Check your spelling and try again."
choice = raw_input("Rock, paper, or scissors?:").lower()
print "The computer chose %s." % computerchoice
winner = win(choice, computerchoice)
if winner==0:
print "It's a draw!"
if winner==1:
print "Player wins, %s %s %s!" % (choice, CHOICES[choice], computerchoice)
if winner==2:
print "Computer wins, %s %s %s!" % (computerchoice, CHOICES[computerchoice], choice)
rps()
Now say you want to add lizard and spock. Just update CHOICES and the win() function. :)
Check theese lines out:
if choice != "paper":
if choice != "scissors":
print "Check your spelling and try again."
rps()
else:
pass #here you tell it to do nothing when you choose "scissors"
else:
pass #here you tell it to do nothing when you choose "paper"
I think you just need to re-sort your if/else statements :-)
The else section (containing the brains of your code) of the first if:
if choice != "rock":
if choice != "paper":
if choice != "scissors":
never runs if player doesn't select 'rock' i.e. 'paper', 'scissors' and any invalid input will ensure the else containing the important section of your code doesn't get executed.
you definitely don't need recursion for such a simple algorithm (calling rps() from rps())
you should try to implement it like this:
input == ""
while input != "quit":
input = raw_input(...)
if input not in ["r", "p", "s"]: continue
computer_choice = ...
if foo beats bar: print ...
if bar beats foo: print ...
Let's look at this.
if choice != "rock":
if choice != "paper":
if choice != "scissors":
print "Check your spelling and try again."
rps()
else:
pass
else:
pass
else:
# Do stuff...
You input scissors.
Does "scissors" != "rock"? Yes, so lets go further.
Does "scissors" != "paper"? Yes, so lets go further.
Does "scissors" != "scissors"? No, so let's look at the alternative else clause:
else:
pass
This code does nothing... Every other if/else clause is then broken out of after this... See the issue?
There are also a lot of simplifications you can do, for example you can make use of tables and lists more often instead of using so many if statements. For example (although the code remains largely untested):
import random
def convert_choice(choice):
choice_map = {"rock":0, "paper":1, "scissors":2}
return choice_map[choice]
def rock_paper_scissors():
choices = ["rock", "paper", "scissors"]
computer_choice = random.randint(0,2)
player_choice = raw_input("Rock, paper, or scissors? ")
raw_player_choice = convert_choice(player_choice) * 3
print "Copmuter played: " + choices[computer_choice]
print "You played: " + player_choice
win_states = {0:"tied", 3:"won", 6:"loss",
-1:"loss", 2:"tied", 5:"won",
-2:"won", 1:"loss", 4:"tied"}
print "You " + win_states[raw_player_choice - computer_choice]
def main():
rock_paper_scissors()
if __name__ == "__main__":
main()