Trying to do input validation for rps game - python-3.x

I'm making an rps game on python 3.6 and can't seem to figure out how to do input validation for my two player game function module. Whenever I run the program and select two player game and enter a number less than 1 or more than 4, it just asks if I want to play again.
def twoPlayerGame():
player1 = False
player2 = 0
player1Win = 0
player2Win = 0
tie_ = 0
#prompting for weapon choice
while player1 == False:
weaponMenu()
player1 = int(input("Player 1, please make a selection.\t"))
player2 = int(input("Player 2, please make a selection.\t"))
while player1 or player2 not in range(1,4):
print ("Invalid data entered, try again.")
weaponMenu()
player1 = int(input("Player 1, please make a selection.\t"))
player2 = int(input("Player 2, please make a selection.\t"))
#redirects to main
while player1 == 4 or player2 == 4:
main()
if player1 == player2:
print("It's a tie!\n")
tie_ = tie_ + 1
elif player1 == 1:
if player2 == 2:
print("Paper covers rock! Player 2 won!\n")
player2Win = player2Win + 1
else:
print("Rock smashes scissors! Player 1 won!\n")
player1Win = player1Win + 1
elif player1 == 2:
if player2 == 3:
print("Scissors cuts paper! Player 2 won!\n")
player2Win = player2Win + 1
else:
print("Paper covers rock! Player 1 won!\n")
player1Win = player1Win + 1
elif player1 == 3:
if player2 == 1:
print("Rock smashes scissors! Player 2 won!\n")
player2Win = player2Win + 1
else:
print("Scissors cuts paper! Player 2 won!\n")
p1ayer2Win = player2Win + 1
#ask user if they want to play again
again = input("Play again? Enter yes or no.\n")
again = again.lower()
#display scores
print("Ties:\t", tie_)
print("Player 1 wins:\t", player1Win)
print("Player 2 wins:\t", player2Win)
#if yes, player still playing
#if no, redirect to main
if again=="yes":
player1 = False
else:
player1 = True
main()

Problem is with this line:
while player1 or player2 not in range(1,4):
Whatever you put on each side of or should usually be a true or false value. Putting player1 on the left side, while acceptable to the Python interpreter, is incorrect here because what you want to do is check if it's in range. On the right side, player2 not in range(1,4) is an actual true/false value, so that's fine.
So change the thing on the left to player1 not in range(1,4), and the function works fine:
while player1 not in range(1,4) or player2 not in range(1,4):

Related

Python Error handling for an input requiring a integer

I would like to implement error handling so that if the user puts in anything besides an integer they get asked for the correct input. I believe try/except would work but I am wondering how I can get it to check for both a correct number within a range and ensuring there are no other characters. I have pasted my code below for review.
Thanks!
# Rock Paper Scissors
import random as rdm
print("Welcome to Rock/Paper/Scissors, you will be up against the computer in a best of 3")
# game_counter = 0
human_1 = input("Please enter your name: ")
GameOptions = ['Rock', 'Paper', 'Scissors']
hmn_score = 0
cpt_score = 0
rps_running = True
def rps():
global cpt_score, hmn_score
while rps_running:
hmn = int(input("""Please select from the following:
1 - Rock
2 - Paper
3 - Scissors
\n""")) - 1
while not int(hmn) in range(0, 3):
hmn = int(input("""Please select from the following:
1 - Rock
2 - Paper
3 - Scissors
\n""")) - 1
print('You Chose: ' + GameOptions[hmn])
cpt = rdm.randint(0, 2)
print('Computer Chose: ' + GameOptions[cpt] + '\n')
if hmn == cpt:
print('Tie Game!')
elif hmn == 0 and cpt == 3:
print('You Win')
hmn_score += 1
elif hmn == 1 and cpt == 0:
print('You Win')
hmn_score += 1
elif hmn == 2 and cpt == 1:
print('You Win')
hmn_score += 1
else:
print('You Lose')
cpt_score += 1
game_score()
game_running()
def game_score():
global cpt_score, hmn_score
print(f'\n The current score is {hmn_score} for you and {cpt_score} for the computer \n')
def game_running():
global rps_running
if hmn_score == 2:
rps_running = False
print(f"{human_1} Wins!")
elif cpt_score == 2:
rps_running = False
print(f"Computer Wins!")
else:
rps_running = True
rps()
To answer your question, you can do something like the following
options = range(1, 4)
while True:
try:
choice = int(input("Please select ...etc..."))
if(choice in options):
break
raise ValueError
except ValueError:
print(f"Please enter a number {list(options)}")
print(f"You chose {choice}")
As for the a code review, there's a specific stack exchange for that, see Code Review

