How to add a while loop counter to this code - python

I believe that this code is fairly self-explanatory but I am confused as to how to implement a counter.
The code is for a guessing game
from random import randint
computer_guess = randint(0,10)
def endGame(computer_guess):
print("Cheerio")
finalOption = True
import sys
if 10/5 == 2:
sys.exit()
def menu(computer_guess):
finalOption = False
while not finalOption:
print("Welcome to this number guessing game sir")
print("You must see if you can guess my number...")
mainGame()
def mainGame():
anyInput = int(input('Give me your guess'))
if (anyInput == computer_guess):
print ("Well done, you got my number")
finalOption = True
endGame(computer_guess)
elif (computer_guess > anyInput):
print ("You need to go higher")
mainGame()
elif (anyInput > computer_guess):
print ("You need to go lower")
mainGame()
menu(computer_guess)
Apologies for the gaps in the code

try the following pattern
count = 1
while true:
guess = get input...
if guess > answer:
say something...
else if guess < answer:
say something...
else:
exit with count...
count++

I find that a class structure like
class MyGame:
def __init__(self, options):
# set up initial game state
def play(self):
# play one full game;
# return WIN or LOSE when the game is over
def one_round(self):
# play one round;
# return WIN, LOSE if the game is over,
# or CONTINUE to keep playing
makes it easier to think about a game. This becomes something like
from random import randint
LOSE, WIN, CONTINUE = 0, 1, 2
class GuessingGame:
def __init__(self, low=1, high=10, guesses=10):
self.low = low
self.high = high
self.prompt = "\nGive me your guess [{}-{}]: ".format(low, high)
self.turn = 0
self.guesses = guesses
self.target = randint(low, high)
def play(self):
print("Welcome to this number guessing game sir")
print("You must see if you can guess my number...")
while self.turn < self.guesses:
result = self.get_guess()
if result == WIN:
return WIN
# ran out of guesses!
print("Sorry, you lost! My number was {}.".format(self.target))
return LOSE
def get_guess(self):
self.turn += 1
# repeat until you get a valid guess
while True:
try:
num = int(input(self.prompt))
if self.low <= num <= self.high:
break
except ValueError:
print("It has to be an integer!")
# find the result
if num < self.target:
print("You need to go higher!")
return CONTINUE
elif num == self.target:
print("Well done, you guessed the number.")
return WIN
else:
print("You need to go lower!")
return CONTINUE
def main():
results = [0, 0]
while True:
result = GuessingGame().play()
results[result] += 1
print("\nYou have {} losses and {} wins.".format(*results))
yn = input("Do you want to play again [y/n]? ").strip().lower()
if yn in ["n", "no"]:
break
if __name__=="__main__":
main()

Related

Print something outside of for loop for last iteration

