Guess Counting Control - python

I'm starting my studies in Python and I was assigned the Task to write code for a guessing game in which I have to control the total tries the player will have. I've described the functions, they're working (I believe...haha) but I can't make to "reset" the game when a wrong guess is input...
I wrote this:
guess_count = []
count_control = 1
def check_guess(letter,guess):
if guess.isalpha() == False:
print("Invalid!")
return False
elif guess.lower() < letter:
print("Low")
return False
elif guess.lower() > letter:
print("High")
return False
elif guess.lower() == letter:
print("Correct!")
return True
else:
print("anything")
def letter_guess(guess):
check_guess ('a',guess)
while len(guess_count) <= 3:
if check_guess == True:
return True
elif check_guess == False:
guess_count.append(count_control)
guess = input("Try again \n")
letter_guess(input("test: "))
UPDATE: I rewrote the code after some insights from other users and readings and came up with this:
class Game:
number_of_attempts = 3
no_more_attempts = "Game Over"
def attempt_down(self): #This will work as the counter of remaining lives.
self.number_of_attempts -= 1
print('Remaining Lives:',self.number_of_attempts)
def check_guess(self,letter):
"""
Requires
letter - a letter that has to be guessed
guess - a input from the user with the guessed letter
"""
while self.number_of_attempts > 0:
guess = input ("Guess the letter: ")
if guess.isalpha() == False:
print("Invalid!")
elif guess.lower() < letter:
self.attempt_down()
print("Low")
print("Try Again!")
elif guess.lower() > letter:
self.attempt_down()
print("High")
print("Try Again!")
elif guess.lower() == letter:
print("Correct!")
return True
print (self.no_more_attempts)
return False
game = Game()
"""
This is used to run the game.
Just insert the letter that
has to be guessed.
"""
teste1 = game.check_guess('g')
teste2 = game.check_guess('r')

The rub is in that you have a state of a game that you are tracking as global variables guess_count and count_control
This is an example of why python and other languages provide classes and objects:
class Game:
def __init__(self):
self.guess_count = []
self.count_control = 1
#staticmethod
def check_guess(letter, guess):
if guess.isalpha() == False:
print("Invalid!")
return False
elif guess.lower() < letter:
print("Low")
return False
elif guess.lower() > letter:
print("High")
return False
elif guess.lower() == letter:
print("Correct!")
return True
else:
print("anything")
def letter_guess(self, guess):
self.check_guess('a', guess)
while len(self.guess_count) <= 3:
if self.check_guess('a', guess) == True:
return True
elif self.check_guess('a', guess) == False:
self.guess_count.append(self.count_control)
guess = input("Try again \n")
game = Game()
game.letter_guess(input("test: "))
game = Game()
game.letter_guess(input("test: "))

Related

Guess the word - Python (more guesses than should be)

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")

Function and keyword argument

Why is my code not working? I am following UDEMY's 100 days of code and it is essentially the same as the instructor but I wanted to have keyword named arguments. First of all it's not printing the correct turn_left after each turn and it's not stopping the game.
from random import randint
EASY_LEVEL_TURNS = 10
HARD_LEVEL_TURNS = 5
def check_answer(user_guess, correct_answer, tracking_turns):
"""
Checks answer with guess.
"""
if user_guess > correct_answer:
print("Too high")
return tracking_turns - 1
elif user_guess < correct_answer:
print("Too low")
return tracking_turns - 1
elif user_guess == correct_answer:
print(f"Right the answer is {correct_answer}")
def set_difficulty(game_level):
"""
Sets game difficulty
"""
if game_level == "easy":
return EASY_LEVEL_TURNS
elif game_level == "hard":
return HARD_LEVEL_TURNS
def game():
"""
Setting up the game
"""
guess = 0
answer = randint(1, 100)
print("Welcome to the number guessing game!")
print("I am thinking of a number between 1 to 100")
level = input("How difficult would you like the game to be? Easy or Hard ").lower()
turn_left = set_difficulty(game_level=level)
while guess != answer:
print(f"You have {turn_left} attempts to guess the answer.")
guess = int(input("What is your guess? "))
answer_checked = check_answer(user_guess=guess, correct_answer=answer,
tracking_turns=turn_left)
if turn_left == 0:
print("You have ran out of terms")
return
game()
You can modify your game function like this, mainly by updating the turn_left value and setting the end-of-function condition
def game():
"""
Setting up the game
"""
guess = 0
answer = randint(1, 100)
print("Welcome to the number guessing game!")
print("I am thinking of a number between 1 to 100")
level = input("How difficult would you like the game to be? Easy or Hard ").lower()
turn_left = set_difficulty(game_level=level)
while guess != answer:
print(f"You have {turn_left} attempts to guess the answer.")
guess = int(input("What is your guess? "))
turn_left = check_answer(user_guess=guess, correct_answer=answer,
tracking_turns=turn_left)
if turn_left == 0:
print("You have ran out of terms")
return
elif not turn_left:
return

Python - How to return to previous function after calling another function?

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()

Last if condition is met, but code doesn't run

