I am creating a Python Dice game called Beat That. I have gotten everything to work so far except for taking the players guess and comparing it to the highest possible number you can make. So let's say you roll a 5 and a 2 the highest number you could make it 52. So far when I enter the correct number it always says incorrect. Any help is appreciated.
In the screenshot below everything works except for the def turn section where it says "The highest number you could've made out of your roll is ...". It prints out the correct number but it marks it as incomplete.
This is the whole code:
import random
import time
from random import randint
play_again = True
#greeting the players to the game
print("Welcome to Beat That, a small game made by Mats Muche.")
#as long as play_again is true this will repeat itself until the user decides to end the game
while play_again:
totalnumber = []
def rollDice(numOfDice):
num = []
for i in range(1,numOfDice+1):
num = randint(1, 6)
print("Rolling the dice... You rolled a",num)
totalnumber.append(num)
time.sleep(1.5)
return num
return totalnumber
#this part checks the players guess to the highest number that can be made
def turn(numOfDice):
roll = rollDice(numOfDice)
totalnumber.sort(reverse = True)
print(*totalnumber , sep="")
guess = int(input("What is the biggest number you can make?"))
if guess == totalnumber:
print("Correct!")
else:
if totalnumber != guess:
print("Incorrect!")
print("The highest number you could've made out of your roll is ", *totalnumber , sep="")
time.sleep(1)
return totalnumber
#main code
#rules
print("*" * 80)
print("Here are the rules!")
time.sleep(1)
print("-Players may take turns rolling a set number of dice.")
time.sleep(1)
print("-The aim of the game is to get the biggest number from your dice roll.")
print("*" * 80)
time.sleep(2)
#amount of dice players want to use
numOfDice = int(input("How many dice would you like to use? "))
#start of game
print("Player 1's turn:")
time.sleep(1)
p1 = turn(numOfDice)
print("*" * 80)
time.sleep(2)
print("Player 2's turn:")
time.sleep(1)
totalnumber = []
p2 = turn(numOfDice)
print("*" * 80)
#seeing who won the game (highest number made wins)
if p1 > p2:
print("Player 1 has won the game! Congrats!")
time.sleep(1)
elif p2 > p1:
print("Player 2 has won the game! Congrats!")
time.sleep(1)
else:
print("It's a tie! Try again.")
print("*" * 80)
#seeing if players want to play again
again = input("Do you want to play again? Press any key except from 'n' to continue. ")
if again[0].lower() == 'n':
play_again = False
#if players say "n" then this message pops up and the game ends
print("End of game. Thank you for playing!")
Thanks for reading :)
As I am a beginner who is in school. I do not really have much knowledge of how to fix something like this issue.
This is the line that is the problem.
print("The highest number you could've made out of your roll is ", *totalnumber , sep="")
The problem would be this line:
def turn(numOfDice):
roll = rollDice(numOfDice)
totalnumber.sort(reverse = True)
print(*totalnumber , sep="")
guess = int(input("What is the biggest number you can make?"))
if guess == totalnumber:
print("Correct!")
Here, totalnumber is a list, not an int. therefore, you can try to make the input similarly a list too. change:
guess = int(input("What is the biggest number you can make?"))
into:
guess = list(map(int, input("What is the biggest number you can make?")))
Which should fix the issue.
Related
It's my RPG assignment for our school. I made an RPG program about an encounter with a Pirate and conversing with him with a guessing game. When I didn't use Colorama, the program runs normal but when using it, it slows down the program when running. I submitted the got 18 or 20 which is not bad, and I suspected it's how my program runs that's why I didn't get the perfect score.
I'm wondering if you guys can help me how to run the program faster when using Colorama? I just really wanted to learn how to solve this kind of issue.
import random
import time
import colorama
from colorama import Fore, Back, Style
talk_again = 'y'
while talk_again == 'y':
print("\nThere is a pirate coming down the road...")
time.sleep(2)
try:
user_option = int(input("\nWhat would you like to do? \n [1] To greet! \n [2] To play a game of chance \n [3] To walk on \n>>> "))
greetings= ["Hello stranger", "Hi there stranger!","Ahoy stranger!","Hey","*He stops, staring at you & didn't say anything*"]
inventory = ["Sword", "Shield","Dagger","Choker","Healing potion", "Red gem", "Red diamond","Sword", "Armour"]
leaving = ["Argghhh!!!", "Arrgh!Shut up!","Dammit! Arrgghh!!!"]
# lowercase items in inventory list, so we can compare wager input text
lowercase_inventory = [x.lower() for x in inventory]
def speak(text): #This is pirate conversation function colored in red
colorama.init(autoreset=True) # Automatically back to default color again
print(Fore.RED + '\t\t\t\t' + text)
def guess_my_number(): # the guessing number game
colorama.init(autoreset=True)
speak("Great! Let's play game of chance.")
time.sleep(1.5)
speak("I have a magic pen we can play for. What can you wager?")
time.sleep(1.5)
print("This is your inventory:" , lowercase_inventory)
wager = input(">>> ").lower()
# if wager item available in lowercased inventory
if wager.lower() in lowercase_inventory:
speak("That is acceptable!, Let's play the game of chance!")
time.sleep(1.5)
speak("I've thought of number between 1 to 100, you have 10 trys to guess it")
time.sleep(1.5)
speak("If you guess correctly, magic pen will be added to your inventor")
time.sleep(1.5)
speak("Otherwise you will lose " + wager + " from your inventory")
time.sleep(1.5)
speak("Make your guess:")
random_number = random.randint(1,100)
count = 10
main_game = True
# while loop will keep runing either guessed number matches random number or count number reaches 1
while main_game and count > 0:
try:
guess = int(input(">>> "))
except ValueError:
speak("Arrghh! I said guess numbers from 1 to 100 only!! Do you wanna play or not?")
else:
if count == 0:
speak("HA HA HA!! You lose!")
# count decreses by one every time.
lowercase_inventory.remove(wager)
print("Your current inventory:", lowercase_inventory)
break
if guess == random_number:
speak("Darn it!.. You won in " + str(11 - count)+ " guesses") #str(11 - count) means subtract the guesses from 11
lowercase_inventory.append('Magic pen')
print("The magic pen has been added in your inventory.\nYour inventory now: ", lowercase_inventory)
break
elif guess > random_number:
speak("Lower the number kid! Guess again!")
count-=1 # count decreses by one every time.
speak(str(count)+" "+ "chances left!!")
elif guess < random_number:
speak("Make it higher!Guess again!")
count-=1 # count decreses by one every time.
speak(str(count)+" "+ "chances left!!")
else:
speak("You don't have this item in your inventory, We can't play!")
except ValueError:
print("\nType 1, 2 and 3 only!")
else:
while True:
if user_option == 1:
print("\nType to greet the pirate:")
input(">>> ")
speak(random.choice(greetings))
elif user_option == 2:
guess_my_number()
elif user_option == 3:
leave_input = input("\nWhat would you like to say on leaving?:\n>>> ")
if leave_input == 'nothing':
speak("*He glances at you, then looks away after he walk passeed you, minding his own business*")
else:
speak(random.choice(leaving))
talk_again = input("\nPlay again?(y/n) " )
if talk_again == 'n':
print("\n Goodbye!")
break
user_option = int(input("\nWhat would you like to do? \n[1] to greet! \n[2] to play a game of chance \n[3] to walk on \n>>> "))
Trying my hand at writing a very simple Game of Chance game on Codecademy while working through their Python course. I was doing ok (I think) for a while and the code returned what I expected it to, but now it feels I'm stuck and googling things frantically hasn't really helped me and I don't just want to look at the actual solution because where's the fun in that so here goes.
My thought process was the game should initially ask the player to input their guess and their bid, then run the code in game() and print the outcome. This was then to be locked in a while loop to check if the user wanted to continue playing or not and if the answer was "Yes" to restart the game() function again. This is where I am stuck as I just can't figure out what to put in line 26 after the "Yes" check returns True.
I guess the TL/DR version of my actual question is how do you (without giving the actual code away) call a function from within a while loop? Wondering if perhaps I'm simply headed in the wrong direction here and need to review while loops once more.
Thanks!
# Import stuff
import random
# Generate random number from 1 - 9
num = random.randint(1, 10)
# The actual game, asking user for input and returning the outcome
def game():
guess = int(input("Guess the number: "))
bid = int(input("Bet on the game: "))
money = 100
if guess == num:
money = (money + bid)
print("You Won")
print("You now have: " + str(money) +" money")
return money
else:
money = (money - bid)
print("You lost, you will die poor")
print("You now have: " + str(money) +" money")
return money
# Run game() while there's still money left in the pot
def structure():
while money > 0:
another_go = input("Would you like to play again? Yes or No: ")
if another_go == "Yes":
game() # This is where I'm stuck
elif another_go == "No":
print("Oh well, suit yourself")
break
else:
print("Pick Yes or No")
print(another_go)
game()
Ok so a few things to go through here.
First off, the concept of a local variable is coming into play here and is why your money variable is not communicating properly between your two functions. Each of your functions uses it's own money variable, which is completely independent of the other.
So this is the root of your current problem, where your money > 0 loop never actually runs. Secondly, although this might have just been done for troubleshooting, you don't actually call structure which is supposed to control game().
Lets try something like this where we keep money in the structure function and pass an update version to the game function as a parameter. Then, because you have game() returning money, you can just update the money value in your structure() call.
# Import stuff
import random
# Generate random number from 1 - 9
num = random.randint(1, 10)
# The actual game, asking user for input and returning the outcome
def game(money):
guess = int(input("Guess the number: "))
bid = int(input("Bet on the game: "))
if guess == num:
money = (money + bid)
print("You Won")
print("You now have: " + str(money) +" money")
return money
else:
money = (money - bid)
print("You lost, you will die poor")
print("You now have: " + str(money) +" money")
return money
# Run game() while there's still money left in the pot
def structure():
money = 100
money = game(money)
while money > 0:
another_go = input("Would you like to play again? Yes or No: ")
if another_go == "Yes":
money = game(money) # This is where I'm stuck
elif another_go == "No":
print("Oh well, suit yourself")
break
else:
print("Pick Yes or No")
print(another_go)
structure()
Notice because of how your while loop is written, in order to get game() to run the first time I had to call it before the while loop. Maybe as a challenge, see if you can be rewrite the structure of your loop so that you don't have to do this!
Welcome to SO. Your code is overall fine. Here's one way to slightly change your code to make it work:
... Most of the code ...
money = 10
def structure():
another_go = "Yes" # initialize to 'Yes', so we'll
# always have a first game.
while money > 0:
if another_go == "Yes":
game() # This is where I'm stuck
elif another_go == "No":
print("Oh well, suit yourself")
break
else:
print("Pick Yes or No")
print(another_go)
# move 'another go' to the end of the loop
another_go = input("Would you like to play again? Yes or No: ")
structure() # call this function to start
# make money a global parameter with a -ve value
money = -1
def game():
global money
guess = int(input("Guess the number: "))
bid = int(input("Bet on the game: "))
# Then, if money has default(game started for first time), update it
if(money < 0):
money = 100
.
.
.
.
while money > 0:
global money
another_go = input("Would you like to play again? Yes or No: ")
if another_go == "Yes":
game(money) # Pass remaining money to game()
.
.
.
So this is my random number guessing program I made. It asks the user to input two numbers as the bound, one high and one low, then the program will choose a number between those two. The user then has to try and guess the number chosen by the program. 1) How do I get it to ask the user if they would like to play again and upon inputting 'yes' the program starts over, and inputting 'no' the program ends? 2) How do I create an error trap that tells the user "Hey you didn't enter a number!" and ends the program?
def main(): # Main Module
print("Game Over.")
def introduction():
print("Let's play the 'COLD, COLD, HOT!' game.")
print("Here's how it works. You're going to choose two numbers: one small, one big. Once you do that, I'll choose a random number in between those two.")
print("The goal of this game is to guess the number I'm thinking of. If you guess right, then you're HOT ON THE MONEY. If you keep guessing wrong, than you're ICE COLD. Ready? Then let's play!")
small = int(input("Enter your smaller number: "))
large = int(input("Enter your bigger number: "))
print("\n")
return small, large
def game(answer):
c = int(input('Input the number of guesses you want: '))
counter = 1 # Set the value of the counter outside loop.
while counter <= c:
guess = int(input("Input your guess(number) and press the 'Enter' key: "))
if answer > guess:
print("Your guess is too small; you're ICE COLD!")
counter = counter + 1
elif answer < guess:
print("Your guess is too large; you're still ICE COLD!")
counter = counter + 1
elif answer == guess:
print("Your guess is just right; you're HOT ON THE MONEY!")
counter = c + 0.5
if (answer == guess) and (counter < c + 1):
print("You were burning hot this round!")
else:
print("Wow, you were frozen solid this time around.", "The number I \
was thinking of was: " , answer)
def Mystery_Number(a,b):
import random
Mystery_Number = random.randint(a,b) # Random integer from Python
return Mystery_Number # This function returns a random number
A,B = introduction()
number = Mystery_Number(A,B) # Calling Mystery_Number
game(number) # Number is the argument for the game function
main()
You'd first have to make game return something if they guess right:
def game(answer):
guess = int(input("Please put in your number, then press enter:\n"))
if answer > guess:
print("Too big")
return False
if answer < guess:
print("Too small")
return False
elif answer == guess:
print("Your guess is just right")
return True
Then, you'd update the 'main' function, so that it incorporates the new 'game' function:
def main():
c = int(input("How many guesses would you like?\n"))
for i in range(c):
answer = int(input("Your guess: "))
is_right = game(answer)
if is_right: break
if is_right: return True
else: return False
Then, you'd add a run_game function to run main more than once at a time:
def run_game():
introduction()
not_done = False
while not_done:
game()
again = input('If you would like to play again, please type any character')
not_done = bool(again)
Finally, for error catching, you'd do something like this:
try:
x = int(input())
except:
print('That was not a number')
import sys
sys.exit(0)
import random
import time
def closest_num(GuessesLog, CompNum):
return GuessesLog[min(range(len(GuessesLog)), key=lambda g: abs(GuessesLog[g] - CompNum))]
GameModeActive = True
while GameModeActive:
Guesses = None
GuessesLog = []
while not isinstance(Guesses, int):
try:
Guesses = int(input("How many guesses do you have?: "))
except ValueError:
print("Please enter a whole number")
print(" ")
CompNum = random.randint(1,99)
print(CompNum)
Players = None
while not isinstance(Players, int):
try:
Players = int(input("How many players are there?: "))
except ValueError:
print("Please enter a whole number")
print(" ")
NumberOfPlayers = []
for i in range(Players):
NumberOfPlayers.append(i+1)
NumberOfGuesses = []
for i in range(Guesses):
NumberOfGuesses.append(i+1)
print(NumberOfGuesses)
print(NumberOfPlayers)
print(len(NumberOfGuesses))
print(len(NumberOfPlayers))
for Guess in NumberOfGuesses:
if Guess != len(NumberOfGuesses):
print("ITS ROUND {}! GET READY!".format(Guess))
print(" ")
PlayersForRound = NumberOfPlayers
for Player in PlayersForRound:
print("It is Player {}'s Turn >>>".format(Player))
print(PlayersForRound)
print(NumberOfPlayers)
PlayerEntry = None
while not isinstance(PlayerEntry, int):
try:
PlayerEntry = int(input("Enter guess number {}: ".format(Guess)))
print(" ")
except ValueError:
print("Please enter a whole number")
print("CALCULATING YOUR RESULT!")
time.sleep(1)
print("***5***")
time.sleep(1)
print("***4***")
time.sleep(1)
print("***3***")
time.sleep(1)
print("***2***")
time.sleep(1)
print("***1***")
if PlayerEntry == CompNum:
print("Congratulations player {}, you have successfully guessed the number on round {}!".format(Player, Guess))
print(" ")
NumberOfPlayers.pop(Player-1)
if len(NumberOfPlayers) == 1:
print("Only {} Player remains".format(len(NumberOfPlayers)))
PlayersForRound
elif len(NumberOfPlayers) > 1:
print("Only {} Players remain".format(len(NumberOfPlayers)))
continue
elif PlayerEntry < CompNum:
print("Your guess was too low!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
elif PlayerEntry > CompNum:
print("Your guess was too high!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
if Guess == len(NumberOfGuesses):
print("ITS ROUND {}! THIS IS THE LAST ROUND! GOOD LUCK!".format(Guess))
print(" ")
print(NumberOfGuesses)
print(NumberOfPlayers)
print(len(NumberOfGuesses))
print(len(NumberOfPlayers))
PlayersForRound = NumberOfPlayers
for Player in PlayersForRound:
print("It is Player {}'s Turn >>>".format(Player))
PlayerEntry = None
while not isinstance(PlayerEntry, int):
try:
PlayerEntry = int(input("Enter guess number {}: ".format(Guess)))
print(" ")
except ValueError:
print("Please enter a whole number")
print("CALCULATING YOUR RESULT!")
time.sleep(1)
print("***5***")
time.sleep(1)
print("***4***")
time.sleep(1)
print("***3***")
time.sleep(1)
print("***2***")
time.sleep(1)
print("***1***")
if PlayerEntry == CompNum:
print("Congratulations player {}, you have successfully guessed the number on round {}!".format(Player, Guess))
print(" ")
NumberOfPlayers.pop(Player-1)
if len(NumberOfPlayers) == 1:
print("Only {} Player remains".format(len(NumberOfPlayers)))
elif len(NumberOfPlayers) > 1:
print("Only {} Players remain".format(len(NumberOfPlayers)))
continue
elif PlayerEntry < CompNum:
print("Your guess was too low!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
elif PlayerEntry > CompNum:
print("Your guess was too high!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
print("The closest guess was ", closest_num(GuessesLog, CompNum))
print(" ")
while True:
Answer = input("Would you like to play again? Y/N: ")
if Answer.lower() not in ('y', 'n'):
print("Please enter either Y for Yes, or N for No.")
else:
break
if Answer == 'y':
GameActiveMode = True
elif Answer == 'n':
GameActiveMode = False
print("Thankyou for playing ;)")
break
holdCall = str(input("Holding the console, press enter to escape."))
In my above code, when there are multiple players and multiple guesses(Rounds) then it works fine unless someone successfully guesses the code. If the code is guessed the code deletes the correct record from the player list. But for some reason fails to iterate over the rest of the list or if the correct guess comes from the second user it skips the next player altogether and moves onto the next round.
I have absolutely no idea why. Anyone have any ideas? Thanks in advance.
For example, if you run this in console and then have 3 guesses with 3 users, on the first player you guess incorrectly. On the second you guess correctly, it skips player 3 and goes straight to round 2. Despite only remove player 2 from the list after a correct guess.
Or if you guess it correctly the first time around it skips to the 3rd player?
You are keeping track of players in the current round using a list of player numbers. So, if you start with three players, PlayersForRound will start as [1,2,3].
You then proceed to loop over this list to give each player their turn by using for Player in PlayersForRound. However, PlayersForRound and NumberOfPlayers are the exact same list (not a copy), so when you remove a player from one, it is removed from both.
Once a player guesses correctly, you remove them from the list you were looping over with NumberOfPlayers.pop(Player-1). For example if the second player guesses correctly, you remove their "index" from the list and the resulting list is now [1,3].
However, because Python is still looping over that same list, player 3 never gets their turn, because their "index" is now in the position where the "index" of player 2 was a moment ago.
You should not modify the list you're looping over, this will result in the weird behaviour you are seeing. If you want to modify that list, you could write a while loop that conditionally increases an index into the list and checks whether it exceeds the length of the list, but there are nicer patterns to follow to achieve the same result.
As for naming, please refer to https://www.python.org/dev/peps/pep-0008/ - specifically, your variables like PlayersForRound should be named players_for_round, but more importantly, you should name the variables so that they mean what they say. NumberOfPlayers suggests that it is an integer, containing the number of players, but instead it is a list of player numbers, etc.
The selected bits of your code below reproduce the problem, without all the fluff:
# this line isn't in your code, but it amounts to the same as entering '3'
Players = 3
NumberOfPlayers = []
for i in range(Players):
NumberOfPlayers.append(i+1)
PlayersForRound = NumberOfPlayers
for Player in PlayersForRound:
# this line is not in your code, but amounts to the second player guessing correctly:
if Player == 2:
NumberOfPlayers.pop(Player-1)
if Player == 3:
print('this never happens')
# this is why:
print(PlayersForRound, NumberOfPlayers)
When you pop the list, you intervene in the for loop. Here, you can play with this and see yourself.
players = 3
player_list = []
for p in range(players):
player_list.append(p + 1)
for player in player_list:
print(player)
if player == 2:
print("popped:",player_list.pop(player-1))
Output
1
2
popped: 2
I'm trying to write a script for a game where the user has to guess a computer generated value. The aim is for the player number to be reduced until it has a value of 1 at which point it ends.
import random
import time
players = input("Let's play Five's! How many are you?:" )
#print("you are", players, "players?") #test number of players
players = int(players)
if players <=1:
print("Game Over")
else:
while players >= 1:
players = players+1
#Decide possible values than can be chosen
options = [] #Possible options
for i in range(0,players):
x = i * 5
options.append(x)
print("Your choices are", options)
#Playing the game
#Each turn
guess = random.choice(options)
print("Computer has chosen", int(guess))
count_down = 3
while (count_down):
print(count_down)
time.sleep(1)
count_down -= 1
choice = input("Guess:")
choice = int(choice)
if choice not in options: #If choice isn't a multiple of 5
input("Not allowed, choose again:")
elif choice in options and choice != guess: #Valid choice but wrong
print("Wrong") #so player is still in the
else: #game
choice = int(choice)
if choice == guess: #Correct choice so player leaves game
print("You're Out.") # this should reduce the player count
players -=1
I've included the line printing the computer generated value so I can give the correct guess but even if guess correctly it doesn't reduce the player count and so the game continues infinitely
You add a player on the first line of the while loop.
players = players+1
Then you subtract a player on the last line
players -=1
If I understand your code correctly, the number of players won't change.