I started to make a number guessing game. Here is the code I wrote:
import random
print('Hello what is your name?')
NamePlayer = input()
print('Well, ' + NamePlayer + ' I am thinking of a number between 1 and 20')
randomnumber = random.randint(1, 20)
print('Take a guess.')
for Guesstaken in range(1, 7):
Guess = int(input())
if Guess < randomnumber:
print('Too low, take another guess!')
elif Guess > randomnumber:
print('Too high, take another guess!')
else:
break
if Guess == randomnumber:
print('Damnn are you a mindreader, ' + NamePlayer)
else:
print('You are wrong')
The problem is that for the last iteration I get the print for the condition that is met inside of the for loop, as well as the print outside of the loop. Of course I don't want the print 'Too high, take another guess' or something like that if it is the last guess.
How can I only print 'Damnn are you a mindreader' or 'You are wrong' for the last iteration?
You can store number of guesses in a var like N.
N = 7
for Guesstaken in range(1, N):
Guess = int(input())
if Guesstaken == N - 1:
break
if Guess < randomnumber:
print('Too low, take another guess!')
elif Guess > randomnumber:
print('Too high, take another guess!')
else:
break
if Guess == randomnumber:
print('Damnn are you a mindreader, ' + NamePlayer)
else:
print('You are wrong')
It would be better if you had a line to print rules of game, I wasn't sure how many tries you wanted to give. your program counted from 1.....6 and it was just 6 steps so i made it loop 7 times as this
for Guesstaken in range(7):
Guess = int(input())
if Guess < randomnumber and Guesstaken<6:
print('Too low, take another guess!')
elif Guess > randomnumber and Guesstaken<6:
print('Too high, take another guess!')
else:
break
import random
number_of_trials=6
c=0
print('Hello what is your name?')
NamePlayer = input()
print('Well, ' + NamePlayer + ' I am thinking of a number between 1 and 20')
randomnumber = random.randint(1, 20)
print('Take a guess.')
for Guesstaken in range(1, number_of_trials+1):
c+=1
Guess = int(input())
if Guess < randomnumber and c!=number_of_trials:
print('Too low, take another guess!')
elif Guess > randomnumber and c!=number_of_trials:
print('Too high, take another guess!')
else:
break
if Guess == randomnumber:
print('Damnn are you a mindreader, ' + NamePlayer)
else:
print('You are wrong')
here c is a counter to see if the number_of_trials are reached. It will help in not displaying 'Too high, take another guess' or something like that if it is the last guess.
The main loop in your code is to be repeated while there is going to be another guess.
You also want to only print out the "too high" or "too low" messages if there is another guess going to happen.
An alternative is to test for a correct answer or too many guesses and change the state of another_guess before those messages are printed.
For example:
import random
NamePlayer = input('Hello what is your name? ')
print(f'Well, {NamePlayer} I am thinking of a number between 1 and 20')
randomnumber = random.randint(1, 20)
print('Take a guess.')
another_guess = True
guesses = []
while another_guess:
Guess = int(input())
guesses.append(Guess)
if Guess == randomnumber:
another_guess = False
if len(guesses) == 6:
another_guess = False
if another_guess and Guess < randomnumber:
print('Too low, take another guess!')
elif another_guess and Guess > randomnumber:
print('Too high, take another guess!')
if Guess == randomnumber:
print('Damnn, are you a mind reader, ' + NamePlayer)
else:
print('You are wrong')
If you had ambition to take this game and add graphical user interface it might be beneficial to separate out the UI, game state, game logic.
For example:
"""Guess a number game"""
from dataclasses import dataclass, field
from enum import IntEnum
import random
def main():
cli = UI()
player_name = cli.ask_name()
game = Game(Scoreboard(), cli, player_name)
game.play()
class GuessState(IntEnum):
"""Possible states of guess"""
LOW = -1
CORRECT = 0
HIGH = 1
class UI:
"""Handle UI interaction to make it easy to move to different UI"""
def ask_name(self):
"""Ask the players name"""
return input("Hello, what is your name? ")
def ask_guess(self, max_choice):
"""
Ask for guess value. Check input is a valid value before returning
"""
while True:
try:
choice = int(input("Enter guess: "))
if 0 < choice < max_choice + 1:
return choice
print(f"Please enter a guess between 1 and {max_choice}")
except ValueError:
print("You entered something other than a number")
def display_welcome(self, player_name, max_choice, max_guesses):
"""Welcome message and rules"""
print(f"Welcome, {player_name}")
print(f"I am thinking of a number between 1 and {max_choice}.")
print(f"Can you guess it within {max_guesses} guesses?")
def display_turn_result(self, value, result):
"""Display the guessed value and if they are too high or low"""
if result == GuessState.LOW:
print(f"{value} is lower than the number I am thinking of!")
elif result == GuessState.HIGH:
print(f"{value} is higher than the number I am thinking of!")
def display_goodbye(self, player_name, scoreboard):
"""Game over message"""
if scoreboard.any_correct_guesses():
print(f"{player_name} are you a mindreader!")
else:
print(f"You didn't get the number, {player_name}. Please try again")
#dataclass
class Scoreboard:
"""Keep track of the guesses and if active for more guesses"""
guesses: list = field(default_factory=list)
game_active: bool = True
def add_guess(self, choice, state):
"""Add the value and state of a guess"""
self.guesses.append((choice, state))
def get_last_guess(self):
"""Return the value and state of the last guess"""
return self.guesses[-1]
def get_guess_count(self):
"""Return how many guess have been had"""
return len(self.guesses)
def any_correct_guesses(self):
"""Return True if there has been a correct guess"""
return GuessState.CORRECT in [state[1] for state in self.guesses]
def to_display(self, ui: UI):
"""Display the turn result in the UI"""
guess_value, guess_state = self.get_last_guess()
ui.display_turn_result(guess_value, guess_state)
#dataclass
class Game:
"""Game logic"""
scoreboard: Scoreboard
ui: UI
player_name: str
max_rounds: int = 6
max_number: int = 20
def play(self):
"""Play the game"""
self.ui.display_welcome(self.player_name, self.max_number, self.max_rounds)
target_number = random.randint(1, self.max_number)
print("For testing here is the target number:", target_number)
while self.scoreboard.game_active:
self.turn(target_number)
if self.scoreboard.game_active:
self.scoreboard.to_display(self.ui)
self.ui.display_goodbye(self.player_name, self.scoreboard)
def turn(self, target_number):
"""Play a turn"""
choice = self.ui.ask_guess(self.max_number)
if choice == target_number:
self.scoreboard.add_guess(choice, GuessState(0))
self.scoreboard.game_active = False
elif choice < target_number:
self.scoreboard.add_guess(choice, GuessState(-1))
elif choice > target_number:
self.scoreboard.add_guess(choice, GuessState(1))
if self.scoreboard.get_guess_count() == 6:
self.scoreboard.game_active = False
if __name__ == "__main__":
main()

