Rock paper scissors AI issue - python

I'm building a simple rock paper scissors game. It works fine, except for the fact that the game won't stop when comp_count reaches 3. I can't seem to understand why, since it works fine for player_count. Help me out please!
from random import randint
player_count = 0
comp_count = 0
def game():
player_choice = raw_input('Do you choose rock [r], paper [p], or scissors [s]? ')
computer_choice = randint(0,2)
#Rock = 0 Paper = 1 Scissors = 2
#Player chooses paper, computer chooses rock
if player_choice == "p" and computer_choice == 0:
print 'Computer chose rock'
player_won()
#Player chooses rock, computer chooses scissors
elif player_choice == 'r' and computer_choice == 2:
print 'Computer chose scissors'
player_won()
#Player chooses scissors, computer chooses paper
elif player_choice == 's' and computer_choice == 1:
print 'Computer chose paper'
player_won()
#Computer chooses paper, player chooses rock
elif player_choice == 'r' and computer_choice == 1:
print 'Computer chose paper'
computer_won()
#Computer chooses rock, player chooses scissors
elif player_choice == 's' and computer_choice == 0:
print 'Computer chose rock'
computer_won()
#Computer chooses scissors, player chooses paper
elif player_choice == 'p' and computer_choice == 2:
print 'Computer chose scissors'
computer_won()
#Ties
elif player_choice == 'r' and computer_choice == 0:
print "It's a tie!"
game()
elif player_choice == 's' and computer_choice == 2:
print "It's a tie!"
game()
elif player_choice == 'p' and computer_choice == 1:
print "It's a tie!"
game()
#Wrong input
else:
print 'Please try again.'
game()
def player_won():
global player_count
print 'You win!'
player_count += 1
print 'You have ' + str(player_count) + ' point(s).'
while player_count < 3:
game()
def computer_won():
global comp_count
print 'Computer wins!'
comp_count += 1
print 'Computer has ' + str(comp_count) + ' point(s).'
while comp_count < 3:
game()
print 'Welcome to Rock, Paper, Scissors! First to 3 points wins it all.'
game()

Your while loops are whats causing your problem. Simply change while to a if in your player_won and computer_won functions and it fixes the issue.
def player_won():
global player_count
print 'You win!'
player_count += 1
print 'You have ' + str(player_count) + ' point(s).'
if player_count < 3:
game()
def computer_won():
global comp_count
print 'Computer wins!'
comp_count += 1
print 'Computer has ' + str(comp_count) + ' point(s).'
if comp_count < 3:
game()
Now go rock paper scissors your heart out!

I admit this isn't really a direct answer to your question, but I feel it might be useful to have a potentially simpler way to write this brought up.
You could make the user choose from three different numbers in the input instead of letters, or just convert the letters to numbers. One advantage of this is that to test for a tie, you could simply write:
if player_choice == computer_choice:
Even checking for who won in a game if it wasn't a tie wouldn't be very difficult, since if it is all numeric, an option that beats another one will be one away from it in a certain direction. So, for example, you could test if the player won like so:
winning = computer_choice - 1
if winning == -1: winning = 2
if player_choice == wining:
player_won()
else: #assuming we have already checked if it is a tie, we can say that otherwise the computer won.
computer_won()
If each number represented a different option (for example if you had a dictionary linking 0 to rock, 1 to scissors, and 2 to paper), then this would check if the user chose the option before the computer's, which would be the winning option.
That would actually let you check for who won and with which options with relatively few if statements. Your check could look something like this:
options = {0: "rock", 1:"scissors", 2:"paper"}
#collect player and computer choice here
print "computer chose "+options[computer_choice] #We will probably tell them what the computer chose no matter what the outcome, so might as well just put it once up here now that a variable can determine what the computer chose.
if player_choice == computer_choice:
print "It's a tie!"
game()
winning = computer_choice - 1
if winning == -1: winning = 2
if player_choice == wining:
player_won()
else: #assuming we have already checked if it is a tie, we can say that otherwise the computer won.
computer_won()
This isn't really necessary for making your code work, but I think it will be useful if you are interested.

Related