Rock-Paper-Scissors-Pencil-Fire game with functions doesn't work

I am trying to make a game of rock-paper-scissors-pencil-fire with functions and it doesn't work. It seems that it can't go inside the compare function(named findwinner()) and return the results.
i looked throw the web for help but i couldn't find anything. i tried assigning the variables in many different ways but with no luck.
python
#Rock-Paper-Scissors-Fire-Pencil Game
#Game:
#The player must choose his weapon and 'fight' against the computer following #the rules above.
#The player can choose between the following: Rock, Scissors, Fire, Pencil and #Paper.
#Rules: The rock beats the scissors, the scissors beat the fire, the fire #beats the pencil, the pencil beats the paper and the paper beats the rock
#Player1 is the human player
#Player2 is the computer
import random
#The game welcomes the player.
print("Wellcome to the Rock-Paper-Scissors-Fire-Pencil game!")
#The player can play as many times as he/she wants until he/she type anything #else except yes in the "Do you want to play again?" question.
def getuser():
choices = ["rock", "scissors", "fire", "pencil", "paper"]
#The computer chooses it's 'weapon'.
player2 = choices[random.randint(0,4)]
player1 = None
while player1 not in choices:
#The player must choose his/her 'weapon'
player1 = input("\n PLAYER 1 - Please make a choice (rock/paper/scissors/fire/pencil):")
print (f"\nPlayer1 choose {player1}")
print (f"\nPlayer2 choose {player2}")
return ()
def findwinner():
winner = None
p1 = getuser()[1]
p2 = getuser()[2]
#The game keeps how many times the player1 has won, lost or tied with the computer in the variables bellow.
wins = 0
losses = 0
ties = 0
#The game compares the choises of the players and announces if the human player won, lost or tied with the computer.
#Then it adds the win, the lost or the tie to the summary of wins, losses or ties.
if p1 != p2:
if p1 == "rock":
if p2 == "scissors" or p2 == "pencil" or p2 == "fire":
print("\n Player1 wins this round!")
winner = p1
wins += 1
else:
print("\n Player2 wins this round!")
winner = p2
losses += 1
if p1 == "paper":
if p2 == "rock":
print("\n Player1 wins this round!")
winner = p1
wins += 1
else:
print("\n Player2 wins this round!")
winner = p2
losses += 1
if p1 == "scissors":
if p2 == "paper" or p2 == "pencil":
print("\n Player1 wins this round!")
winner = p1
wins += 1
else :
print("\n Player2 wins this round!")
winner = p2
losses += 1
if p1 == "pencil":
if p2 == "paper":
print("\n Player1 wins this round!")
winner = p1
wins += 1
else:
print("\n Player2 wins this round!")
winner = p2
losses += 1
if p1 == "fire":
if p2 == "paper" or p2 == "scissors" or p2 == "pencil":
print("\n Player1 wins this round!")
winner = p1
wins += 1
else:
print("\n Player2 wins this round!")
winner = p2
losses += 1
else:
print("\n The round is a tie!")
winner = None
ties += 1
print (f"\nThe winner of this round is {winner}")
return (winner, wins, losses, ties)
play_again = "yes"
while play_again == "yes":
#The game shows the choises of the players.
player1 = getuser()[1]
player2 = getuser()[2]
findwinner(player1, player2)
#The game askes the player if he/she wants to play again.
play_again = input("\nDo you want to play again?:")
else:
#If the player doesn't want to play again, the game prints the results of all the rounds of the game and closes.
print(f"The player1 won {findwinner()[2]} times")
print(f"The player1 lost {findwinner()[3]} times")
print(f"The player1 tied {findwinner()[4]} times")
print("\n Good Bye")
You got a couple of problems:
getuser() just prints the choices but does not return them, to fix this just change the return to player1, player2
findwinner() does not get any parameters according to the signature, you have to change the signature to findwinner(p1, p2)
If you are receiving the players choices by argument in findwinner(), you don't have to call getuser() again.
Wins, losses and ties counters are going to be reset each time you call findwinner() you have to declare them as globals outside the function, and then update them inside the function.
After fixing these, you end up with this:
import random
#The game keeps how many times the player1 has won, lost or tied with the computer in the variables bellow.
# 4 FIX) declare counters as globals
wins = 0
losses = 0
ties = 0
#The game welcomes the player.
print("Welcome to the Rock-Paper-Scissors-Fire-Pencil game!")
#The player can play as many times as he/she wants until he/she type anything
#else except yes in the "Do you want to play again?" question.
def getuser():
choices = ["rock", "scissors", "fire", "pencil", "paper"]
#The computer chooses it's 'weapon'.
player2 = choices[random.randint(0,4)]
player1 = None
while player1 not in choices:
#The player must choose his/her 'weapon'
player1 = input("\n PLAYER 1 - Please make a choice (rock/paper/scissors/fire/pencil):")
print (f"\nPlayer1 choose {player1}")
print (f"\nPlayer2 choose {player2}")
return player1, player2 # 1 FIX) return players choice
# 2 FIX) add players choice as parameters
def findwinner(p1, p2):
winner = None
# 3 FIX) do not call getuser since you have the player choices as arguments
# 4 FIX) use them as globals in the function scope
global wins, losses, ties
#The game compares the choises of the players and announces if the human player won, lost or tied with the computer.
#Then it adds the win, the lost or the tie to the summary of wins, losses or ties.
if p1 != p2:
if p1 == "rock":
if p2 == "scissors" or p2 == "pencil" or p2 == "fire":
print("\n Player1 wins this round!")
winner = p1
wins += 1
else:
print("\n Player2 wins this round!")
winner = p2
losses += 1
if p1 == "paper":
if p2 == "rock":
print("\n Player1 wins this round!")
winner = p1
wins += 1
else:
print("\n Player2 wins this round!")
winner = p2
losses += 1
if p1 == "scissors":
if p2 == "paper" or p2 == "pencil":
print("\n Player1 wins this round!")
winner = p1
wins += 1
else :
print("\n Player2 wins this round!")
winner = p2
losses += 1
if p1 == "pencil":
if p2 == "paper":
print("\n Player1 wins this round!")
winner = p1
wins += 1
else:
print("\n Player2 wins this round!")
winner = p2
losses += 1
if p1 == "fire":
if p2 == "paper" or p2 == "scissors" or p2 == "pencil":
print("\n Player1 wins this round!")
winner = p1
wins += 1
else:
print("\n Player2 wins this round!")
winner = p2
losses += 1
else:
print("\n The round is a tie!")
winner = None
ties += 1
print (f"\nThe winner of this round is {winner}")
return winner # 4 FIX) no need to return the counters anymore
play_again = "yes"
while play_again == "yes":
#The game shows the choises of the players.
player1, player2 = getuser() # 1 FIX) save player choices
findwinner(player1, player2)
#The game askes the player if he/she wants to play again.
play_again = input("\nDo you want to play again?:")
else:
#If the player doesn't want to play again, the game prints the results of all the rounds of the game and closes.
# 4 FIX) Use the global variables
print(f"The player1 won {wins} times")
print(f"The player1 lost {losses} times")
print(f"The player1 tied {ties} times")
print("\n Good Bye")
I can tell you have problems understanding function returns. Each time you do findwinner() you are calling the function AGAIN, to run it only once and save the result you assign it to a variable. As done for getuser():
player1, player2 = getuser()