creating a python number guessing game

SUPER new to programming so bear with me, please. I am taking my first ever programming class and for a project, I was given a list of requirements I need to fulfill, creating a simple number guessing game has been the only thing I've not had a lot of trouble with so I decided to give it a go.
(i need 1 class, function, dictionary or list, for loop, and while loop) What I, well at least have tried to make is a guessing game that gives a limit of 2 guesss for a # between 0 and 10, any help would be greatly appreciated. :)
import random
class Player:
player = ""
playerscore = 0
def gamestart(self):
self.number = random.randint(0,7)
self.guesss = 0
self.list = []
self.limit = 3
print()
print("Guess what number I'm thinking off")
print()
print("Might even give you a hit if you do well enough")
print()
while self.limit > 0:
self.player_guess = int(input("Well? What are you waiting for? Start guessing:"))
print()
if self.player_guess > 7 or self.player_guess < 0:
print("Wow that was a terrible guess, think harder or we might be here all week long")
print("also,", self.player_guess , "is not in the range...")
print("Becareful though, you only have", self.limit, "guesss left")
elif self.player_guess > self.number:
self.guesss += 1
self.limit-= 1
print("WRONG")
print(self.player, "You only have", self.limit, "guesss left")
self.list.append(self.player_guess)
elif self.player_guess < self.number:
self.guesss += 1
self.limit -= 1
print("oh oh... wrong again!")
print()
print(self.player, "You only have", self.limit, "guesss left.")
self.list.append(self.player_guess)
else:
self.limit -= 1
self.playerscore += 1
self.list.append(self.player_guess)
print()
print("wow, you actually got it right")
print()
print(self.player_guess, "IS THE CORRECT ANSWER!")
print()
print("you only had",self.limit,"left too...")
print("Lets see all the numbers you guessed")
print()
for i in self.list:
print(i)
self.list.clear()
I found the question confusing, however the following code should work as a number guessing game, hope I answered your question.
import random
game = "true"
guesses = 2
while game == "true":
comp_number = int(random.uniform(1,8))
print("I have randomly selected a number between 1 and 7 (inclusive), you have 2 attempts to guess the number.")
while guesses > 0:
if guesses == 2:
turn = "first"
else:
turn = "final"
guess = int(input("Please submit your "+turn+" guess:"))
while guess < 1 or guess > 7:
print("Invalid guess, remember my number is between 1 and 7 (inclusive)")
guess = int(input("Resubmit a valid guess:"))
if guess == comp_number:
print("Congratulations you guessed my number, you win!")
if str(input("Would you like to play again? Please enter Y or N.")) == "Y":
guesses = 2
game = "true"
else:
game = "false"
break
else:
print("Incorrect number, try again.")
guesses -= 1
print("You where unable to guess my number, I win!")
if str(input("Would you like to play again? Please enter Y or N.")) == "Y":
guesses = 2
game = "true"
else:
game = "false"
break

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

How to add a second player to this number guessing game for python?