Infinite Loop on Rock Paper Scissors Game in Python

I have been assigned of developing a Rock Paper Scissors game in Python with some modifications. However, I am quite new to programming, and I do not know how to go about in infinite looping the program unless if the user inputs 'q'. I have a general idea of that I have to use a while loop, however I cannot figure out where to put it.
Attached here is the code that the rock paper scissors game works regularly without trying to infinitely loop and breaking the loop in the program. I have tried to mess around with the indentation of the code after the while loop and had varying results, most of which just broke the program.
import random
def play():
user_option = input("'r for rock:', 'p for paper:', or 's for scissors: or q to quit':")
cpu = random.choice(['r', 's', 'p'])
#while user_option != 'y':
if user_option == cpu:
return("You tie!")
if win(user_option, cpu):
return("You won!")
return "You lost!"
def win(player, computerOpponent):
if (player == 'r' and computerOpponent == 's') or (player == 's' and computerOpponent == 'p') or (player == 'p' and computerOpponent == 'r'):
return True
print(play())
If you want to make the game automatically start a new round without asking the players if they want to play again, you can remove the part of the code that asks for player input and simply have the game loop back to the beginning after each round. Here's one way to do that:
while True:
# Get player input
player1 = input("Player 1, make your move (rock, paper, scissors): ")
player2 = input("Player 2, make your move (rock, paper, scissors): ")
# Determine the winner
if player1 == player2:
print("It's a tie!")
elif player1 == "rock" and player2 == "scissors":
print("Player 1 wins!")
elif player1 == "paper" and player2 == "rock":
print("Player 1 wins!")
elif player1 == "scissors" and player2 == "paper":
print("Player 1 wins!")
else:
print("Player 2 wins!")
# Start a new round automatically
print("Starting a new round...")

Python Rock Paper Scissors List Choices

Instructions: Write a program to allow the user to play Rock, Paper, Scissors against the computer. The program will be menu driven (see details below). The user can continue to play the game over and over by choosing to play the game in the menu. A game consists of a single battle: win, lose, or tie. For a single battle the user makes their move and then the computer move is displayed followed by a description of who won that battle. Do not break a tie.
Once the user chooses to quit, the program then displays the win/loss/tie record for all the games just played
The user will enter the details in the following order during gameplay:
Menu choice (1 integer, 1 to play a game, 2 to quit)
Player's move (1 string, 'Rock', 'Paper', or 'Scissors')
My problem is that I'm not sure how to make the computer choose from my list and accept it. I keep getting this...1
import random
def main():
"""
Runs a game of Rock, Paper, Scissors. Asks the user for input and plays against the computer.
"""
#print display message
print('Lets play Rock, Paper, Scissors!')
moves_list = ['Rock', 'Paper', 'Scissors']
#a place to keep track of scores
tied = 0
computer = 0
player = 0
#create a variable to control loop
play_again = 1
comp_choice = process_comp()
player_choice = process_player()
winner = determine_winner(player_choice, comp_choice)
#while loop for multiple games
while play_again == 1:
comp_choice = process_comp()
player_choice = process_player()
if comp_choice == 'Rock' or comp_choice == 'rock':
print('Computer chooses rock.')
elif comp_choice == 'Paper' or comp_choice == 'paper':
print('Computer chooses paper.')
else:
print('Computer chooses scissors.')
#call the determine winner function
winner = determine_winner(player_choice, comp_choice)
#check who won the game and add 1 to the correct winner
if winner == 'computer':
computer += 1
elif winner == 'player':
player += 1
else:
tied += 1
#ask user if they want to play again
play_again = input('Would you like to play again? (Enter 1 for yes, 2 for no): ')
#display number of games that were won
print()
print('There were', tied, 'tied games.')
print('The player won', player, 'games.')
print('The computer won', computer,'games.')
#define the computer process function
def process_comp():
#make computer choose a move from list
choosen = random.choice(moves_list)
return choosen
#make sure user enters correct option.
def process_player():
player_choice = int(input('Rock, Paper, Scissors? (Enter 2 if you want to quit):'))
#if the player enters 2, quit the game
if player_choice == 2:
print('Thank you for playing!')
play_again = 2
#check if user is inputting correct selections
while player_choice != 'Rock' or player_choice != 'rock' and player_choice != 'Paper' or player_choice != 'paper' and player_choice != 'Scissors' or player_choice != 'scissors' and player_choice != 2:
print('Error! Please enter an option that was given.')
player_choice = int(input('Rock, Paper, Scissors? (Enter 2 if you want to quit):'))
return player_choice
#define the determine winner function.
def determine_winner(player_choice, comp_choice):
#setup computer selections
if comp_choice == 'Rock' or comp_choice == 'rock':
if player_choice == 'Paper' or player_choice == 'paper':
print('You win!')
winner = 'player'
elif player_choice == 'Scissors' or player_choice == 'scissors':
print('The computer wins!')
winner = 'computer'
else:
print('The game is tied. Try again.')
winner = 'tied'
if comp_choice == 'Paper' or comp_choice == 'paper':
if player_choice == 'Rock' or player_choice == 'rock':
print('The computer wins!')
winner = 'computer'
elif player_choice == 'Scissors' or player_choice == 'scissors':
print('You win!')
winner = 'player'
else:
print('The game is tied. Try again.')
winner = 'tied'
if comp_choice == 'Scissors' or comp_choice == 'scissors':
if player_choice == 'Rock' or player_choice == 'rock':
print('You win!')
winner = 'player'
elif player_choice == 'Paper' or player_choice == 'player':
print('The computer wins!')
winner = 'computer'
else:
print('The game is tied. Try again.')
winner = 'tied'
return winner
main()
You are trying to translate a string, e.g. rock into an integer (number). This is not possible as Python has no way of knowing the integer you wish to translate it into. Instead you could change your process_player() to the following. I simplified your while statement, and removed the translation to int - Then you check for whether player_choice is equal to the string '2' instead of the integer version, and it should work
def process_player():
player_choice = input('Rock, Paper, Scissors? (Enter 2 if you want to quit):')
# if the player enters 2, quit the game
if player_choice == '2':
print('Thank you for playing!')
# check if user is inputting correct selections
while player_choice.lower() not in ['rock', 'paper', 'scissors', '2']:
print('Error! Please enter an option that was given.')
player_choice = input('Rock, Paper, Scissors? (Enter 2 if you want to quit):')
return player_choice