I am writing my first assignment and i cant seem figure out why i am unable to enter my first function

First of im sorry about bombarding my post with a bunch of code, but im putting it here hoping that it will help you guys understanding my question better.
I am trying to figure out why my IDE is unwilling to execute the first function of my code. Obviously im doing something wrong, but im to unexperienced to see it for myself. All help would be greatly appriciated.
If you have any further comments or tips on my code feel free contribute.
import random
print("Press '1' for New Single Player Game - Play against computer component: ")
print("Press '2' for New Two Player Game - Play against another person, using same computer: ")
print("Press '3' for Bonus Feature - A bonus feature of choice: ")
print("Press '4' for User Guide - Display full instructions for using your application: ")
print("Press '5' for Quit - Exit the program: ")
def choose_program():
what_program = int(input("What program would you like to initiate?? Type in the 'number-value' from the chart above: "))
if what_program == 1 or 2 or 3 or 4 or 5:
program_choice = int(input("Make a choice: "))
if (program_choice > 5) or (program_choice < 1):
print("Please choose a number between 1 through 5 ")
choose_program()
elif program_choice == 1:
print("You picked a New Single Player Game - Play against computer component")
def single_player():
start_game = input("Would you like to play 'ROCK PAPER SCISSORS LIZARD SPOCK'?? Type 'y' for YES, and 'n' for NO): ").lower()
if start_game == "y":
print("Press '1' for Rock: ")
print("Press '2' for Paper: ")
print("Press '3' for Scissors: ")
print("Press '4' for Lizard: ")
print("Press '5' for Spock: ")
elif start_game != "n":
print("Please type either 'y' for YES or 'n' for NO: ")
single_player()
def player_one():
human_one = int(input("Make a choice: "))
if (human_one > 5) or (human_one < 1):
print("Please choose a number between 1 through 5 ")
player_one()
elif human_one == 1:
print("You picked ROCK!")
elif human_one == 2:
print("You picked PAPER!")
elif human_one == 3:
print("You picked SCISSORS!")
elif human_one == 4:
print("You picked LIZARD!")
elif human_one == 5:
print("You picked SPOCK!")
return human_one
def computers_brain():
cpu_one = random.randint(1, 5)
if cpu_one == 1:
print("Computers choice iiiiiis ROCK!")
elif cpu_one == 2:
print("Computers choice iiiiiis PAPER!")
elif cpu_one == 3:
print("Computers choice iiiiiis SCISSORS!")
elif cpu_one == 4:
print("Computers choice iiiiiis LIZARD!")
elif cpu_one == 5:
print("Computers choice iiiiiis SPOCK!")
return cpu_one
def who_won(human, cpu, human_wins, cpu_wins, draw):
if human == 1 and cpu == 3 or cpu == 4:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == 2 and cpu == 1 or cpu == 5:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == 3 and cpu == 2 or cpu == 4:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == 4 and cpu == 2 or cpu == 5:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == 5 and cpu == 1 or cpu == 3:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == cpu:
print("Human & computer think alike, such technology")
draw = draw.append(1)
else:
print("Computer have beaten it's master, incredible..")
cpu_wins = cpu_wins.append(1)
return
def end_score(human_wins, cpu_wins, draw):
human_wins = sum(human_wins)
cpu_wins = sum(cpu_wins)
draw = sum(draw)
print("Humans final score is: ", human_wins)
print("Computers final score is: ", cpu_wins)
print("Total draws: ", draw)
def main():
human = 0
human_wins = []
cpu = 0
cpu_wins = []
draw = []
finalhuman_wins = 0
finalcpu_wins = 0
finaldraw = 0
Continue = 'y'
single_player()
while Continue == 'y':
human = player_one()
cpu = computers_brain()
who_won(human, cpu, human_wins, cpu_wins, draw)
Continue = input("Would you like to play again (y/n):").lower()
if Continue == 'n':
print("Printing final scores.")
break
end_score(human_wins, cpu_wins, draw)
main()
elif program_choice == 2:
print("You picked a New Two Player Game - Play against another person, using same computer")
elif program_choice == 3:
print("You picked the Bonus Feature - A bonus feature of choice")
elif program_choice == 4:
print("You picked the User Guide - Display full instructions for using your application")
elif program_choice == 5:
print("You picked to Quit - Exit the program")
return program_choice
elif what_program != 1 or 2 or 3 or 4 or 5:
print("To initiate a program you need to type in the appropriate number to initiate this program, either 1, 2, 3, 4 & 5 ")
choose_program()
Outout in IDE:
Press '1' for New Single Player Game - Play against computer component:
Press '2' for New Two Player Game - Play against another person, using same computer:
Press '3' for Bonus Feature - A bonus feature of choice:
Press '4' for User Guide - Display full instructions for using your application:
Press '5' for Quit - Exit the program:
Process finished with exit code 0
Thank you in advance for your help :)

