Infinite Loop on Rock Paper Scissors Game in Python - 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...")

Related

Refining/condensing my python code for rock paper scissors (I just started learning)

### Import specification function required - for some reason if I do just "import random"
from random import randint
moves = ["rock", "paper", "scissors"]
### While pretty much is used so we can play over and over.
while True:
computer = moves[randint(0,2)]
player = input("Choose rock, paper or scissors, or 'end' to finish the game: ").lower()
### Break the loop if player wants to end
if player == "end":
print("The game is over")
break
### All possible iterations.
elif player == computer:
print("It's a tie!")
elif player == "rock":
if computer == "paper":
print("You lose!", computer, "beats", player)
else:
print("You win!", player, "beats", computer)
elif player == "paper":
if computer == "scissors":
print("You lose!", computer, "beats", player)
else:
print("You win!", player, "beats", computer)
elif player == "scissors":
if computer == "rock":
print("You lose!", computer, "beats", player)
else:
print("You win!", player, "beats", computer)
### This is to let the player know they typed in the wrong thing and re do it.
else:
print("Check your spelling and try again")
I made this code and have tried other ways to simplify but none of them seem to work as intended.
Any help refining/condensing the code with some explanations/guidance would be much appreciated.
This is my 3rd-day learning python so I'm not familiar with any of the more advanced python commands you may know.
You can eliminate most of your code and achieve the same result:
At its core, rock/paper/scissors is a 1/3 chance of each of win, loss, or tie. Therefore, requesting the user's input and then returning a randomly chosen outcome will give the same results.
import random as r
input("Enter rock, paper, or scissors")
print(r.choice(["You won!", "You lost!", "Tie!"]))
There isn't much here to be refined, really (and looks like something I'd make in Lua lol).
However, there are a few quality of life suggestions I can give:
player = input("...")
player = player.lower() # -- Strings in python act akin to arrays, and this changes all
# -- characters in the string lowercase
This way, if someone capitalizes in their response, it will still be recognized.
Beyond that, perhaps adding a simpler method to responding aswell:
elif player == "rock" or player == "r"
elif player == "paper" or player == "p"
elif player == "scissors" or player == "s"
However, that does add complexity, and I'm not sure if your looking to lower line count or complexity. (Probably both.) It's your choice.
(Maybe arrays could be used to make it very easy to add other moves, but I personally don't see the point there...)
You can create a function as follows to reduce code repetition in the win condition logic:
def is_win(player, computer):
if player == computer:
print('Tie')
elif player == 'rock' and computer == 'scissors' or
player == 'paper' and computer == 'rock' or
# Rest of win conditions here
print('Win')
else:
print('Lose')
Then invoke it like this:
is_win(player, computer)
There is another a bit advanced option to use class for Player and class for Computer and define methods for win for each one.

Rock, Paper And Scissors Program (Upper And Lower Case Problem)

I Was Practicing Programs Of Python And Then I Made This Rock, Paper, Scissors Program. And The Program Is Running Perfectly But The Problem Is Like This:
I Chose "Rock, Paper, Scissors" Like This Than It Runs.
But If I Enter Rock, Paper, Scissors In Any Other Way It Prints The Else Statment i.e., Invalid Choice.
I Want To Use Upper/Lower Case But How And Where.
import random
user = input("""Tell Me What Do You Choose:
~Rock
~Paper
~Scissors.
-> I Choose : """)
choose = ["Rock", "Paper", "Scissors"]
computer = random.choice(choose)
print(f"Computer Chose {computer}.")
#Function To Compare Choices
def compare(user, computer):
if user == computer:
return("It's A Tie :(....")
elif user == "Rock":
if computer == "Scissors":
return("User Wins!")
else:
return("Computer Wins!")
elif user == "Scissors":
if computer == "Paper":
return("User Wins!")
else:
return("Computer Wins!")
elif user == "Paper":
if computer == "Rock":
return("User Wins!")
else:
return("Computer Wins!")
else:
return("User Choose Out Of The Options!")
exit()
print(compare(user, computer))
just transform your input into lowercase with the lower() method
user = user.lower()
that makes sCiSsOrS into scissors
you also need to adjust your if statements to be all lowercase
elif user == "Rock": --> elif user == "rock":

Creating a while loop in Rock Paper Scissors game for Python

I am very new to programming and looking for some help with a homeowner assignment. The assignment is as follows:
Write a program using default python functions that lets the user play a game of Rock, Paper, Scissors against the computer. The program should work as follows:
When the program begins, a random number in the range of 1 through 3 is generated. If the number is 1, then the computer has chosen rock. If the number is 2, then the computer has chosen paper, if the number is 3, then computer has chosen scissors.
The user enters his or her choice of "rock", "paper" or "scissors" at the keyboard.
The computer's choice is displayed.
A winner is selected according to the following rules.
The game should end when either the computer or user has won a single round and continue when the result as a draw. Any help is greatly appreciated.
from random import randint
#create a list of play options
t = ["Rock", "Paper", "Scissors"]
#assign a random play to the computer
computer = t[randint(1,3)]
#set player to False
player = False
while player == False:
#set player to True
player = input("Rock, Paper, Scissors?")
if player == computer:
print("Tie!")
elif player == "Rock":
if computer == "Paper":
print("You lose!", computer, "covers", player)
else:
print("You win!", player, "smashes", computer)
elif player == "Paper":
if computer == "Scissors":
print("You lose!", computer, "cut", player)
else:
print("You win!", player, "covers", computer)
elif player == "Scissors":
if computer == "Rock":
print("You lose...", computer, "smashes", player)
else:
print("You win!", player, "cut", computer)
else:
print("That's not a valid play. Check your spelling!")
#player was set to True, but we want it to be False so the loop continues
player = False
computer = t[randint(1,3)]
First problem is that you are making a wrong choice for the computer. The lists in Python, as arrays in vast majority of programming languages, start from 0. In your case you are generating a number in range 1 to 3, which is it will never get the first element of t and will fail when the number is 3, as the list ends with 2.
For that part you can generate a number from 0 to 2, or use choice() method from the random module. Please note that you need to import it first.
Also, I'd rather use while True with some breaks rather than the old fashioned state variable.
Here is the working version of your code, made same refactoring:
from random import choice
#create a list of play options
t = ["Rock", "Paper", "Scissors"]
while True:
computer = choice(t)
player = input("Rock, Paper, Scissors?")
if player == computer:
print("Tie!")
elif player == "Rock":
if computer == "Paper":
print("You lose!", computer, "covers", player)
else:
print("You win!", player, "smashes", computer)
break
elif player == "Paper":
if computer == "Scissors":
print("You lose!", computer, "cut", player)
else:
print("You win!", player, "covers", computer)
break
elif player == "Scissors":
if computer == "Rock":
print("You lose...", computer, "smashes", player)
else:
print("You win!", player, "cut", computer)
break
else:
print("That's not a valid play. Check your spelling!")

How to get different results from a random.choice in a nested while loop

This is a rock, paper scissors program minigame, however the random.choice selects only one from the list even though it repeats the choice in a nested loop.
I've tried looking at other answers but most of them state about using a loop, the others aren't adequate enough for my case.
rpsloop = True
while rpsloop:
#credit to https://thehelloworldprogram.com/python/python-game-rock-paper-scissors/ for help
aiselc = ["rock","paper","scissors"]
computer = random.choice(aiselc)
print("type exit to leave")
player = input("rock, paper, scissors?")
if player == computer:
print("Tie!")
print("-------------------------")
continue
elif player == "rock":
if computer == "paper":
print("You lose!", computer, "covers", player)
print("-------------------------")
continue
else:
print("You win!", player, "smashes", computer)
print("-------------------------")
continue
elif player == "Paper":
if computer == "Scissors":
print("You lose!", computer, "cut", player)
print("-------------------------")
continue
else:
print("You win!", player, "covers", computer)
continue
elif player == "Scissors":
if computer == "Rock":
print("You lose...", computer, "smashes", player)
print("-------------------------")
continue
else:
print("You win!", player, "cut", computer)
print("-------------------------")
continue
else:
break
else:
break
I expect the computer to pick either rock, paper or scissors.
it picks one and keeps the value even after a loop.
however it picks another value each execution.
Remember that using == in Python when comparing strings does an exact comparison. This means that the case of the letters is taken into account when comparing strings. For example, Scissors and scissors would be considered not equal to each other.
I highly suspect that you are putting in all of your choices in lowercase. This means that if you were to enter scissors or paper, your if statements for checking if the player entered Scissors would not execute. What will end up happening is that your loop will exit as what you put in is not handled by any of the other if statements due to the case-sensitive nature of the string comparison. This is why rock only executes and none of the other if statements do.
Specifically, take note that in your if statements, rock is lowercase, but Scissors and Paper have their first letters capitalized.
Therefore, given this implementation change your if statements so that the strings are in fact lowercase.
elif player == "paper":
if computer == "scissors":
...
...
elif player == "scissors":
if computer == "rock":
...
...

Rock paper scissors AI issue

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.

Categories