python problems can't seem to check some values - python

I have just started my first language: python. So I started practicing it and tried writing a rock, paper, scissors game. I know I'm not the best but can't seem to make the game end when the us_count and comp_count reached the max
import random
us_count = 0
comp_count = 0
gamelim = None
def GameConfig(gamelim,us_count,comp_count):
gamelim = input("How long do you want the game to be: \n")
Game(gamelim,us_count,comp_count)
def GameLoop(gamelim,us_count,comp_count):
if us_count > comp_count and us_count + comp_count == gamelim:
print("You have the best ",us_count," out of ",gamelim)
GameEnd()
elif us_count < comp_count and us_count + comp_count == gamelim:
print("Computer has bested ",comp_count," out of ",gamelim)
GameEnd()
elif us_count == comp_count and us_count + comp_count == gamelim:
print("Game tied.")
GameEnd()
else:
Game(gamelim,us_count,comp_count)
def GameEnd():
gamecont = print("Game has ended do you want to play again?")
end
def Game(gamelim,us_count,comp_count):
us_choice = str(input("Please select rock, paper or scissors: \n"))
choices = ["rock","paper","scissors"]
comp_choice = random.choice(choices)
if us_choice == comp_choice:
print("Computer choses " + comp_choice + "\nIt'a tie.")
elif us_choice == "rock" and comp_choice == "scissors":
print("Computer choses " + comp_choice + "\nYou won.")
us_count = us_count + 1
elif us_choice == "rock" and comp_choice == "paper":
print("Computer choses " + comp_choice + "\nYou lost.")
comp_count = comp_count + 1
elif us_choice == "paper" and comp_choice == "rock":
print("Computer choses " + comp_choice + "\nYou won.")
us_coun = us_count + 1
elif us_choice == "paper" and comp_choice == "scissors":
print("Computer choses " + comp_choice + "\nYou lost.")
comp_count = comp_count + 1
elif us_choice == "scissors" and comp_choice == "paper":
print("Computer choses " + comp_choice + "\nYou won.")
us_count = us_count + 1
elif us_choice == "scissors" and comp_choice == "rock":
print("Computer choses " + comp_choice + "\nYou lost.")
comp_count = comp_count + 1
else:
print("Please enter a corret value")
GameLoop(gamelim,us_count,comp_count)
GameConfig(gamelim,us_count,comp_count)

Related

Game Not Functioning Properly