Hi i am unsure on how to add a second player for this number guessing game whereby after player 1 makes a guess, then player 2 makes a guess. like between every guess. I am only able to make it so that the player 2 guesses after player 1 guesses finish all of his choices(code below) if anyone is able to tell me if what i am looking for is possible or if there is any advice, it would be greatly appreciated. thanks in advance.
def main():
import random
n = random.randint(1, 99)
chances = 5
guess = int(input("Player 1 please enter an integer from 1 to 99, you have 5 chances: "))
while n != "guess":
chances -=1
if chances ==0:
print("out of chances")
break
if guess < n:
print("guess is low")
guess = int(input("Enter an integer from 1 to 99: "))
elif guess > n:
print ("guess is high")
guess = int(input("Enter an integer from 1 to 99: "))
else:
print("you guessed it")
break
import random
n1 = random.randint(1, 99)
chances1 = 0
guess1 = int(input("Player 2 please enter an integer from 1 to 99, you have 5 chances "))
while n1 != "guess":
chances1 +=1
if chances1 ==5:
print("out of chances")
break
if guess1 < n1:
print("guess is low")
guess1 = int(input("Enter an integer from 1 to 99: "))
elif guess > n1:
print ("guess is high")
guess1 = int(input("Enter an integer from 1 to 99: "))
else:
print("you guessed it")
break
retry=input("would you like to play again? (please choose either 'yes' or 'no')")
if retry == "yes":
main()
else:
print("Okay. have a nice day! :D ")
main()
to achieve this I would use a while loop and a variable to detect which players turn it is. Like this:
import random
random_number = random.randint(1, 99)
player_chances = 5
current_player = 1
while player_chances > 0:
if current_player == 1:
guess = int(input("Player 1 please enter an integer from 1 to 99, {} chances left. ".format(player_chances)))
player_chances -= 1
current_player = 2
if guess < random_number:
print("->guess is too low")
elif guess > random_number:
print("->guess is too high")
else:
print("CONGRATULATIONS! You guessed it! Player 1 wins!")
break
else:
guess = int(input("Player 2 please enter an integer from 1 to 99, {} chances left. ".format(player_chances)))
player_chances -= 1
current_player = 1
if guess < random_number:
print("->guess is too low")
elif guess > random_number:
print("->guess is too high")
else:
print("CONGRATULATIONS! You guessed it! Player 1 wins!")
break
print("####")
print("Out of chances! The number was {}.".format(random_number))
print("####")
To make this possible in an efficient way I would have created a player class as such:
class Player:
def __init__(self,name):
self.name = name
self.getNumberOfTrys = 0
self.guess = 0
def getNumberOfTrys(self):
return self.getNumberOfTrys
def getPlayerName(self):
return self.name
def play(self):
try:
self.guess = int(input("Enter an integer from 1 to 99: "))
self.getNumberOfTrys+=1
return self.guess
except Exception as error:
print(error)
return None
this class is responsible to create the player with the number of tries,his guess and his name.
the logic will be going through the list of players (you can add as much as you want) and perform the game logic as follows:
import random
p1 = Player("Player 1")
p2 = Player("Player 2")
players = []
players.append(p1)
players.append(p2)
n1 = random.randint(1, 99)
NUMBER_OF_TRIES = 5
print(n1)
while players:
for player in players:
print(player.getPlayerName() + " turn, you have " + str(NUMBER_OF_TRIES - player.getNumberOfTries) + " turns left")
guess = player.play()
if guess < n1:
print("guess is low")
elif guess > n1:
print ("guess is high")
else:
print(player.getPlayerName()," you guessed it")
players.clear()
break
if player.getNumberOfTries == NUMBER_OF_TRIES:
print(player.getPlayerName(), " out of chances")
players.remove(player)
Basically, create a list of players then go through each one and apply the game logic (getting input, comparing and checking number of tries)
after a player loses, we should remove him from the list and if a player wins we can clear the list and thus exiting the game.
Here is the full code:
class Player:
def __init__(self,name):
self.name = name
self.getNumberOfTries = 0
self.guess = 0
def getNumberOfTries(self):
return self.getNumberOfTries
def getPlayerName(self):
return self.name
def play(self):
try:
self.guess = int(input("Enter an integer from 1 to 99: "))
self.getNumberOfTries+=1
return self.guess
except Exception as error:
print(error)
return None
import random
p1 = Player("Player 1")
p2 = Player("Player 2")
players = []
players.append(p1) #addding player
players.append(p2)
n1 = random.randint(1, 99)
NUMBER_OF_TRIES = 5
print(n1) #for debug
while players:
for player in players:
print(player.getPlayerName() + " turn, you have " + str(NUMBER_OF_TRIES - player.getNumberOfTries) + " turns left")
guess = player.play()
if guess < n1:
print("guess is low")
elif guess > n1:
print ("guess is high")
else:
print(player.getPlayerName()," you guessed it")
players.clear() # exit game
break #exit loop
if player.getNumberOfTries == NUMBER_OF_TRIES:
print(player.getPlayerName(), " out of chances")
players.remove(player)
Hope I got your question right, and excuse me If there is any errors or typos, I just created something fast that you can be inspired by. I highly suggest you get into OOP, it very simple and it can make your life much easier :)
All the best!

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