I am trying to make a small texted based game in which the player has to guess a word. If the secret word is water and the player guesses barge, the game should display -Ar-e, because those are the letters that are in common and since a is also in the correct place, it is shown as a capital letter.
from random import randint
def lingo():
fp = open("wordsEn.txt","r")
words = []
while True:
buffer = fp.readline()
if buffer == "":
break
else:
words.append(buffer[:-1])
secret_word = list(words[randint(0,len(words)-1)])
display_word = []
rand_num = randint(0,len(secret_word)-1)
compare_word = []
for i in range(len(secret_word)):
if i == rand_num:
display_word.append(secret_word[i])
compare_word.append(secret_word[i])
else:
display_word.append("-")
compare_word.append("-")
print(secret_word)
for i in range(5):
print(display_word)
print(compare_word)
if compare_word == secret_word:
break
else:
while True:
guess = input("guess: ")
if guess.isalpha() == False:
print("Only letters")
elif len(guess) > len(secret_word):
print("Too long")
elif len(guess) < len(secret_word):
print("Too short")
else:
break
for j in range(len(guess)):
print(guess[j])
print(guess[j] in secret_word)
if guess[j] in secret_word:
print("I am in")
if guess[j] == secret_word[j]:
display_word[j] == guess[j].upper()
compare_word[j] == guess[j]
else:
display_word[j] == guess[j]
else:
print("I am out")
continue
lingo()

While Loop Stopping

The Code is working, but after 2 trys of the code it will just stop, this is in the section of playagain() when im asking the yes or no question it will display the error but will stop after the trys am i doing it wrong?
import random
import time
import getpass
import sys
def game1():
number = (input("Please Enter Your 3 Digit Code e.g.(0 0 1): "))
if number.isnumeric(): #if its a number
counter = 0
x = True
L = 1
H = 100
while x == True:
time.sleep(0.5)
randomguess = random.randint(L,H)
print("%03d"%randomguess)
if randomguess > int(number):
print("The Passcode is lower")
H = randomguess
elif randomguess < int(number):
print("The Passcode is higher")
L = randomguess
else:
print("The Passcode is Equal")
x = False
counter = counter + 1
if randomguess == int(number):
print("Well Done the Prisoner has Escaped, he did it in",counter,"trys")
return playagain()
if counter > 9:
print("The Prisoner get it wrong",counter,"times he is locked in, Well Done Jailer")
return playagain()
else:
print("This is Invalid, Please Provide a 3 Digit Code")
#This is the Section just for Reference
def playagain():
playagain = input("Do you wish to play again (yes/no): ")
if playagain == "yes":
print("You chose to play again")
return game1()
elif playagain == "no":
print("So you let the prisoner escape, thats it your fired")
time.sleep(2)
print("Thanks for Playing")
time.sleep(2)
#quit("Thanks for Playing") #quit game at this point
sys.exit()
else:
print("Please choose a valid option")
return
Here's a cleaned-up version:
from random import randint
from time import sleep
DELAY = 0.5
def get_int(prompt, lo=None, hi=None):
while True:
try:
val = int(input(prompt))
if (lo is None or lo <= val) and (hi is None or val <= hi):
return val
except ValueError:
# not an int, try again
pass
def get_yn(prompt):
while True:
yn = input(prompt).strip().lower()
if yn in {"y", "yes"}:
return True
elif yn in {"n", "no"}:
return False
def game(tries=100):
code = get_int("Please enter a 3-digit number (ie 091): ", 0, 999)
lo, hi = 0, 999
for attempt in range(1, tries+1):
sleep(DELAY)
guess = randint(lo, hi)
if guess < code:
print("Guessed {:03d} (too low!)".format(guess))
lo = guess + 1
elif guess > code:
print("Guessed {:03d} (too high!)".format(guess))
hi = guess - 1
else:
print("{:03d} was correct! The prisoner escaped on attempt {}.".format(guess, attempt))
return True
print("The prisoner failed to escape!")
return False
def main():
while True:
game()
if get_yn("Do you want to play again? "):
print("You chose to play again.")
else:
print("Alright, bye!")
break
if __name__=="__main__":
main()
def game1():
number = (input("Please Enter Your 3 Digit Code e.g.(0 0 1): "))
if number.isnumeric(): #if its a number
counter = 0
x = True
L = 1
H = 100
while x == True:
time.sleep(0.5)
randomguess = random.randint(L,H)
print("%03d"%randomguess)
if randomguess > int(number):
print("The Passcode is lower")
H = randomguess
elif randomguess < int(number):
print("The Passcode is higher")
L = randomguess
else:
print("The Passcode is Equal")
x = False
counter = counter + 1
if randomguess == int(number):
print("Well Done the Prisoner has Escaped, he did it in",counter,"trys")
x = False
if counter > 9:
print("The Prisoner get it wrong",counter,"times he is locked in, Well Done Jailer")
x = False
else:
print("This is Invalid, Please Provide a 3 Digit Code")
playagain()
#This is the Section just for Reference
def playagain():
playagain = ""
while (playagain != "yes" or playagain != "no"):
playagain = input("Do you wish to play again (yes/no): ")
if playagain == "yes":
print("You chose to play again")
return game1()
elif playagain == "no":
print("So you let the prisoner escape, thats it your fired")
time.sleep(2)
print("Thanks for Playing")
time.sleep(2)
#quit("Thanks for Playing") #quit game at this point
sys.exit()
else:
print("Please choose a valid option")
game1()
See https://repl.it/B7uf/3 for a working example.
Games typically run in a game loop which you have implemented using while x = True. The gameloops exits when the game is over and then user is asked to restart it. The bugs you were experiencing were due to the gameloop prematurely exiting before the user could be asked to restart.
The code below above that problem. There are other things that could be updated to improve the flow, but will leave that to you.
Use try/catch blocks instead of boolean checks
Break the game loop out into a separate method

Categories

Resources