Need code to let user make repeated attempts

I am new to coding so I am trying to create a Rock Paper Scissors Game. I have almost completed the game, but when the user and computer input the same number, I want the program to repeat until either one of the player wins. How can I do this? Any help is appreciated. Here is my code.
game = input("Want to play Rock Paper Scissors? (Y/N) ")
if game == "Y":
print("1 = Rock, 2 = Paper, 3 = Scissors")
print('')
user = int(input("You have one chance of beating me. Input a number. "))
print('')
import random
computer = random.randint(1,3)
if user == 1 and computer == 1:
print("Must play again! We both played Rock!")
elif user == 1 and computer == 2:
print("You lose! You played Rock and I played Paper!")
elif user == 1 and computer == 3:
print("You win! You played Rock and I played Scissors!")
elif user == 2 and computer == 1:
print("You win! You played Paper and I played Rock!")
elif user == 2 and computer == 2:
print("Must play again! We both played Paper!")
elif user == 2 and computer == 3:
print("You lose! You played Paper and I played Scissors!")
elif user == 3 and computer == 1:
print("You lose! You played Scissors and I played Rock!")
elif user == 3 and computer == 2:
print("You win! You played Scissors and I played Paper!")
elif user == 3 and computer == 3:
print("Must play again! We both played Scissors!")
else:
print("Not a number.")
else:
print("Fine. Bye.")
You could put the whole if-elif-block in a while-loop that will repeat until you have a winner. In order to determine if there is a winner, use a boolean variable.
winner = False
while not winner:
if ...... ## Your if-elif-block
elif user == 1 and computer == 2:
print("You lose! You played Rock and I played Paper!")
winner = True
## Your remaining if-elif-block
You only put the command winner=True in the command blocks of the conditions that have a winner. So, the loop will continue until you hit one of these conditions.
You could also choose to use a more advanced winner variable (0 for draw, 1 for player, 2 for computer) to use the value in a goodbye-message.
One way would be to use a while loop, breaking when a condition is satisfied.
while True:
if (condition):
print("")
break
...
The while statement repeats the loop until one of the conditions is satisfied. The break statement causes the program to exit the loop and move on to the next executable statement.
(to learn more google anything in quotes :)
using a "while loop" to create a "game loop". I learned this trick from making small games in python. Also, you want to learn to use "classes" as the logic and the code can be improved using "OOP concepts".T code has been tested and works.
import random
#Create a "function" that meets the requirements of a "game loop"
def gameloop():
game = input("Want to play Rock Paper Scissors? (Y/N) ")
if game == "Y":
#Create a "while loop" to host the logic of the game.
#Each If statement will enable one "rule" of the game logic.
#game logic could be redesigned as an "Event".
#You can add a game "Event System" to your future project backlog
winner = False
while not winner:
print("1 = Rock, 2 = Paper, 3 = Scissors")
print('')
user = int(
input("You have one chance of beating me. Input a number. "))
print('')
computer = random.randint(1, 3)
if user == 1 and computer == 2:
print("You lose! You played Rock and I played Paper!")
winner = True
elif user == 1 and computer == 3:
print("You win! You played Rock and I played Scissors!")
winner = True
elif user == 2 and computer == 1:
print("You win! You played Paper and I played Rock!")
winner = True
elif user == 2 and computer == 3:
print("You lose! You played Paper and I played Scissors!")
winner = True
elif user == 3 and computer == 1:
print("You lose! You played Scissors and I played Rock!")
winner = True
elif user == 3 and computer == 2:
print("You win! You played Scissors and I played Paper!")
winner = True
elif user == 1 and computer == 1:
print("Must play again! We both played Rock!")
elif user == 2 and computer == 2:
print("Must play again! We both played Paper!")
elif user == 3 and computer == 3:
print("Must play again! We both played Scissors!")
else:
print("Not a number.")
else:
print("game....over?")
gameloop()
I took the time to do an OOP Class example too! it could be optimized in many ways. However, I hope it shows you the next level of study! I also hope it helps you look into all the crazy design patterns and Game Programming Techniques you can apply as you learn.
import random
# we can create a player class to be used as an "interface" as we design the games logic
# this will let us scale the features be build in our game
# in this case i will leave it to you to add Wins to the scoreboard to help you learn
class player:
# your games requerment wants your players to make a choice from 1-3
choice = 0
# your games may requerment a player to be defined as the winner
win = 0
# your games may requerment a player to be defined as the losser
loss = 0
class game:
# by using classes and OOP we can scale the data and logic of your game
# here we create instances of the class player and define new objects based on your "requerments"
# your "requerments" where to have one Computer as a player, and one user as a player
computer = player()
user = player()
# this "function" will create a Scoreboard feature that can be called in the 'game loop' or in a future "event" of the game.
# Like a "Game Stats stage" at the end of the game
def Scoreboard(self, computer, user):
Computer = computer.loss
User = user.loss
print("+============= FINAL RESULTS: SCOREBOARD!! ======+ ")
print(" ")
print("Computer losses: ", Computer)
print("Player losses: ", User)
print(" ")
# Create a "function" that meets the requirements of a "game loop"
def main_loop(self, computer, user):
gameinput = input("Want to play Rock Paper Scissors? (Y/N) ")
if gameinput == "Y":
# Create a "while loop" to host the logic of the game.
# Each If statement will enable one "rule" of the game logic.
# game logic could be redesigned as an "Event".
# You can add a game "Event System" to your future project backlog
winner = False
while not winner:
print("1 = Rock, 2 = Paper, 3 = Scissors")
print('')
# we create 'Player1' as the user
Player1 = user
# we change the 'Player1' 'choice' to the user input
Player1.choice = int(
input("You have one chance of beating me. Input a number. "))
print('')
# we pull in to the game the computer player and call them 'Player1'
Player2 = computer
# we change the 'Player2' 'choice' to a random number
Player2.choice = random.randint(1, 3)
if user.choice == 1 and computer.choice == 2:
print("You lose! You played Rock and I played Paper!")
winner = True
user.loss += 1
elif user.choice == 1 and computer.choice == 3:
print("You win! You played Rock and I played Scissors!")
winner = True
computer.loss += 1
elif user.choice == 2 and computer.choice == 1:
print("You win! You played Paper and I played Rock!")
winner = True
computer.loss += 1
elif user.choice == 2 and computer.choice == 3:
print("You lose! You played Paper and I played Scissors!")
winner = True
user.loss += 1
elif user.choice == 3 and computer.choice == 1:
print("You lose! You played Scissors and I played Rock!")
winner = True
user.loss += 1
elif user.choice == 3 and computer.choice == 2:
print("You win! You played Scissors and I played Paper!")
winner = True
computer.loss += 1
elif user.choice == 1 and computer.choice == 1:
print("Must play again! We both played Rock!")
elif user.choice == 2 and computer.choice == 2:
print("Must play again! We both played Paper!")
elif user.choice == 3 and computer.choice == 3:
print("Must play again! We both played Scissors!")
else:
print("Not a number.")
# by returning "self" you call the same 'instances' of game that you will define below
return self.Scoreboard(user, computer)
else:
print("game....over?")
# define Instance of game as "test_game"
test_game = game()
# run game loop
test_game.main_loop()