While loop exiting instead of returning back to the top of the loop -Python

I am having problems at the end of the while loop. When completing the game the program asks you if you want to play the game again after you input yes it set the player variable to false so you can continue the loop, but if you input anything the program exit.
# Importing Random
from random import *
win = 0
lose = 0
draw = 0
print("[y/Y] Play game")
print("[n/N] Quit")
answer = input("Do you wanna play a game?: ")
if answer == "y" or answer == "Y":
# Show score of game
print("Score:", win,"wins,", draw, "draws,", lose,"losses")
#create a list of play options
plays = ["ROCK", "PAPER", "SCISSORS"]
#assign a random play to the computer
computer = choice(plays)
#set player to False
player = False
while player == False:
#set player to True
player = input("Choose one: rock, paper or scissors: ").upper()
if player == computer:
print("Draw, try again")
# Add 1 to the draw score
draw += 1
elif player == "ROCK":
if computer == "Paper":
print("You lose!", computer, "covers", player)
# Add 1 to the lose score
lose += 1
else:
print("You win!", player, "smashes", computer)
# Add 1 to the win score
win += 1
elif player == "PAPER":
if computer == "Scissors":
print("You lose!", computer, "cut", player)
# Add 1 to the lose score
lose += 1
else:
print("You win!", player, "covers", computer)
# Add 1 to the win score
win += 1
elif player == "SCISSORS":
if computer == "Rock":
print("You lose...", computer, "smashes", player)
# Add 1 to the lose score
lose += 1
else:
print("You win!", player, "cut", computer)
# Add 1 to the win score
win += 1
else:
print("That's not a valid play. Check your spelling!")
# Ask the player for a new game
new_game = input("Do you wanna play again?: ")
if answer == ["Y", "y", "Yes", "yes", "YES"]:
# Set player to false again to continue loop
player = False
computer = choice(plays)
elif answer == ["N", "n", "no", "No", "NO"]:
global flag
flag = 1
exit()
if flag == 1:
exit()
elif answer == "n" or answer == "N":
exit()
The problem is with this part
# Ask the player for a new game
new_game = input("Do you wanna play again?: ")
if answer == ["Y", "y", "Yes", "yes", "YES"]:
# Set player to false again to continue loop
player = False
computer = choice(plays)
elif answer == ["N", "n", "no", "No", "NO"]:
global flag
flag = 1
exit()
if flag == 1:
exit()
elif answer == "n" or answer == "N":
exit()
Solved, I had to change the variable new_game with answer