So i tried making a rock paper scissors game but some if statements are not working. code was written in python.
Is there something preventing the if statements ffrom running? or s there another problem
I tried a bunch of little changes but none of them work
code:
import random
moves = ('rock', 'paper', 'scissors')
while True:
print("rock, paper, scissors. Go! ")
userInput = input("Choose your move: ")
botInput = random.choice(moves)
if userInput == botInput:
print(userInput + " VS " + botInput)
print("DRAW")
if userInput == "paper" and botInput == "rock":
print(userInput + " VS " + botInput)
print("Player Wins!")
if userInput == "scissors" and botInput == "paper":
print(userInput + " VS " + botInput)
print("Player Wins!")
if userInput == "rock" and botInput == "scissors":
print(userInput + " VS " + botInput)
print("Player Wins!")
if userInput == "rock" and botInput == "paper":
print(userInput + " VS " + botInput)
print("Bot Wins!")
if userInput == "paper" and botInput == "scissors":
print(userInput + " VS " + botInput)
print("Bot Wins!")
if userInput == "scissors" and botInput == "rock":
print(userInput + " VS " + botInput)
print("Bot Wins!")
print("Wanna Rematch?")
decision = input("Yes or No? ")
if decision == "Yes":
pass
elif decision == "No":
break
Here's my solution to this. I cleaned up the amount of if-else statements in your code as well with a variable outcome_map. I also removed a lot of the typing rarities that come with inputs by introducing your choice to be "(1, 2, or 3)":
import random
moves = ('rock', 'paper', 'scissors')
while True:
print("Rock, paper, scissors. Go! ")
user_input = int(input("Choose your move (1:rock, 2:paper, 3:scissors): "))
if user_input not in [1, 2, 3]:
print("Invalid input. Try again...")
continue
bot_move = random.choice(moves)
user_move = moves[user_input-1]
outcome_map = { # item A vs item B -> Outcome for A
"rock":{
"rock":"Draw",
"paper":"Lose",
"scissors":"Win",
},
"paper":{
"rock":"Win",
"paper":"Draw",
"scissors":"Lose",
},
"scissors":{
"rock":"Lose",
"paper":"Win",
"scissors":"Draw",
}
}
outcome = outcome_map[user_move][bot_move]
print("Player: ", outcome, "!")
decision = input("Wanna Rematch? (y/n) ")
if decision in ["y", "yes", "Y", "YES"]:
pass
else:
print("Exiting... ")
break
Hope this helps!
I think there's nothing wrong with your code... however, it does not handle specific inputs, maybe that is your problem, here is my solution:
import random
moves = ('rock', 'paper', 'scissors')
while True:
print("rock, paper, scissors. Go! ")
userInput = input("Choose your move: ").lower()
botInput = random.choice(moves)
#check if input is valid
if userInput not in moves:
print("Choose a valid move! Wanna try again?")
decision = input("Yes or No? ").lower()
if decision == "yes" or decision == 'y': continue
# skips the remaining body of the loop
else: break
elif userInput == botInput:
print(userInput + " VS " + botInput)
print("DRAW")
elif userInput == "paper" and botInput == "rock":
print(userInput + " VS " + botInput)
print("Player Wins!")
elif userInput == "scissors" and botInput == "paper":
print(userInput + " VS " + botInput)
print("Player Wins!")
elif userInput == "rock" and botInput == "scissors":
print(userInput + " VS " + botInput)
print("Player Wins!")
elif userInput == "rock" and botInput == "paper":
print(userInput + " VS " + botInput)
print("Bot Wins!")
elif userInput == "paper" and botInput == "scissors":
print(userInput + " VS " + botInput)
print("Bot Wins!")
elif userInput == "scissors" and botInput == "rock":
print(userInput + " VS " + botInput)
print("Bot Wins!")
print("Wanna Rematch?")
decision = input("Yes or No? ").lower()
if decision == "yes" or decision == 'y': continue
else: break
I hope you understand what I did here:
moves = ('rock', 'paper', 'scissors')
decision = "Nothing"
while decision != "No":
decision = "Nothing"
print("rock, paper, scissors. Go! ")
userInput = input("Choose your move: ")
botInput = random.choice(moves)
if userInput == "paper":
if botInput == "rock":
print(userInput + " VS " + botInput)
print("Player Wins!")
elif botInput == "paper":
print(userInput + " VS " + botInput)
print("DRAW")
elif botInput == "scissors":
print(userInput + " VS " + botInput)
print("Bot Wins!")
else:
print("Invalid choice.")
if userInput == "scissors":
if botInput == "rock":
print(userInput + " VS " + botInput)
print("Bot Wins!")
elif botInput == "paper":
print(userInput + " VS " + botInput)
print("Player Wins!")
elif botInput == "scissors":
print(userInput + " VS " + botInput)
print("DRAW")
if userInput == "rock":
if botInput == "rock":
print(userInput + " VS " + botInput)
print("DRAW")
elif botInput == "paper":
print(userInput + " VS " + botInput)
print("Bot Wins!")
elif botInput == "scissors":
print(userInput + " VS " + botInput)
print("Player Wins!")
while decision != "Yes" and decision != "No":
print("Wanna Rematch?")
decision = input("Yes or No? ")
if decision == "Yes":
pass
elif decision == "No":
break
else:
print("Invalid answer.")

Python: Game not running through