Rock Paper Scissors Not Printing Out Results

I am trying to create a Rock Paper Scissors program against a computer but running into some issues.
I have made two methods, one for the computer's choice and the user's choice. For the computer, it randomly generates 0,1,2 and selects rock, paper or scissors from an array which I declared as a local variable, rps. When I try to run the game with the game_play() method, I am able to enter in input but don't get an output of the result between the player and the computer.
class RockPaperScissors():
global rps
rps = ['rock', 'paper','scissors']
def computer_choice(self): #computer randomly picks rock paper or scissors
x = random.randint(0,2)
w = rps[x]
return w
#print(rps[x])
def player_choice(self): #does the player choose rock paper or scissors
x = True
while x:
choice = (input("Player- would you like rock, paper, or scissors? enter rock,paper, or scissors?: "))
if choice.lower() == 'rock':
return 'rock'
elif choice.lower() == 'paper':
return 'paper'
elif choice.lower() == 'scissors':
return 'scissors'
else:
("please enter in rock, paper or scissors")
def game_play(self):
rock = RockPaperScissors()
user = rock.player_choice()
comp= rock.computer_choice()
if comp == 'rock' and user == 'paper':
return "the player wins!"
elif comp == 'rock' and user == 'scissors':
return "the computer wins!"
elif comp == 'paper' and user == 'rock':
return "the computer wins!"
elif comp == 'paper' and user == 'scissors':
return "the player wins!"
elif comp == 'scissors' and user == 'paper':
return"the computer wins!"
elif comp == 'scissors' and user == 'rock':
return "the player wins"
I am trying to test it this way:
rock = RockPaperScissors()
rock.game_play()
If you are running it as a script instead of everything in the Python interpreter. You must explicitly print the value.
One possible solution is:
rock = RockPaperScissors()
print(rock.game_play())
Directly answering your question: you are not "printing" the game, which would be...
print(rock.game_play())
However, there's some other improvements I would do.
Avoid global variables so that you can provide greater clarity to
the code. Maybe it's a better idea to define rps inside the function
computer_choice() instead of having it as a global variable.
You can simplify player_choice() as:
x = input("Player- would you like rock, paper, or scissors? enter rock,paper, or scissors?: ").lower()
while x != 'rock' and x != 'paper' and x != 'scissors':
choice = (input("Player- would you like rock, paper, or scissors? enter rock, paper, or scissors?: "))
x = input("please enter in rock, paper or scissors").lower()
return x
Possibly, your code wasn't copied correctly, but everything below the first line (class RockPaperScissors:) is missing one indent.
Finally, another possible solution is to print the game's result inside function game_play() instead of returning a string.
Good luck and keep learning.