A simple Game of Pig

The code I have for the game runs just fine, but I'm having trouble getting the game to end when one person reaches at least 100 points.
def dont_Be_Greedy(turn):
points = 0
keepPlaying = 121
print('Lets start!')
input('Press enter to roll')
while keepPlaying == 121:
roll = roll_Dice()
print('You rolled a ' + str(roll))
if roll == 1:
points = 0 * roll
keepPlaying = 110
enter = input('Your turn is over. Next player.')
elif roll > 1:
points += roll
print('your total is', points)
passPlay = input('Do you want to keep playing or pass?'
'\ntype pass or play. ')
if passPlay == 'play':
keepPlaying = 121
else:
keepPlaying = 110
enter = input('Your turn is over. Next player.')
return points
player1 = 0
player2 = 0
while player1 < 100 and player2 < 100:
print('Player 1 points are: ' + str(player1))
print('Player 2 points are: ' + str(player2))
gameOn = dont_Be_Greedy(1)
player1 += gameOn
print('Player 1 points are: ' + str(player1))
print('Player 2 points are: ' + str(player2))
gameOn = dont_Be_Greedy(2)
player2 += gameOn
if player1 >= 100:
print('Player 1 is the winner!')
elif player2 >= 100:
print('Player 2 is the winner!')
Instead of the program stopping when one player reaches 100, it lets them continue their turn. After they pass their turn, it lets the next player start rolling until they pass or roll one then the program stops and states the winner (person with the higher of the two scores).
I'm not sure where the problem is.
EDIT: I added dont_Be_Greedy I tried moving the if and elif statements just below the loop and the program stops without printing the winner.
Seems like your problem lies with dont_Be_Greedy().
It doesn't stop when it reaches 100.

Resources