How to execute multiple while loops? - python

I was wondering if someone could tell me how to have the computer choose a new choice after every round. I got the lower portion of the code to cover all choices but it turns out my code runs where the computer uses the same choice every time. Is there a way to set my code so the computer chooses something new from the list. Thanks!
import random
def computerChoice():
gameList = ["Rock", "Paper", "Scissors"]
computerChoice = random.choice(gameList)
print(computerChoice)
def userChoice(computerChoice):
userScore = 0
computerScore = 0
rounds = 0
print("Welcome to Rock, Paper, Scissors. You are playing against the computer on best out of three game, winner takes all! Have Fun!")
while userScore < 2 and computerScore < 2:
userAnswer = input("Please choose Rock, Paper, or Scissors: ")
if userAnswer == "Rock" and computerChoice != "Paper":
userScore += 1
rounds += 1
print("The Computer Loses and You Win the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Paper" and computerChoice != "Scissors":
userScore += 1
rounds += 1
print("The Computer Loses and You Win the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Scissors" and computerChoice != "Rock":
userScore += 1
rounds += 1
print("The Computer Loses and You Win the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Rock" and computerChoice == "Paper":
computerScore += 1
rounds += 1
print("The Computer Wins and You Lose the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Paper" and computerChoice == "Scissors":
computerScore += 1
rounds += 1
print("The Computer Wins and You Lose the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Scissors" and computerChoice == "Rock":
computerScore += 1
rounds += 1
print("The Computer Wins and You Lose the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Rock" and computerChoice == "Rock":
print("This round is a PUSH!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Scissors" and computerChoice == "Scissors":
print("This round is a PUSH!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Paper" and computerChoice == "Paper":
print("This round is a PUSH!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
else:
print("Whatever you just inputed doesn't work noodlehead, try again!")
continue
x = computerChoice()
print(userChoice(x))

Move this inside your while loop:
computerChoice = random.choice(gameList)
Currently you are saving a single choice, and then using it every time. Where as this would create a new choice each time:
while userScore < 2 and computerScore < 2:
userAnswer = input("Please choose Rock, Paper, or Scissors: ")
computerChoice = random.choice(gameList)
# Compare to see who won.
Note that gameList must be available inside that scope, so you will have to either pass it in as a function parameter or include it inside the function. That does change the nature of the function somewhat:
def game():
print("Welcome to Rock, Paper, Scissors. You are playing against the computer on best out of three game, winner takes all! Have Fun!")
userScore, computerScore, rounds = game_loop()
def game_loop(available_options: list=["Rock", "Paper", "Scissors"]):
computerScore = 0
userScore = 0
rounds = 0
while userScore < 2 and computerScore < 2:
userAnswer = input("Please choose Rock, Paper, or Scissors: ")
computerChoice = random.choice(available_options)
// compare and score (preferably in their own functions)
return userScore, computerScore, rounds

try this
import random
def computerChoice():
gameList = ["Rock", "Paper", "Scissors"]
return random.choice(gameList)
def userChoice(computerChoice):
userScore = 0
computerScore = 0
rounds = 0
print("Welcome to Rock, Paper, Scissors. You are playing against the computer on best out of three game, winner takes all! Have Fun!")
while userScore < 2 and computerScore < 2:
userAnswer = input("Please choose Rock, Paper, or Scissors: ")
#all your if statements and stuff
computerChoice = computerChoice()
print(userChoice(computerChoice()))

Related

How to keep score for player and computer?

This is a rock,paper,scissors game.
import random
options = ("rock", "paper", "scissors") # three options
running = True
score = 0
while running: # continuing the game
player = "" # storing the player's choices
computer = random.choice(options) # computer will choose a random choice from the options
while player not in options: # the player has to choose one of the options, if not, it will still keep on looping
player = input("Enter a choice (rock, paper, scissors): ")
print("Player: " + player) # player(user) vs. computer
print("Computer: " + computer)
if player == computer:
score = 0
print("It's a tie!")
elif player == "rock" and computer == "scissors":
score += 1
print("You win!")
elif player == "paper" and computer == "rock":
score += 1
print("You win!")
elif player == "scissors" and computer == "paper":
score += 1
print("You win!")
else:
score += 1
print("You lose!")
print(score, "for computer")
print(score)
play_again = input("Play again? (y/n): ").lower()
if play_again == "y":
running = True
print("Yes sir!")
else:
running = False
print("Thanks for playing! ")
My goal was trying to keep score for player and computer. If the user wins, they get a point. If the computer wins, they get a point. If its a tie, neither of them gets a point.
The following code shows you three rounds of three games of a simulated user input game with its result. It is your code only slightly changed to count properly the results:
import random
lst_user_input = [
"list faking user input:"
,"scissors"
,"paper"
,"rock"
,"y"
,"scissors"
,"paper"
,"rock"
,"y"
,"scissors"
,"paper"
,"rock"
,"n"
]
options = ("rock", "paper", "scissors") # three options
running = True
computer_score = 0
player_score = 0
round_no = 0
while running: # continuing the game
#player = "" # storing the player's choices
round_no += 1
computer = random.choice(options) # computer will choose a random choice from the options
#while player not in options: # the player has to choose one of the options, if not, it will still keep on looping
# player = input("Enter a choice (rock, paper, scissors): ")
print(round_no)
player = lst_user_input[round_no]
print("Player : " + player) # player(user) vs. computer
print("Computer: " + computer)
if player == computer:
print("It's a tie!")
elif player == "rock" and computer == "scissors":
player_score += 1
print("You win!")
elif player == "paper" and computer == "rock":
player_score += 1
print("You win!")
elif player == "scissors" and computer == "paper":
player_score += 1
print("You win!")
else:
computer_score += 1
print("You lose!")
print("Player score:", player_score)
print("Computer score:", computer_score)
if not round_no % 3: # ask only each 3 rounds
#play_again = input("Play next 3-rounds? (y/n): ").lower()
round_no +=1
play_again = lst_user_input[round_no]
if play_again == "y":
running = True
print("Yes sir!")
else:
running = False
print("Thanks for playing! ")
Here an example of printed output:
1
Player : scissors
Computer: paper
You win!
Player score: 1
Computer score: 0
2
Player : paper
Computer: scissors
You lose!
Player score: 1
Computer score: 1
3
Player : rock
Computer: paper
You lose!
Player score: 1
Computer score: 2
Yes sir!
5
Player : scissors
Computer: paper
You win!
Player score: 2
Computer score: 2
6
Player : paper
Computer: rock
You win!
Player score: 3
Computer score: 2
Thanks for playing!

my rock paper scissors gives me nothing in output (python)

I am new to python and as a practice I'm trying to write a rock paper scissors with it.
I triple checked eth but i can't find the problem.
I'm using visual studio code console. the msvcrt is for "getch" and I'm not sure about about the random function syntax
problem: when you give it the input number, It doesn't do or write anything despite the program.
help me pleaaaaase.
import random
import msvcrt
##################################################
player_move = " "
system_move = " "
##################################################
def rand(system_move):
rn = random.randint(1, 3)
if rn == 1:
system_move = "Rock"
elif rn == 2:
system_move = "Paper"
elif rn == 3:
system_move = "Scissors"
else:
rand()
return system_move
##################################################
print("!!! Rock, Paper, Scissors !!!\n\n\n")
###################################################
def playermove(player_move):
print("What do you want to go with?\n1-Rock\n2-paper\n3-scissors\n")
temp = msvcrt.getch()
if temp == '1' or 1:
player_move = 'Rock'
elif temp == '2' or 2:
player_move = 'Paper'
elif temp == '3' or 3:
player_move = 'Scissors'
else:
print(f"invalid input {player_move}. Try again\n")
playermove()
return player_move
###################################################
pm = ' '
sm = ' '
rand(sm)
playermove(pm)
if pm== 'Scissors':
if sm == "Scissors":
print(f"System move: {sm}\nIt's a tie!\n")
elif sm == "Rock":
print(f"System move: {sm}\nSystem won!\n")
elif sm == "Paper":
print(f"System move: {sm}\nYou won!\n")
else:
print("Oops! Something went wrong.\n")
elif pm == "Paper":
if sm == "Scissors":
print(f"System move: {sm}\nSystem won!\n")
elif sm == "Rock":
print(f"System move: {sm}\nYou won!\n")
elif sm == "Paper":
print(f"System move: {sm}\nIt's a tie!\n")
else:
print("Oops! Something went wrong.\n")
elif pm == "Rock":
if sm == "Scissors":
print(f"System move: {sm}\nYou won!\n")
elif sm == "Rock":
print(f"System move: {sm}\nIt's a tie!\n")
elif sm == "Paper":
print(f"System move: {sm}\nSystem won!\n")
else:
print("Oops! Something went wrong.\n")
print("Press any key to exit...")
xyz = msvcrt.getch()
Well, the reason your code doesn't work is because you are not assigning the return value of your functions to any variable. To fix your code you need to do the following:
sm = rand(sm)
pm = playermove(pm)
In Python, passing an immutable object like string means that you cannot make any changes to it. As you're not using the passed value, your function's signature should actually look like this.
def rand()
def playermove()
After you do this, you'll see there are other things you need to fix in your code.
Try this code. Just replace snake, water, gun by rock, paper, scissors.
print(" \t\t\t Welecome to Snake , Water , Gun game\n\n")
import random
attempts= 1
your_point=0
computer_point=0
while (attempts<=10):
lst=["snake","water","gun"]
ran=random.choice(lst)
print("what do you choose snake, water or gun")
inp=input()
if inp==ran:
print("tie")
print(f"you choosed {inp} and computer guess is {ran}")
print("No body gets point\n")
elif inp=="snake" and ran=="water":
your_point=your_point+1
print(f"you choosed {inp} and computer guess is {ran}")
print("The snake drank water\n")
print("You won this round")
print("you get 1 point\n")
elif inp=="water" and ran=="snake":
computer_point = computer_point + 1
print(f"you choosed {inp} and computer guess is {ran}")
print("The snake drank water\n")
print("You Lost this round")
print("computer gets 1 point\n")
elif inp=="water" and ran=="gun":
print(f"you choosed {inp} and computer guess is {ran}")
your_point = your_point + 1
print("The gun sank in water\n")
print("You won this round")
print("you get 1 point\n")
elif inp == "gun" and ran == "water":
print(f"you choosed {inp} and computer guess is {ran}")
computer_point = computer_point + 1
print("The gun sank in water\n")
print("You Lost this round")
print("computer gets 1 point\n")
elif inp == "gun" and ran == "snake":
print(f"you choosed {inp} and computer guess is {ran}")
your_point = your_point + 1
print("The snake was shoot and he died\n")
print("You Won this round")
print("you get 1 point\n")
elif inp == "snake" and ran == "gun":
print(f"you choosed {inp} and computer guess is {ran}")
computer_point=computer_point+1
print("The snake was shoot and he died\n")
print("You Lost this round")
print("computer gets 1 point\n")
else:
print("invalid")
print(10 - attempts, "no. of guesses left")
attempts = attempts + 1
if attempts>10:
print("game over")
if computer_point > your_point:
print("Computer wins and you loose")
if computer_point < your_point:
print("you win and computer loose")
print(f"your point is {your_point} and computer point is {computer_point}")

My input sometimes takes multiple times for it to go in the if statements

I am attempting to make a basic rock, paper, scissors game. When I input either rock, paper, or scissors, I sometimes have to enter the same thing multiple times for it to continue to the if statements. See code below:
# Rock, Paper, Scissors
player_total = 0
computer_total = 0
def get_computer_hand():
choice = randint(1, 3)
if choice == 1:
return "scissors"
elif choice == 2:
return "paper"
else:
return "rock"
def ask_user():
global player_total
global computer_total
player = input("Enter your hand (stop to stop): ")
if player == "stop":
print("Computer had ", computer_total, "points, you had ", player_total, " points.")
exit(0)
computer = get_computer_hand()
if player == "rock":
if computer == "paper":
return "win"
elif computer == "scissors":
return "lose"
else:
return "tie"
elif player == "paper":
if computer == "paper":
return "tie"
elif computer == "scissors":
return "lose"
else:
return "win"
elif player == "scissors":
if computer == "scissors":
return "tie"
elif computer == "paper":
return "win"
else:
return "lose"
def count_winner():
global player_total
global computer_total
player_total = 0
computer_total = 0
while True:
outcome = ask_user()
if outcome == "win":
print("You won that one.")
player_total += 1
elif outcome == "lose":
print("Computer won that one.")
computer_total += 1
count_winner()
I expect it to work the first time and to continue as usual, but I can't seem to figure out why it just asks "Enter your hand (stop to stop): " instead sometimes when I enter either rock, paper, or scissors.
This is happening because there is a tie happening between the computer and the user. This could be fixed by adding the end with the code of
else outcome == "tie":
print("You have tied with the Computer!")
computer_total += 1
player_total += 1
This would add a point to both sides and if you don't want that just delete the last two lines of my code

How to create a Rock, Paper, Scissors program

I'm very new to python and am taking an online class. I'm not very familiar with many functions in python so if you could keep it somewhat basic for me to keep track of, I would really appreciate it. I am trying to make a program that runs Rock, Paper, Scissors with a user but the num_games is not being accepted in the "for i in range". Also, I have run it and found that Scissors can beat Rock (THIS IS ANARCHY!). Can anyone assist me? Thanks in advance!
import random
def comp_turn():
comp_move = random.randint(1,3)
if comp_move == 1:
return "Rock!"
elif comp_move == 2:
return "Paper!"
else:
return "Scissors!"
def main():
num_games = int(input("Enter how many games you would like to play: "))
print "You are going to play " + str(num_games) + " games! Here we go!"
num_wins = 0
for i in range(num_games):
user_move = input("Choose either Rock, Paper or Scissors and enter it: ")
cpu_turn = comp_turn()
print "The computer went with: " + cpu_turn
if user_move == 'Rock' and cpu_turn == 'Scissors':
print "You won! Nice job!"
num_wins +=1
elif user_move == 'Paper' and cpu_turn == 'Rock':
print "You won! Nice job!"
num_wins +=1
elif user_move == 'Scissors' and cpu_turn == 'Paper':
print "You won! Nice job!"
num_wins +=1
elif user_move == cpu_turn:
print "Oh! You tied"
else:
print "Whoops! You lost!"
return num_wins
print main()
This should be what you want:
import random
def comp_turn():
return random.choice(['Rock','Paper','Scissors'])
def main():
num_games = int(input("Enter how many games you would like to play: "))
print("You are going to play " + str(num_games) + " games! Here we go!")
num_wins = 0
for i in range(num_games):
user_move = input("Choose either Rock, Paper or Scissors and enter it: ")
cpu_turn = comp_turn()
print("The computer went with: " + cpu_turn)
if user_move == 'Rock' and cpu_turn == 'Scissors': print("You won! Nice job!"); num_wins +=1
elif user_move == 'Paper' and cpu_turn == 'Rock': print("You won! Nice job!"); num_wins +=1
elif user_move == 'Scissors' and cpu_turn == 'Paper': print("You won! Nice job!"); num_wins +=1
elif user_move == cpu_turn: print("Oh! You tied")
else: print("Whoops! You lost!");
return num_wins
print(main())
Or even Better:
import random
def comp_turn():
return random.choice(['Rock','Paper','Scissors'])
def main():
num_games = int(input("Enter how many games you would like to play: "))
print("You are going to play " + str(num_games) + " games! Here we go!")
num_wins = 0
winning=[('Rock','Scissors'),('Paper','Rock'),('Scissors','Paper')]
for i in range(num_games):
user_move = input("Choose either Rock, Paper or Scissors and enter it: ")
cpu_turn = comp_turn()
print("The computer went with: " + cpu_turn)
if (user_move,cpu_turn) in winning:
print('You won!')
num_wins+=1
elif user_move == cpu_turn:
print('Same')
else:
print('You lost!')
return num_wins
print(main())
And another option that's also good:
import random
def comp_turn():
return random.choice(['Rock','Paper','Scissors'])
def main():
num_games = int(input("Enter how many games you would like to play: "))
print("You are going to play " + str(num_games) + " games! Here we go!")
num_wins = 0
d={}.fromkeys([('Rock','Scissors'),('Paper','Rock'),('Scissors','Paper')],'You Won')
for i in range(num_games):
user_move = input("Choose either Rock, Paper or Scissors and enter it: ")
cpu_turn = comp_turn()
print("The computer went with: " + cpu_turn)
if not user_move == cpu_turn:
print(d.get((user_move,cpu_turn),'You lost!'))
else:
print('Same')
return num_wins
print(main())
Here's what you want:
import random
outcome = random.choice(['Rock', 'Paper', 'Scissors'])
print(outcome)
Have you tried removing the '!' in the comp_turn function? It seems like cpu_turn variable will contain either 'Rock!', 'Scissors!' or 'Paper!' while your if-else condition is looking for either 'Rock', 'Scissors' or 'Paper' without the '!'. So, no matter what the player or cpu chooses, it will go into 'else' in the 'for' loop and the player loses.
This is the edited code:
import random
def comp_turn():
comp_move = random.randint(1,3)
if comp_move == 1: return "Rock"
elif comp_move == 2: return "Paper"
else: return "Scissors"
def main():
num_games = int(input("Enter how many games you would like to play: "))
print("You are going to play " + str(num_games) + " games! Here we go!")
num_wins = 0
for i in range(num_games):
user_move = input("Choose either Rock, Paper or Scissors and enter it: ")
cpu_turn = comp_turn()
print("The computer went with: " + cpu_turn)
if user_move == 'Rock' and cpu_turn == 'Scissors':
print("You won! Nice job!")
num_wins +=1
elif user_move == 'Paper' and cpu_turn == 'Rock':
print("You won! Nice job!")
num_wins +=1
elif user_move == 'Scissors' and cpu_turn == 'Paper':
print("You won! Nice job!")
num_wins +=1
elif user_move == cpu_turn:
print("Oh! You tied")
else: print("Whoops! You lost!")
return num_wins
print(main())
Do note that the player's input is case sensitive too. Hope this helps!

Python Coding Rock,Paper,Scissors,Lizard and Spock [duplicate]

This question already has an answer here:
How can I concatenate str and int objects?
(1 answer)
Closed 6 years ago.
total_guess = 0
wins = 0
loss = 0
import random
characters = ["rock", "paper", "scissors", "lizard", "spock"]
computer = characters[random.randint(0,4)]
print(computer)
Subroutine- functions fine
def valid(text, flag):
error_message= ""
while True:
var = input(error_message + text)
if flag == "s":
if var.isalpha()==True:
break
else:
error_message = "This is not valid, "
elif flag =="i":
if var.isdigit()==True:
var = int(var)
break
else:
error_message = user_name + " this is not a number, "
elif flag == "g":
if var == "rock" or var == "paper" or var == "scissors" or var == "lizard" or var == "spock":
break
else:
error_message = user_name + " this is not valid! "
return(var)
user_name = valid("What is your name?", "s")
num_rounds = valid(user_name +" how many rounds do you want?", "i")
This code does not work either due to past changes initially worked, 'says can't convert 'int' object to str implicitly
while True:
player = valid(user_name + """ ,What do you want as your character:
Rock, paper, scissors, lizard or spock""", "g" )
while num_rounds > total_guess:
total_guess = total_guess + 1
if player == computer:
print("Draw!")
# --------------------------------------------
elif player == "Rock" or player == "rock":
if computer == "paper" or computer == "spock" :
loss = loss + 1
print("You lost ", computer, " beats ", player)
print( user_name + " you have won " + wins +" games")
if computer == "scissors" or computer == "lizard":
wins = wins + 1
print("You win", player, " beats ", computer)
# ---------------------------------------------
elif player == "Paper" or player == "paper":
if computer == "scissors" or computer == "lizard":
loss = loss + 1
print("You lost ", computer, " beats ", player)
if computer == "rock" or computer == "spock":
wins = wins + 1
print("You win", player, " beats ", computer)
# ---------------------------------------------
elif player == "Scissors" or player == "scissors":
if computer =="Spock" or computer == "rock":
loss = loss + 1
print("You lost ", computer, " beats ", player)
if computer =="paper" or computer == "lizard":
wins = wins + 1
print("You win", player, " beats ", computer)
# --------------------------------------------
elif player == "Lizard" or player =="lizard":
if computer =="scissors" or computer == "rock":
loss = loss + 1
print("You lost ", computer, " beats ", player)
if computer == "paper" or computer == "spock":
wins = wins + 1
print("You win", player, " beats ", computer)
# --------------------------------------------
elif player == "Spock" or player == "spock":
if computer == "lizard" or computer == "paper":
loss = loss + 1
print("You lost ", computer, " beats ", player)
if computer =="rock" or computer == "scissors":
wins = wins + 1
print("You win", player, " beats ", computer)
# -------------------------------------------
This block code to restart game does not work it's purpose is to have a try again feature
end_game = input("To exit enter N, to play again enter any key ")
if end_game == 'n' or end_game == 'N':
print("THANKS FOR PLAYING " + user_name + '!')
break
This could be shortened heavily but I don't feel like rewriting your entire program. This should work as expected.
total_guess = 0
wins = 0
loss = 0
import random
characters = ["rock", "paper", "scissors", "lizard", "spock"]
computer = characters[random.randint(0,4)]
print(computer)
def valid(text, flag):
error_message= ""
while True:
var = input(error_message + text)
if flag == "s":
if var.isalpha()==True:
break
else:
error_message = "This is not valid, "
elif flag =="i":
if var.isdigit()==True:
var = int(var)
break
else:
error_message = user_name + " this is not a number, "
elif flag == "g":
if var == "rock" or var == "paper" or var == "scissors" or var == "lizard" or var == "spock":
break
else:
error_message = user_name + " this is not valid! "
return(var)
user_name = valid("What is your name?", "s")
num_rounds = valid(user_name +" how many rounds do you want?", "i")
while True:
while num_rounds > total_guess:
player = valid(user_name + """ ,What do you want as your character:
Rock, paper, scissors, lizard or spock""", "g" )
total_guess = total_guess + 1
if player == computer:
print("Draw!")
# --------------------------------------------
elif player == "Rock" or player == "rock":
if computer == "paper" or computer == "spock" :
loss = loss + 1
print(' '.join(("You lost", computer, "beats", player)))
if computer == "scissors" or computer == "lizard":
wins = wins + 1
print(' '.join(("You win", player, "beats", computer)))
elif player == "Paper" or player == "paper":
if computer == "scissors" or computer == "lizard":
loss = loss + 1
print(' '.join(("You lost", computer, "beats", player)))
if computer == "rock" or computer == "spock":
wins = wins + 1
print(' '.join(("You win", player, "beats", computer)))
elif player == "Scissors" or player == "scissors":
if computer =="Spock" or computer == "rock":
loss = loss + 1
print(' '.join(("You lost", computer, " beats ", player)))
if computer =="paper" or computer == "lizard":
wins = wins + 1
print(' '.join(("You win", player, "beats", computer)))
elif player == "Lizard" or player =="lizard":
if computer =="scissors" or computer == "rock":
loss = loss + 1
print(' '.join(("You lost", computer, "beats", player)))
if computer == "paper" or computer == "spock":
wins = wins + 1
print(' '.join(("You win", player, "beats", computer)))
elif player == "Spock" or player == "spock":
if computer == "lizard" or computer == "paper":
loss = loss + 1
print(' '.join(("You lost", computer, "beats", player)))
if computer =="rock" or computer == "scissors":
wins = wins + 1
print(' '.join(("You win", player, "beats", computer)))
end_game = input("To exit enter N, to play again enter any key ")
if end_game == 'n' or end_game == 'N':
print("THANKS FOR PLAYING " + user_name + '!')
break
total_guess = 0

Categories