I am working on a rock, paper, scissors program using functions and it is always returning else cases

I am looking for some input on a rock, paper, scissors program that I am making where the statements in the main() and determineWinner that use playerChoice always terminate in the else: case. Each trial will output the player chooses scissors and that the game is tied. I am not sure where I went wrong here as I've printed the input to confirm it is correct before sending to it to the other functions. I cannot figure what pare of the above to function is causing the problem, if anyone could point me in the right direction here I would be grateful.
Here is the code I have so far:
import random
# define main function
def main():
# initialize playAgain to start game, set stats to 0
playAgain = 'y'
numberTied = 0
numberPlayerWon = 0
numberComputerWon = 0
print("Let's play a game of rock, paper, scissors.")
# loop back to play again if user confirms
while playAgain == 'y' or playAgain == 'Y':
computerChoice = processComputerChoice()
playerChoice = processPlayerChoice()
# display computer choice
if computerChoice == 1:
print('The computer chooses rock.')
elif computerChoice == 2:
print('The computer chooses paper.')
else:
print('The computer chooses scissors.')
# display player choice
if playerChoice == 1:
print('You choose rock.')
elif playerChoice == 2:
print('You choose paper.')
else:
print ('You choose scissors.')
# assign who won to result and add total wins/ties to accumulator
result = determineWinner(playerChoice, computerChoice)
if result == 'computer':
numberComputerWon += 1
elif result == 'player':
numberPlayerWon += 1
else:
numberTied += 1
# ask player if they would like to play again
print('')
print
playAgain = input('Do you want to play again? (Enter y or Y to start another game)')
print('')
else:
# print accumulated wins and ties for computer and player
print('There were', numberTied, 'tie games played.')
print('The computer won', numberComputerWon, 'game(s).')
print('The player won', numberPlayerWon, 'game(s).')
print('')
# define computer choice function
def processComputerChoice():
# randomly select an option for the computer to play
randomNumber = random.randint(1,3)
print(randomNumber)
return randomNumber
# define player choice function
def processPlayerChoice():
choice = int(input(('What is your choice? Enter 1 for rock, 2 for paper, or 3 for scissors. ')))
print (choice)
# throw error if player makes invalid choice
while choice != 1 and choice != 2 and choice != 3:
print('ERROR: please input a valid choice of 1, 2, or 3')
choice = int(input('Please enter a correct choice: '))
return choice
# definition for the function to determine the winner
def determineWinner(playerChoice, computerChoice):
# determine player choice and compare to computer choice to determine the winner
if computerChoice == 1:
if playerChoice == 2:
print('Paper covers rock. You are victorious!')
winner = 'player'
elif playerChoice == 3:
print('Rock bashes scissors. The computer is victorious!')
winner = 'computer'
else:
print('The game is tied. Try again 1')
winner = 'tied'
if computerChoice == 2:
if playerChoice == 1:
print('Paper covers rock. The computer is victorious!')
winner = 'computer'
elif playerChoice == 3:
print('Scissors slice paper. You are victorious!')
winner = 'player'
else:
print('The game is tied. Try again 2')
winner = 'tied'
if computerChoice == 3:
if playerChoice == 1:
print('Rock bashes scissors. You are victorious!')
winner = 'player'
elif playerChoice == 2:
print('Scissors slice paper. The computer is victorious!')
winner = 'computer'
else:
print('The game is tied. Try again 3')
winner = 'tied'
return winner
main()
input("Press Enter to continue")
The return statement of your function processPlayerChoice has incorrect indentation. It should be out of while loop (unindent it one level)
At the moment, if player enters correct choice your function will return None.
If user enters incorrect choice, it will enter the while loop and will return whatever the second input from user is.
def processPlayerChoice():
choice = int(input(('What is your choice? Enter 1 for rock, 2 for paper, or 3 for scissors. ')))
print (choice)
# throw error if player makes invalid choice
while choice != 1 and choice != 2 and choice != 3:
print('ERROR: please input a valid choice of 1, 2, or 3')
choice = int(input('Please enter a correct choice: '))
return choice
Make sure to align your return statements with the function body. Currently in both processPlayerChoice and determineWinner they are aligned with the conditional loops, and thus will not be reached every time.

Categories