It is a Snake Water Gun Game in python
But My score is not counting
What is the problem
import random
Importing Random Module
chance = 1
human_point = 0
computer_point = 0
print("s for snake , w for water , g for gun ; you can use both uppercase or lowercase characters")
while (chance <= 10):
lst=["s","w","g"]
computer_choice=random.choice(lst)
human_point = 0
computer_point = 0
usr = input("Snake, Water & Gun : ")
usr = usr.lower()
if usr == computer_choice:
print("Tie\nNobody get points")
elif usr == "s" and computer_choice=="w":
print("You Win!")
human_point = human_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
elif usr == "s" and computer_choice=="g":
print("You Loose")
computer_point = computer_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
elif usr == "w" and computer_choice=="g":
print("You Win!")
human_point = human_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
elif usr == "w" and computer_choice=="s":
print("You Loose")
computer_point = computer_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
elif usr == "g" and computer_choice=="s":
print("You Win!")
human_point = human_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
elif usr == "g" and computer_choice=="w":
print("You Loose")
computer_point = computer_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
else:
print("Invalid Input")
continue
if attempts>10:
print("Game Over!")
print("No. of guesses left: {}".format(10 - chance))
chance = chance + 1
if computer_point < human_point:
print("All Over You Win! And Computer Loose")
print(f"Your score: {human_point} \nComputer's score: {computer_point}")
elif computer_point > human_point:
print("All Over Computer Win! And You Loose")
print(f"Your score: {human_point} \nComputer's score: {computer_point}")
else:
print("It Was A Tie")
print(10 - chance, "no. of guesses left")
chance = chance + 1
But if computer wins the computer score = 1 and my score = 0 and if I win then my score = 1 and computer score = 0
Why it is not counting score
Please Suggest me the answer What I am doing wrong
Please Help
You set the score of both you and your computer to 0 at the beginning of your while loop. This would mean that for every iteration, your scores will be 0 so when you do a command such as: computer_point = computer_point + 1 or player_point = player_point + 1, those statements will always evaluate to 0 + 1, hence why it doesn't actually "update"
you repeated human_point = 0, computer_point = 0 code under while.
you should probably erase that part
human_point = 0
computer_point = 0
print("s for snake , w for water , g for gun ; you can use both uppercase or lowercase characters")
while (chance <= 10):
lst=["s","w","g"]
computer_choice=random.choice(lst)
human_point = 0 <- erase this part
computer_point = 0 <- erase this part
Here's the full code you'll need. I removed chance = chance +1 repeating twice and updated the logic to only display the final result if chance = 10. Finally, I moved the human_point = 0 and computer_point = 0 to above the while loop so you don't constantly reset the score.
import random
chance = 1
human_point = 0
computer_point = 0
print("s for snake , w for water , g for gun ; you can use both uppercase or lowercase characters")
while (chance <= 10):
lst=["s","w","g"]
computer_choice=random.choice(lst)
usr = input("Snake, Water & Gun : ")
usr = usr.lower()
if usr == computer_choice:
print("Tie\nNobody get points")
elif usr == "s" and computer_choice=="w":
print("You Win!")
human_point = human_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
elif usr == "s" and computer_choice=="g":
print("You Loose")
computer_point = computer_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
elif usr == "w" and computer_choice=="g":
print("You Win!")
human_point = human_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
elif usr == "w" and computer_choice=="s":
print("You Loose")
computer_point = computer_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
elif usr == "g" and computer_choice=="s":
print("You Win!")
human_point = human_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
elif usr == "g" and computer_choice=="w":
print("You Loose")
computer_point = computer_point + 1
print(f"You Choosed {usr} Computer Choosed {computer_choice} ")
else:
print("Invalid Input")
continue
if attempts>10:
print("Game Over!")
print("No. of guesses left: {}".format(10 - chance))
chance = chance + 1
if chance == 10 and computer_point < human_point:
print("All Over You Win! And Computer Loose")
print(f"Your score: {human_point} \nComputer's score: {computer_point}")
elif chance == 10 and computer_point > human_point:
print("All Over Computer Win! And You Loose")
print(f"Your score: {human_point} \nComputer's score: {computer_point}")
elif chance == 10 and computer_point == human_point:
print("It Was A Tie")
print(10 - chance, "no. of guesses left")
Related
I am trying to make a game where the user inputs a word with only three guesses available, but instead it keeps allowing four guesses which I don't want.
When i input a word and my guess_count reaches 3, i am supposed to be sent this msg "You have no more guesses, you lose!" then ask if i want to retry but instead it lets me play one more time thereby exceeding the guess_limit
Here is my code
secret_word = "loading"
guess_word = ""
guess_count = 0
guess_limit = 3
end = False
print("Welcome to the guessing game\nYou have 3 guesses")
guess_word = input("Enter a word: ")
def end_msg(msg):
print(msg)
retry = input("Do you want to play again? ")
if (retry == "yes") :
global end, guess_word, guess_count
end = False
guess_word = ""
guess_count = 0
print("Welcome to the guessing game\\nYou have 3 guesses")
guess_word = input("Enter a word: ")
else:
end = True
while (not(end)) :
if (guess_word != secret_word and guess_count \< guess_limit):
guess_count += 1
print("Incorrect!")
print("You have " + str(3 - guess_count) + " left!")
guess_word = input("Try again: ")
elif (guess_count == 3):
end_msg("You have no more guesses, you lose!")
else:
end_msg("Correct, you win")
I see your query already answered above, In case you want I have adapted your code to make it more organized and structured into two functions
playagain - which asks after winning/losing if the user wants to play the game again
play - the actual program to play the game
I removed some redundancies like end = False variable you used and could have also removed some other variables like guess_limiter (by just assigning the guess limit value in the actual program) but I wanted to retain your code as much as possible in case for your understanding, hope this helps
def playagain():
play_again = input("Do you want to play again? (y/n) ")
if play_again == 'y':
return play()
elif play_again == 'n':
print("Thank you for playing")
else:
print("incorrect input please try again")
playagain()
def play():
secret_word = "loading"
guess_word = ""
guess_count = 1
guess_limit = 3
print("Welcome to the guessing game\nYou have 3 guesses")
while (guess_count != guess_limit + 1):
guess_word = input("Enter a word: ")
if guess_word == secret_word:
print("Correct, you win")
playagain()
break
elif guess_count == guess_limit:
print("You have no more guesses, you lose!")
playagain()
break
else:
print("Incorrect!")
print("You have " + str(3 - guess_count) + " left!")
guess_count += 1
play()
You are getting this bug because you wrote guess_limit = 3. You know Programs count from 0, so you need to enter 1 less from your desire try. It should be guess_limit = 2.
And also you wrote elif (guess_count == 3) :, thats mean if guess_count == 3 your will get "You have no more guesses, you lose!" even, user put the right answer. so it should be
elif (guess_word != secret_word and guess_count == 2):
so your final code should be:
secret_word = "loading"
guess_word = ""
guess_count = 0
guess_limit = 2
end = False
print("Welcome to the guessing game\nYou have 3 guesses")
guess_word = input("Enter a word: ")
def end_msg (msg) :
print(msg)
retry = input("Do you want to play again? ")
if (retry == "yes") :
global end, guess_word, guess_count
end = False
guess_word = ""
guess_count = 0
print("Welcome to the guessing game\\nYou have 3 guesses")
guess_word = input("Enter a word: ")
else:
end = True
while (not(end)) :
if (guess_word != secret_word and guess_count < guess_limit) :
guess_count += 1
print("Incorrect!")
print("You have " + str(3 - guess_count) + " left!")
guess_word = input("Try again: ")
elif (guess_word != secret_word and guess_count == 2) :
end_msg("You have no more guesses, you lose!")
else:
end_msg("Correct, you win")
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.
Hi all programming masters! Im working on a python guessing game and want to change the format of my print to file from "name: win 0: loss 0: guess 0", to "Name | Win or loss (not both) | number of guesses". Im not sure how to make it print the win OR loss, do i need another if statement to print to the txt file?
import random
print("Number guessing game")
name = input("Hello, please input your name: ")
win = 0
loss = 0
guesses = 0
diceRoll = random.randint(1, 6)
if diceRoll == 1:
print("You have 1 guess.")
if diceRoll == 2:
print("You have 2 guesses.")
if diceRoll == 3:
print("You have 3 guesses.")
if diceRoll == 4:
print("You have 4 guesses.")
if diceRoll == 5:
print("You have 5 guesses.")
if diceRoll == 6:
print("You have 6 guesses.")
elif diceRoll != 1 and diceRoll != 2 and diceRoll != 3 and diceRoll != 4 and diceRoll != 5 and
diceRoll != 6:
print("Invalid input!")
number = random.randint(1, 3)
chances = 0
print("Guess a number between 1 and 100:")
while chances < diceRoll:
guess = int(input())
if guess == number:
print("Congratulation YOU WON!!!")
win += 1
guesses = guesses + 1
break
elif guess < number:
print("Your guess was too low")
guesses = guesses + 1
else:
print("Your guess was too high")
guesses = guesses + 1
chances += 1
else:
print("YOU LOSE!!! The number is", number)
loss += 1
print(name)
print("win: "+str(win))
print("loss: "+str(loss))
stat = open("Statistics.txt", "a")
stat.write(name + ":" + " win: "+str(win) + " loss: " +str(loss) +" guesses: "+str(guesses)),
stat.close()
You can solve the critical part using the ternary statement, an "if-then-else" expression, like this:
result = "Win" if win == 1 else "Loss"
stat.write((name + ":" + result + " guesses: "+str(guesses))
Beyond this, I strongly recommend that you look up "Python output format", so you can improve your range of expression. You won't have to keep doing string construction for your output statements.
so i don't understand why my counter doesn't reset when i'm restarting the game, also, i believe its got something to do with the fact that i have no builder?
any help will be highly appriciated!
import random
import sys
from termcolor import colored
class RPS():
def show_welcome():
print(colored("Welcome to RPS !!!", 'blue'))
print(colored("RULES:",'yellow'), colored("*", 'red'), "Rock Beats Scissors",colored("*", 'red'))
print(colored(" *", 'grey'),"Scissors beats Paper", colored("*", 'grey'))
print(colored(" *", 'magenta'), "Paper beats Rock", colored("*", 'magenta'))
print(colored("!---=== GOOD LUCK ===---! ", 'green'))
def round_number():
x = 10
user_input = ""
while True:
try:
user_input = int(input("# Number Of Rounds? [Max 10]: "))
except:
print("Invalid Input!")
RPS.round_number()
if user_input < 1 or user_input > x:
print("Max 10 rounds!")
rundnum = 0
RPS.round_number()
else:
return user_input
def restart():
user_input = ""
try:
user_input = input("Would you like to restart? [Y/n]")
except:
print("\nInvalid Input! ")
RPS.show_welcome()
if user_input is "y" or user_input is "Y":
rounds = 0
RPS.round_number()
elif user_input is "n" or user_input is "N":
print(colored("Thanks for playing! Goodbye!", 'green'))
sys.exit()
else:
print("Bullshit input!")
RPS.restart()
def game():
player = 0
rounds = 0
moves = ['Rock', 'Paper', 'Scissors',]
r = rundnum
while rounds < r:
rounds += 1
comp = random.choice(moves)
print(colored("Choose : ", 'green'), colored("1)Rock", 'red'), colored("2)Paper", 'yellow'),
colored("3)Scissors", 'grey'))
try:
player = int(input("What's Your Guess? "))
except:
print(colored("No Valid Input! Restarting Game...", 'red'))
RPS.game()
if (player is 1 and comp is 'Rock') or (player is 2 and comp is 'Paper') \
or (player is 3 and comp is 'Scissors'):
print("Player Choose: {}".format(moves[player - 1]))
print("Computer Choose: {}".format(comp))
print(colored("*** Round #: {} | Result: It's A Draw !! *** ", 'blue').format(rounds))
if rounds >= r:
print(colored("*** GAME OVER *** ", 'grey'))
rounds = 0
RPS.restart()
else:
continue
elif (player is 1 and comp is 'Paper') or (player is 2 and comp is 'Scissors') \
or (player is 3 and comp is 'Rock'):
print("Player Choose: {}".format(moves[player - 1]))
print("Computer Choose: {}".format(comp))
print(colored("*** Round #: {} | Result: Player Lose !! *** ", 'blue').format(rounds))
if rounds >= r:
print(colored("*** GAME OVER *** ", 'grey'))
rounds = 0
RPS.restart()
else:
continue
elif (player is 1 and comp is 'Scissors') or (player is 2 and comp is 'Rock') \
or (player is 3 and comp is 'Paper'):
print("Player Choose: {}".format(moves[player - 1]))
print("Computer Choose: {}".format(comp))
print(colored("*** Round #: {} | Result: Player Wins !! *** ", 'blue').format(rounds))
if rounds >= r:
print(colored("*** GAME OVER *** ", 'grey'))
rounds = 0
RPS.restart()
else:
continue
else:
print(colored("No valid input!", 'red'))
RPS.game()
if __name__ == '__main__':
#rounds = ""
while True:
RPS.show_welcome()
rundnum = RPS.round_number()
RPS.game()
rounds = 0
rundnum = 0
The problem occurs when you call RPS.game() within the function itself. This creates a situation whereby all the variables reset, as defined by the function .game(). To avoid this, you could give the function default parameters and then call the function (within itself) with those parameters.
Example (using part of the original code):
def game(player=0, rounds=0):
# player = 0
# rounds = 0
moves = ['Rock', 'Paper', 'Scissors',]
r = rundnum
while rounds < r:
rounds += 1
comp = random.choice(moves)
print(colored("Choose : ", 'green'), colored("1)Rock", 'red'), colored("2)Paper", 'yellow'),
colored("3)Scissors", 'grey'))
try:
player = int(input("What's Your Guess? "))
except:
print(colored("No Valid Input! Restarting Game...", 'red'))
RPS.game(player, rounds) # Here's the magic...
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