Sometimes when I pick odd, and the result is odd it gives me that the computer won but it's wrong.
Also the scores aren't working, the score always prints 1.
import random
options = ["odd", "even"]
user_wins = 0
comp_wins = 0
while True:
user_answer = input("Choose odd or even. ").lower()
if user_answer not in options:
print("Try again.")
quit()
user_answer2 = input("Choose a number larger than zero. ")
if user_answer2.isdigit():
user_answer2 = int(user_answer2)
if user_answer2 <= 0:
print("Type a number larger than zero. ")
quit()
else:
print("Type a number next time.")
quit()
comp_pick = random.randint(0, 10)
if user_answer == "odd":
print("Computer picked even and its number is", comp_pick)
else:
print("Computer picked odd and its number is", comp_pick)
total = user_answer2 + comp_pick
if total % 2 == 0:
result = "even"
else:
result = "odd"
if result == "even" and user_answer == "even":
print("The result is", total, "You won!")
user_wins =+ 1
else:
print("The result is", total, "Computer won!")
comp_wins =+ 1
print("Your score:", user_wins)
print("Computer score:", comp_wins)
You can't win if you choose odd because of your last if statement:
if result == "even" and user_answer == "even":
which only lets you win if you choose even. You could try changing it to
if result == user_answer:
comp_wins =+ 1 is the same as comp_wins = +1 which is the same as comp_wins = 1. You must have meant:
comp_wins += 1
Same applies to user_wins =+ 1.
Related
My code is executing mostly how I want it to but when it prints my values from my function it is doubling the amount of times that the function code is ran. I only want 10 interations but it is printing 20. I would just lower the range to 5 but then it throws off my final score in my block of code that displays who won the most rounds. How can I stop the function code from running twice? TIA
import random
import time
answer = input("Play the game?")
winsP1 = 0
winsP2 = 0
def determineWinner(winsP1, winsP2):
for wins in range(10):
from random import randint
player1 = randint(1,10)
player2 = randint(1,10)
#time.sleep(1)
print("Player 1:", player1)
#time.sleep(1)
print("Player 2:", player2)
#time.sleep(1)
if player1==player2:
print("This round is a tie!")
winsP1 += 1
winsP2 += 1
elif player1>player2:
print("Player 1 wins this round!")
winsP1 += 1
elif player2>player1:
print("Player 2 wins this round!")
winsP2 += 1
return winsP1, winsP2
winsP1, winsP2 = determineWinner(winsP1 = winsP1, winsP2 =
winsP2)
if answer == "y" or answer == "Y" or answer == "yes" or answer == "Yes":
determineWinner(winsP1, winsP2)
if winsP1>winsP2:
print()
print("The score totals are:")
print("Player one: " + str(winsP1))
print("Player two: " + str(winsP2))
print()
print("Player 1 wins with a score of", str(winsP1) + "!")
print()
elif winsP2>winsP1:
print()
print("The score totals are:")
print("Player One: " + str(winsP1))
print("Player two: " + str(winsP2))
print()
print("Player 2 wins with a score of", str(winsP2) + "!")
print()
elif winsP1==winsP2:
print()
print("The score totals are:")
print("Player one: " + str(winsP1))
print("Player two: " + str(winsP2))
print()
print("It's a tie!")
print()
It's running 20 times since determineWinner is called twice. Once here winsP1, winsP2 = determineWinner(winsP1 = winsP1, winsP2 = winsP2) and the next time within the if block. You could set winsP1 = winsP2 = 0 instead so as to have it start at a neutral state.
Not entirely sure if you'd like to call the function twice; But that's the main reason for the 20 prints you see.
import time
answer = input("Play the game?")
winsP1 = 0
winsP2 = 0
def determineWinner(winsP1, winsP2):
for wins in range(10):
from random import randint
player1 = randint(1,10)
player2 = randint(1,10)
#time.sleep(1)
print("Player 1:", player1)
#time.sleep(1)
print("Player 2:", player2)
#time.sleep(1)
if player1==player2:
print("This round is a tie!")
winsP1 += 1
winsP2 += 1
elif player1>player2:
print("Player 1 wins this round!")
winsP1 += 1
elif player2>player1:
print("Player 2 wins this round!")
winsP2 += 1
return winsP1, winsP2
winsP1 = winsP2 = 0
if answer == "y" or answer == "Y" or answer == "yes" or answer == "Yes":
winsP1, winsP2 = determineWinner(winsP1, winsP2)
if winsP1>winsP2:
print()
print("The score totals are:")
print("Player one: " + str(winsP1))
print("Player two: " + str(winsP2))
print()
print("Player 1 wins with a score of", str(winsP1) + "!")
print()
elif winsP2>winsP1:
print()
print("The score totals are:")
print("Player One: " + str(winsP1))
print("Player two: " + str(winsP2))
print()
print("Player 2 wins with a score of", str(winsP2) + "!")
print()
elif winsP1==winsP2:
print()
print("The score totals are:")
print("Player one: " + str(winsP1))
print("Player two: " + str(winsP2))
print()
print("It's a tie!")
print()
I am having trouble finding a way to allow my Python project to accept a non-integer value and not crash. My intention is that when the user inputs a non-integer value or any value other than the ones assigned by the random sampkle, the game will prompt the function "repeatr()" which will tell them to input the value again.
I've put in the entire solution, but the most relevant sections are in bold and it's that particular section that I want to allow to prompt the repeatr() function instead of crashing
import random
user_wins = 0
user_draws = 0
user_losses = 0
rounds = 0
def closr():
quit()
def repeatr():
print("That is not a valid input. Please input a correct value.")
**def promptr():
print("Please select an input from the following options.")**
options = [5, 4, 3, 2, 1]
randomlist = random.sample(range(1, 5), 3)
randomr = randomlist
x=1
while x == 1:
user_input = int(input("Type 5/4/3/2/1 or Q to quit."))
if user_input in options:
x=2
elif user_input != options:
repeatr()
continue
elif user_input == "q":
closr()
**y=1
while rounds < 10:
promptr()
player_choice = int(input(randomlist))
npc = random.randint(1,5)
if player_choice in randomr:
print("Your opponent has drawn: ", npc)
y=2
else:
repeatr()
continue**
if npc > int(player_choice):
print("You have been defeated this round.")
user_losses = user_losses + 1
print("The score is:" , user_wins , ":" , user_losses)
rounds = rounds + 1
elif npc < player_choice:
print ("You have won this round.")
user_wins = user_wins + 1
print ("The score is:" , user_wins , ":" , user_losses)
rounds = rounds + 1
elif npc == player_choice:
print ("You have drawn this round.")
user_draws = user_draws + 1
print ("The score is:" , user_wins , ":" , user_losses)
rounds = rounds + 1
rounds = 10
if user_losses < user_wins:
print("You have won the game!")
elif user_losses > user_wins:
print("You have lost this game. Better luck next time!")
elif user_losses == user_wins:
print("The game has ended in a draw.")
print("the number of wins you had was:" , user_wins)
print("the number of draws you had was:" , user_draws)
print("the number of losses you had was:" , user_losses)
print("The final score was (Player vs CPU):" , user_wins, ":" , user_losses)
u=1
while u == 1:
resu=input("Press Q to quit the game.")
if resu=="q":
closr()
I hope the question makes sense.
Heres the copy of my code :) this game is part of my personal activity.
so after purchasing a clue (from: def game_hints) i want to return to def Game_process.
import random
SCORE = 0
ROUNDS = 1
def player_stats():
print(f"SCORE: {SCORE} | ROUNDS: {ROUNDS}")
def game_hints(USER_GUESS, Mystery_NUM):
print("Would you like purchase a hint for 5 points? [1/2]: ")
USER_HINT = int(input())
global SCORE
if USER_HINT == 1:
SCORE= SCORE - 5
if USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 0:
print("Mystery Num is even and try a smaller guess")
elif USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a smaller guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a larger guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a larger guess")
def Game_Process():
global ROUNDS
while True:
if ROUNDS <= 10:
Mystery_NUM = random.randrange(10)
print(Mystery_NUM) #remove before final product
print("Guess the num [1-10]: ")
USER_GUESS = int(input())
if USER_GUESS == Mystery_NUM:
print("\nGood Job! +5 Coins!")
global SCORE
SCORE = SCORE + 10
ROUNDS += 1
player_stats()
else:
print("Wrong! Try Again")
game_hints(USER_GUESS, Mystery_NUM)
else:
print("Game Over!")
Game()
def Game():
user_opt = input("\"Welcome to Guess Game\" \nPress [Y] to Play or [N] to Exit: ").lower()
if user_opt == "n":
print("Good bye!")
exit()
elif user_opt == "y":
Game_Process()
else:
print("Invalid Input! [1/2]")
Game()
Game()
As shown below, this is the fuction for the hints. I was able to call this function but the only problem is that the after this fuction is done, it changes the Myster_Num.
def game_hints(USER_GUESS, Mystery_NUM):
print("Would you like purchase a hint for 5 points? [1/2]: ")
USER_HINT = int(input())
global SCORE
if USER_HINT == 1:
SCORE= SCORE - 5
if USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a smaller guess")
elif USER_GUESS > Mystery_NUM and Mystery_NUM % 2 == 1:
print("Secret Num is odd and try a smaller guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 0:
print("Secret Num is even and try a larger guess")
elif USER_GUESS < Mystery_NUM and Mystery_NUM % 2 == 1:
print("Mystery Num is odd and try a larger guess")
First, you must remove the else statement in the game_hints function because it restarts a full GameProcess and therefore indeed recompute a mysterious number.
Then, when you exit game_hints and come back to GameProcess, you must not come back to the big loop because it will indeed recompute a mysterious number. The solution is to have an inner loop inside each round that you exit only if the player guessed the correct value using the break keyword.
def Game_Process():
SCORE = 0
ROUNDS = 1
while True:
if ROUNDS <= 10:
Mystery_NUM = random.randrange(10)
print(Mystery_NUM) # remove before final product
while True:
print("Guess the num [1-10]: ")
USER_GUESS = int(input())
if USER_GUESS == Mystery_NUM:
print("\nGood Job! +5 Coins!")
SCORE = SCORE + 10
ROUNDS += 1
player_stats()
break
else:
print("Wrong! Try Again")
game_hints(USER_GUESS, Mystery_NUM)
else:
print("Game Over!")
Game()
In my option 2 section of my code my loop isn't functioning properly and i can not figure out why. It keeps asking for an input again. I tried moving the input outside of the loop but that didn't work either.
import random
def display_menu():
print("Welcome to my Guess the Number Program!")
print("1. You guess the number")
print("2. You type a number for the computer to guess.")
print("3. Exit")
print()
def main():
display_menu()
option = int(input("Enter a menu option: "))
User pics a number randomly generated by the computer until user gets
the correct answer.
Outputs user guesses and number of attempts until guessed correct
if option == 1:
number = random.randint(1,10)
counter = 0
while True:
try:
guess = input("Guess a number between 1 and 10: ")
guess = int(guess)
print()
if guess < 1 or guess > 10:
raise ValueError()
counter += 1
if guess > number:
print("Too high.")
print()
elif guess < number:
print("Too low.")
print()
else:
print("You guessed it!")
print("You guessed the number in", counter, "attempts!")
break
except ValueError:
print(guess, "is not a valid guess")
print()
Option 2., User enters a number for the computer to guess.
Computer guesses a number within the range given.
Outputs computer guesses and number of guesses until computer gets
the correct number.
if option == 2:
print("Computer guess my number")
print()
while True:
try:
my_num = input("Enter a number between 1 and 10 for the computer to guess: ")
my_num = int(my_num)
counter = 0
counter += 1
print()
comp = random.randint(1,10)
if my_num < 1 or my_num > 10:
raise ValueError()
if comp > my_num:
print("Computer guessed", comp,"to High")
elif comp < my_num:
print("Computer guessed", comp,"to Low")
else:
print("Computer guessed the right number!" , comp)
print("Computer guessed the right number in", counter, "attempts!")
break
except ValueError:
print(my_num, "is not a valid entry")
print()
continue
"""
Ends game
"""
if option == 3:
print("Goodbye")
if __name__ == '__main__':
main()
You should ask for input before the loop. counter should be initialised before the loop too.
if option == 2:
print("Computer guess my number")
print()
# these three lines will be run once before the loop
my_num = input("Enter a number between 1 and 10 for the computer to guess: ")
my_num = int(my_num)
counter = 0
while True:
try:
comp = random.randint(1,10)
counter += 1
print()
if my_num < 1 or my_num > 10:
raise ValueError()
if comp > my_num:
print("Computer guessed", comp,"to High")
elif comp < my_num:
print("Computer guessed", comp,"to Low")
else:
print("Computer guessed the right number!" , comp)
print("Computer guessed the right number in", counter, "attempts!")
break
except ValueError:
print(my_num, "is not a valid entry")
print()
continue
As an aside, instead of randomly guessing, you can improve the computer's guessing by using binary search, where the number of tries has an upper bound.
Whenever it takes me several tries to beat the game, it always says the number_of_guesses is 1, which isn't true. What have I done wrong?
My code:
import random
print("Welcome to Rock, Paper, Scissors. \nYou will be going up against the computer, who will randomly",
"choose an object to duel you with!")
user_win = False
while not user_win:
user_guess = input("\nChoose either Rock, Paper or Scissors: ")
user_guess = user_guess.lower()
if user_guess != "rock" and user_guess != "paper" and user_guess != "scissors":
print("You didn't enter a valid guess. Try again, please.")
user_guess = input("\nChoose either Rock, Paper or Scissors: ")
user_guess = user_guess.lower()
computer_guess = random.randint(1,3)
if computer_guess == 1:
computer_guess = "rock"
elif computer_guess == 2:
computer_guess = "paper"
else:
computer_guess = "scissors"
print("Your guess:", user_guess.capitalize(), "\nComputer guess:", computer_guess.capitalize())
number_of_guesses = 1
if user_guess == computer_guess:
print("\nThe game is a tie. You guessed", user_guess, "and so did the computer.")
number_of_guesses += 1
user_win = False
elif (user_guess == "rock" and computer_guess == "scissors") or (user_guess == "paper" and computer_guess == "rock"):
print("\nCongratulations! You have beaten the computer by playing", user_guess.capitalize(), "while the computer played", computer_guess.capitalize())
user_win = True
number_of_guesses += 1
else:
print("\nDamn! The computer won by playing", computer_guess.capitalize(), "while you played", user_guess.capitalize())
user_win = False
number_of_guesses += 1
if number_of_guesses == 1:
print("\nYou won, and it only took you %d try!" % number_of_guesses)
else:
print("\nYou won, and it only took you %d tries!" % number_of_guesses)
input("\nPress enter to exit the program.")
I think that's formatted correctly. It's not easy to put code in here. Thank you!
You are always setting numbers of guesses equal to 1 inside your loop:
print("Your guess:", user_guess.capitalize(), "\nComputer guess:", computer_guess.capitalize())
number_of_guesses = 1 # setting here
Set the number_of_guesses outside the while loop
First of all in the while loop you always initialize number_of_guesses = 1 on every run. That is why this will always be 1 in each run.
Take this initialization before the while.