I have written logic in python for the game of rock, paper , scissor but having trouble to get it to run.
It wont run the through the entire game and just keeps asking me for my input. I have looked through it multiple times but cant see where it might be getting stuck.
Any idea what the issue may be?
Code is as below:
import random
comp_wins = 0
player_wins = 0
def choose_option ():
user_choice = input("choose rock, paper and scissors: ")
if user_choice in ["rock","Rock"]:
user_choice = "rock"
elif user_choice in ["paper","Paper"]:
user_choice = "paper"
elif user_choice in ["scissors","Scissor"]:
user_choice = "scissors"
else:
print ("error try again")
return user_choice
def computer_option ():
comp_choice = random.randint(1,3)
if comp_choice ==1:
comp_choice = "rock"
elif comp_choice ==2:
comp_choice = "paper"
elif comp_choice ==3:
comp_choice = "scissors"
return comp_choice
while True:
print("")
user_choice = choose_option ()
comp_choice = computer_option ()
print ("")
if user_choice ==["rock"]:
if comp_choice == "rock":
print("draw")
elif comp_choice == "paper":
print("computer wins")
comp_wins += 1
elif comp_choice == "scissors":
print("user wins")
player_wins += 1
elif user_choice == "paper":
if comp_choice == "rock":
print("user wins")
player_wins += 1
elif comp_choice == "paper":
print("draw")
elif comp_choice == "scissors":
print("computer wins")
comp_wins += 1
elif user_choice == "scissors":
if comp_choice == "rock":
print("computer wins")
comp_wins += 1
elif comp_choice == "paper":
print("user wins")
player_wins += 1
elif comp_choice == "scissors":
print("draw")
print("")
print("user_wins: " + str(player_wins))
print("comp_wins: " + str(comp_wins))
print("")
Youur issue is here
while True:
print("")
user_choice = choose_option ()
comp_choice = computer_option ()
print ("")
You never exit this while, you should put an exit condition or a flag when a choice has been made.
Also it would be better to clean up and use a Top-Down structure with a main function in which you control the file.
It looks that there is a wrong indent: the main while True loop never ends. Try to move all blocks after this loop to the right (i.e. add four spaces in the beginning of all next lines).
Your indentation levels aren't correct. The if user_choice ==["rock"]: part is the same indentation level as the while statement, so it isn't included in the loop. You need to indent it to let Python know it's part of the loop block. And since you don't have anything that ends the loop, it will go on forever. Also, using strings to represent choices is really inefficient. If you represent choices with numbers, you can use modular arithmetic.

Why won't my while loop end my rock, paper, scissors game?

I cannot figure out why my while loop won't terminate my game after user_count or comp_count reaches 3.
Would anyone please be able to offer some advice? I don't see what I am missing as I have everything indented under the while loop, and I am incrementing scores +=1 with each turn that is played.
import random
rock_paper_scissor_list = ['ROCK', 'PAPER', 'SCISSORS']
def comp_turn():
comp_choice = random.choice(rock_paper_scissor_list)
return comp_choice
def user_turn():
raw_user_input = input('Choose rock/paper/scissors: ').lower()
if raw_user_input in ['rock', 'r']:
user_choice = 'ROCK'
elif raw_user_input in ['paper', 'p']:
user_choice = 'PAPER'
else:
user_choice = 'SCISSORS'
return user_choice
def play_game(user_choice, comp_choice):
user_score = 0
comp_score = 0
print('User choice is: ' + user_choice)
print('Comp choice is: ' + comp_choice + '\n')
while user_score < 3 or comp_score < 3:
if comp_choice == 'ROCK' and user_choice == 'ROCK':
print("It's a tie!")
elif comp_choice == 'PAPER' and user_choice == "ROCK":
print('Comp wins this round!')
comp_score += 1
elif comp_choice == 'SCISSORS' and user_choice == "ROCK":
print('You win this round!')
user_score += 1
elif comp_choice == 'ROCK' and user_choice == "PAPER":
print('You win this round!')
user_score += 1
elif comp_choice == 'PAPER' and user_choice == "PAPER":
print("It's a tie!")
elif comp_choice == 'SCISSORS' and user_choice == "PAPER":
print('Comp wins this round!')
comp_score += 1
elif comp_choice == 'ROCK' and user_choice == "SCISSORS":
print('Comp wins this round!')
comp_score += 1
elif comp_choice == 'PAPER' and user_choice == "SCISSORS":
print('You win this round!')
user_score += 1
elif comp_choice == 'SCISSORS' and user_choice == "SCISSORS":
print("It's a tie!")
print('\nUser score is: ' + str(user_score))
print('Comp score is: ' + str(comp_score))
play_game(user_turn(), comp_turn())
user_score < 3 or comp_score < 3 will be true until both scores are greater than or equal to 3. You want and to ensure that both are under 3:
while user_score < 3 and comp_score < 3:

Variable not registering change in value

I wanted to make a simple Rock, Paper, Scissor game in Python. It goes well with the game, but the final scores are always being showed as a 0.
I wanted to show a smaller section of the code but, I don't know where the problem lies, so I am sorry for the length of the code.
I am still a novice learner, so please pardon me if the question is too silly or the code is not well formatted.
#Rock-Paper-Scissor Game
import random
print("Please enter your name:")
userName = input()
print("Welcome " + userName)
print("The following are the rules of the game:")
print("Press 'R' for Rock")
print("Press 'P' for Paper")
print("Press 'S' for Scissor")
print("This will be a 10 point match")
userTally = 0
compTally = 0
def gameProcess(userTally, compTally): #The process of the game. It increments or decrements the value depending on the result
print("Your turn:")
userInput = input()
computerChoice = random.choice(["R","P","S"])
if userInput == "R": #User Inputs R for Rock
if computerChoice == "R":
print("The computer chose Rock")
print("It's a Tie")
elif computerChoice == "P":
print("The computer chose Paper")
print("Computer Won")
compTally = compTally + 1
elif computerChoice == "S":
print("The computer chose Scissor")
print("You Won")
userTally = userTally + 1
elif userInput == "P": #User Inputs P for Paper
if computerChoice == "R":
print("The computer chose Rock")
print("You Won")
userTally = userTally + 1
elif computerChoice == "P":
print("The computer chose Paper")
print("It's a Tie")
elif computerChoice == "S":
print("The computer chose Scissor")
print("Computer Won")
compTally = compTally + 1
elif userInput == "S": #User Inputs S for Scissor
if computerChoice == "R":
print("The computer chose Rock")
print("Computer Won")
compTally = compTally + 1
elif computerChoice == "P":
print("The computer chose Paper")
print("You Won")
userTally = userTally + 1
elif computerChoice == "S":
print("The computer chose Scissor")
print("It's a Tie")
return(userTally,compTally)
def tryCount(): #The number of tries....
tryNum = 1
while tryNum < 11:
gameProcess(0, 0)
tryNum = tryNum + 1
tryCount()
print("You scored " + str(userTally))
print("The computer scored " + str(compTally))
if userTally > compTally:
print("CONGRATULATIONS, YOU WON.")
elif userTally < compTally:
print("Sorry, better luck next time.")
close = input()
if close == "Random Input.":
exit()
else:
exit()
You pass 0, 0 to gameProcess, which you treat as the scores within the function, and then return them modified, but you do not actually use the return value in the only place you call gameProcess (in tryCount), so the global userTally, compTally variables remain unchanged.
This is how you should change tryCount:
def tryCount(): #The number of tries....
global userTally, compTally
tryNum = 1
while tryNum < 11:
userTally,compTally=gameProcess(userTally,compTally)
tryNum = tryNum + 1

Python Function not running?

