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()
.
.
.
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>>> "))
I'll try to keep it short and sweet.
I'm writing an interactive story that changes based on the "roll" of a d20 dice. I've managed to figure out getting started, but I've hit a point where I don't think Python is actually listening to the parameters I'm giving it, because it kind of just does whatever.
Essentially, here's what's supposed to happen:
Player agrees that they want to play the game -> Player Rolls dice -> Game uses the randomly rolled number to determine which start that the player will have.
What's currently happening is, all goes well until it's supposed to spit out the start that the player has. It doesn't seem to actually decide based on my parameters. For example, you're supposed to have the "human" start if the player rolls 5 or less, and an "elf" start for anything between 6 and 18. Here's what happened yesterday:
venv\Scripts\python.exe C:/Users/drago/PycharmProjects/D20/venv/main.py
Hello! Would you like to go on an adventure? y/n >> y
Great! Roll the dice.
Press R to roll the D20.
You rolled a 15!
You start as a human.
As a human, you don't have any special characteristics except your ability to learn.
The related code is below:
def NewGame():
inp = input("Hello! Would you like to go on an adventure? y/n >> ")
if inp == "y" or inp == "yes":
print("Great! Roll the dice.")
input("Press R to roll the D20.")
print("You rolled a " + str(RollD20()) + "!")
PostGen()
else:
input("Okay, bye! Press any key to exit.")
sys.exit()
def PostGen():
if RollD20() <= 5:
print("You start as a human.")
PostStartHum()
elif RollD20() >= 6:
print("You start as an elf.")
PostStartElf()
elif RollD20() >= 19:
print("You lucked out, and can start as a demigod!")
PostStartDemi()
def RollD20():
n = random.randint(1, 20)
return n
def PostStartHum():
print("As a human, you don't have any special characteristics except your ability to learn.")
def PostStartElf():
print("As an elf, you have a high intelligence and a deep respect for tradition.")
def PostStartDemi():
print("As a demigod, you are the hand of the gods themselves; raw power incarnated in a human form...")
print("However, even mighty decendants of gods have a weakness. Be careful."
Thanks for all your help.
Turn your PostGen function into the following:
def PostGen(rollValue):
if rollValue <= 5:
print("You start as a human.")
PostStartHum()
elif rollValue >= 6:
print("You start as an elf.")
PostStartElf()
elif rollValue >= 19:
print("You lucked out, and can start as a demigod!")
PostStartDemi()
Change your NewGame function to the following:
def NewGame():
inp = input("Hello! Would you like to go on an adventure? y/n >> ")
if inp == "y" or inp == "yes":
print("Great! Roll the dice.")
input("Press R to roll the D20.")
rollValue = RollD20()
print("You rolled a " + str(rollValue) + "!")
PostGen(rollValue)
else:
input("Okay, bye! Press any key to exit.")
sys.exit()
You are generating a new random number every time you call RollD20(). You need to store the value somewhere and reuse it for the game session.
Each time you call RollD20, you get a new random number. So if you want to use the same random number in multiple ifs, you need to tuck that value into another variable.
def NewGame():
inp = input("Hello! Would you like to go on an adventure? y/n >> ")
if inp == "y" or inp == "yes":
print("Great! Roll the dice.")
input("Press R to roll the D20.")
result = RollD20()
print("You rolled a " + str(result) + "!")
PostGen(result)
else:
input("Okay, bye! Press any key to exit.")
sys.exit()
And from there you change PostGen() to accept the result:
def PostGen(result):
if result <= 5:
print("You start as a human.")
PostStartHum()
elif result >= 6:
print("You start as an elf.")
PostStartElf()
elif result >= 19:
print("You lucked out, and can start as a demigod!")
PostStartDemi()
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)
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.
I have been working on this guessing game but i just cant get it to repeat the game when the player says yes. The game gives you 5 attempts to guess the number that it thought of and then after it asks you if you would like to play again but when you say 'YES' it just keeps repeating the sentence and when you say 'NO' it does what its supposed to which is break the code
def main():
game = "your game"
print(game)
play_again()
import random #imports random number function
print("Welcome to the number guessing game!")
counter=1 #This means that the score is set to 0
number = int(random.randint(1,10))
while counter >0 and counter <=5:
guess=int(input("Try and guess the number\n"))#tells the user to try and guess the number
if guess!=number and guess>number:
print("wrong number! Try again you are too high")#tells you that you were wrong and that that you were too high
counter=counter+1#adds 1 count for every attempt it took you to guess the number
elif guess!=number and guess<number:
print("wrong number! Try again you are too low!")#tells you that you were wrong and tells you that you were too low
counter=counter+1#adds 1 count for every attempt it took you to guess the number
else:
print("Well done! You have guessed the number i was thinking of! The number was ",number)#Prints this out when you guessed the number
print("it took you ",counter, "attempts!")#tells you how many attempts it took you to guess the number
if counter==2:
print("4 attempts left before program ends")
if counter==3:
print("3 attempts left before program ends")
if counter==4:
print("2 attempts left before program ends")
if counter==5:
print("1 attempts left before program ends")
def play_again():
while True:
play_again = input("Would you like to play again?(yes or no) : ")
if play_again == "yes":
main()
if play_again == "no":
exit()
else:
print("I'm sorry I could not recognize what you entered")
main()
It's because your game code isn't in the function. Try it in this manner:
<import statements>
def game():
<insert all game code>
def main():
while True:
play_again = input("Would you like to play again?(yes or no) : ")
if play_again == "yes":
game()
if play_again == "no":
exit()
else:
print("I'm sorry I could not recognize what you entered")
There's a few problems with your code that I'd like to point out.
The main one being that your game does not run again when typing yes. All it will do is run main() which will print your game and then ask you if you want to retry once again. It's easier if you put your game inside a definition that way you can call it whenever necessary.
Also, I don't know if it's just me, but if you guess the correct number, it will still ask you to guess a number. You need to exit your loop by putting your play_again() method in your else block.
Below is the code. I've polished it up a little just for optimization.
import random #imports random number function
def main():
print("Welcome to the number guessing game!")
game = "your game"
print(game)
run_game()
play_again()
def run_game():
counter = 1
number = random.randint(1, 10)
while counter > 0 and counter <= 5:
guess=int(input("Try and guess the number\n"))#tells the user to try and guess the number
if guess!=number and guess > number:
print("wrong number! Try again you are too high")#tells you that you were wrong and that that you were too high
counter=counter+1#adds 1 count for every attempt it took you to guess the number
elif guess != number and guess < number:
print("wrong number! Try again you are too low!")#tells you that you were wrong and tells you that you were too low
counter=counter+1#adds 1 count for every attempt it took you to guess the number
else:
print("Well done! You have guessed the number i was thinking of! The number was " + str(number))#Prints this out when you guessed the number
print("it took you " + str(counter) + " attempts!")#tells you how many attempts it took you to guess the number
play_again()
if counter == 2:
print("4 attempts left before program ends")
if counter == 3:
print("3 attempts left before program ends")
if counter == 4:
print("2 attempts left before program ends")
if counter == 5:
print("1 attempts left before program ends")
def play_again():
while True:
retry = input("Would you like to play again?(yes or no) : ")
if retry == "yes":
main()
if retry == "no":
exit()
else:
print("I'm sorry I could not recognize what you entered")
main()