It's my first time here and I'm kinda panicking. I have an assignment to code Rock, Paper, Scissors in Python. (I use Python 3.1) and for some reason the function is not running...?
Here's the code:
hscore = 0
cscore = 0
tries = 0
#computer choice
rock = ("rock")
paper = ("paper")
scissors = ("scissors")
rps = (rock, paper, scissors)
cchoice = random.choice(rps)
choice = input("\nWhat do you choose? <rock, paper, scissors>: ")
tries +=1
def humanfunction():
if choice == "rock":
if cchoice == scissors:
print("Human wins this round.")
hscore +=1
if choice == "scissors":
if cchoice == paper:
print("Human wins this round.")
hscore +=1
if choice == "paper":
if cchoice == rock:
print("Human wins this round.")
hscore +=1
if cchoice == choice:
print("Tie.")
def compfunction():
if cchoice == scissors:
if choice == "paper":
print("Computer wins this round.")
cscore +=1
if cchoice == rock:
if choice == "scissors":
print("Computer wins this round.")
cscore +=1
if cchoice == paper:
if choice == "rock":
print("Computer wins this rounud.")
cscore +=1
if cchoice == choice:
print("Tie.")
def choose():
tries = 0
while 0 == 0:
choice = input("\nWhat do you choose? <rock, paper, scissors>: ")
tries +=1
print("\nHuman choice: ", choice)
print("Computer choice: ", cchoice)
print("Finished game number", tries)
if tries == 10:
print("Limit reached!")
break
humanfunction()
compfunction()
choose()
I've been trying to solve this for days now and for some reason, when I run the code, it doesn't show up who won. Help would be appreciated <3
EDIT:
here's what i get when i run the code:
output
the program is actually supposed to show this:
output2
Here is my take on your code.
The main reason it wasn't running is that your cscore variable was being referenced before it was initialized, because you had setup cscore as a global variable, but didn't declare it as a global variable in your function.
You also needed to import the random library
Also instead of doing 4 if/then statements I combined them into 1 if/then statement
EDIT: cleaned up the code a little more
EDIT 2: no more globals, avoid globals if possible
import random
def get_human_choice():
valid_choice = False
while not valid_choice:
choice = input("\nWhat do you choose? <rock, paper, scissors>: ")
if choice == 'rock' or 'paper' or 'scissors':
valid_choice = True
return choice
def get_comp_choice():
rps = ('rock', 'paper', 'scissors')
comp_choice = random.choice(rps)
return comp_choice
def human_winner(comp_choice):
print("The computer chooses: %s" % comp_choice)
print("Human wins this round.")
def comp_winner(comp_choice):
print("The computer chooses: %s" % comp_choice)
print("Computer wins this round.")
def stats(attempts, human_score, comp_scored, tie_score):
print("Finished game number: %s" % attempts)
print('Human Score: %s' % human_score)
print('Computer Score: %s' % comp_scored)
print('Ties: %s' % tie_score)
def play_game(human_score, comp_score, tie_score):
choice = get_human_choice()
comp_choice = get_comp_choice()
if choice == 'rock':
if comp_choice == 'scissors':
human_winner(comp_choice)
human_score += 1
else:
comp_winner(comp_choice)
comp_score += 1
elif choice == 'scissors':
if comp_choice == 'paper':
human_winner(comp_choice)
human_score += 1
else:
comp_winner(comp_choice)
comp_score += 1
elif choice == 'paper':
if comp_choice == 'rock':
human_winner(comp_choice)
human_score += 1
else:
comp_winner(comp_choice)
comp_score += 1
elif choice == comp_choice:
print("Tie.")
tie_score += 1
return human_score, comp_score, tie_score
if __name__ == '__main__':
tries = 1
h_score, c_score, t_score = 0, 0, 0
while tries <= 10:
h_score, c_score, t_score = play_game(h_score, c_score, t_score)
if tries == 10:
print("\nLimit reached!\n")
stats(tries, h_score, c_score, t_score)
break
else:
tries += 1

Categories

Resources