My python game code is not working - python

I am trying to code a sort of walking on the ledge random chance game, users would input a certain amount they would like to bet and then depending on how many steps they would take, they would either live or fall off the ledge. The code so far is FAR from being finished but I have encountered a problem and I was wondering if someone could help me fix it.
import time
import random
class Player():
def __init__(self,name):
self.name = name
self.luck = 2
self.gold = 10
def main():
print("Hello what is your name?")
option = input("--> ")
global PlayerIG
PlayerIG = Player(option)
start1()
def start1():
print("Name: {}".format(PlayerIG.name))
print("Luck: {}".format(PlayerIG.luck))
print("Gold: {}".format(PlayerIG.gold))
inputgold()
def inputgold():
print("Please input how much gold you would like to play with")
goldinput = input("--> ")
strgold = str(goldinput)
print("You inputted {}".format(strgold))
if strgold <= PlayerIG.gold:
print("You don't have enough gold")
inputgold()
else:
print("Get ready to start!")
ledge()
def ledge():
print("You are standing on a ledge with an unknown length")
time.sleep(1)
choice = input("How many steps do you want to take forward? Between 1-100")
if choice == step1:
print("You have fallen off the ledge")
PlayerIG.gold -= goldinput
print("Gold: ".format(PlayerIG.gold))
elif choice == step2:
print("You...")
time.sleep(1)
print("Didn't fall off the ledge!")
PlayerIG.gold*1.2
print("Gold: ".format(PlayerIG.gold))
else:
print("You slipped off the ledge and face planted onto the side walk")
PlayerIG.gold -= goldinput
print("Gold: ".format(PlayerIG.gold))
def steps():
step1 = random.randint(10,30)
step2 = random.randint(30,50)
step3 = random.randint(50,100)
main()
When I run it is says:
if strgold <= PlayerIG.gold: TypeError: unorderable types: str() <= int()
How can I fix it?

The problem is this line:
if strgold <= PlayerIG.gold:
Here you are comparing a string with an integer. This is not possible, you have to convert the string to an integer first:
if int(strgold) <= PlayerIG.gold:
I haven't checked the rest of your code, but I suspect you might also have similar mistakes elsewhere too.

Related

Guessing game: Difficulty importing class and getting it to function. PYTHON

I am making a guessing game. I wanted to create a guess counter module in a modules.py doc and import it into my main.py so i could access its instance for other modules.
The only problem is I cant get it to function.
main.py code ##
guess = Guess_Counter(0)
print("Welcome to the guessing game you have 3 guesses your first riddle is: \n")
while True and (guess) < 4:
print("I am cool as a breeze, I stop your heart with ease, seasons may be my enemy, but im part of you and you are friend to me. What am I? \n")
print("Enter your guess or type 'hint', or 'quit' below.")
answer = input()
answer = answer.upper()
guess += 1
if "sneeze" in answer.upper():
print("Great work, your next riddle is: \n")
break
elif answer == "hint":
guess.guess -= 1
print("Achoo!\n")
elif answer == "quit" or guess == 4:
print("Better luck next time! ")
quit()
else:
print("Try again!")
Testmodules.py code ##
class Guess_Counter():
def __init__(self, numguess):
self.numguess = numguess

How do I correctly use isinstance() in my random number guessing game or is another function needed?

I want this number guessing game to be able to catch every possible exception or error the user enters. I've successfully prevented the use of strings when guessing the number, but I want the console to display a custom message when a float is entered saying something along the lines of "Only whole numbers between 1-20 are allowed". I realize my exception would work to catch this kind of error, but for learning purposes, I want to specifically handle if the user enters a float instead of an int. From what I could find online the isinstance() function seemed to be exactly what I was looking for. I tried applying it in a way that seemed logical, but when I try to run the code and enter a float when guessing the random number it just reverts to my generalized exception. I'm new to Python so if anyone is nice enough to assist I would also appreciate any criticism of my code. I tried making this without much help from the internet. Although it works for the most part I can't get over the feeling I'm being inefficient. I'm self-taught if that helps my case lol. Here's my source code, thanks:
import random
import sys
def getRandNum():
num = random.randint(1,20)
return num
def getGuess(stored_num, name, gameOn = True):
while True:
try:
user_answer = int(input("Hello " + name + " I'm thinking of a number between 1-20. Can you guess what number I'm thinking of"))
while gameOn:
if user_answer >= 21 or user_answer <=0:
print("That is not a number between 1-20. Try again.")
user_answer = int(input())
elif isinstance(user_answer, int) != True:
print("Only enter whole numbers. No decimals u cheater!")
user_answer = int(input())
elif user_answer > stored_num:
print("That guess is too high. Try again " + name + " !")
user_answer = int(input())
elif user_answer < stored_num:
print("That guess is too low. Try again " + name + " !")
user_answer = int(input())
elif user_answer == stored_num:
print("You are correct! You win " + name + " !")
break
except ValueError:
print("That was not a number, try again")
def startGame():
print("Whats Your name partner?")
name = input()
stored_num = getRandNum()
getGuess(stored_num, name)
def startProgram():
startGame()
startProgram()
while True:
answer = input("Would you like to play again? Type Y to continue.")
if answer.lower() == "y":
startProgram()
else:
break
quit()
The only thing that needs be in the try statement is the code that checks if the input can be converted to an int. You can start with a function whose only job is to prompt the user for a number until int(response) does, indeed, succeed without an exception.
def get_guess():
while True:
response = input("> ")
try:
return int(response)
except ValueError:
print("That was not a number, try again")
Once you have a valid int, then you can perform the range check to see if it is out of bounds, too low, too high, or equal.
# The former getGuess
def play_game(stored_num, name):
print(f"Hello {name}, I'm thinking of a number between 1-20.")
print("Can you guess what number I'm thinking of?")
while True:
user_answer = get_guess()
if user_answer >= 21 or user_answer <=0:
print("That is not a number between 1-20. Try again.")
elif user_answer > stored_num:
print(f"That guess is too high. Try again {name}!")
elif user_answer < stored_num:
print(f"That guess is too low. Try again {name}!")
else: # Equality is the only possibility left
print("You are correct! You win {name}!")
break

Restarting a function once condition returns True

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

How to get my random number guessing game to loop again upon user input and how to create an error trap?

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)

apparently ran_num is not defined

So I've remade part of my dicegame's code and it's works somewhat decently, however after ROLL'ing the dice and attempting to display the users score, I run in to an error where is says 'name p1_score is not defined'. It says the same thing for the variable p2_score aswell. However I defined p1_score as ran_num+ran_num so I don't get why I'm getting an error.
import random
import time
player_1 = input("")
player_2 = input("")
def rollDice(player_1):
ran_num = random.randint(1,6)
if ran_num == 1:
print("You rolled a",ran_num)
else:
print("You rolled a",ran_num)
p1_score = ran_num+ran_num
def rollDice(player_2):
ran_num = random.randint(1,6)
if ran_num == 1:
print("You rolled a",ran_num)
else:
print("You rolled a",ran_num)
p2_score = ran_num+ran_num
print("Please press ENTER to roll the dice")
input()
rollDice(player_1)
print("Good job",player_1,)
print("Your score is now",p1_score)
time.sleep(5)
print(player_2,"Press ENTER to roll the dice")
input()
rollDice(player_2)
print("Nice work",player_2)
print("Your score is now",p2_score)
def main():
rollDice(player1, player2)
main()
This is a variable scoping issue, you either need to use a global (globals can be dangerous if used incorrectly) the same way you have with player_1 and player_2, OR return from that function and use the returned value for the output.
http://python-textbok.readthedocs.io/en/1.0/Variables_and_Scope.html
"Not affiliated with that website, just did a quick google to see if I could find a resource for you to read so you can understand"
import random
import time
def rollDice():
ran_num = random.randint(1,6)
print("You rolled a " + str(ran_num))
raw_input()
resolved_score = ran_num+ran_num
return str(resolved_score)
player_1 = raw_input("Enter player one name: ")
player_2 = raw_input("Enter player two name: ")
print("Please press ENTER to roll the dice")
raw_input()
p1_result = rollDice()
print("Good job "+player_1)
print("Your score is now "+p1_result)
time.sleep(5)
print(player_2+" Press ENTER to roll the dice")
raw_input()
p2_result = rollDice()
print("Nice work "+player_2)
print("Your score is now "+p2_result)
I've rationalised your code a bit, there were some logic errors. Notice in the def I have a return statement, the return statement adds two numbers together, converts it to a string using str() and I use RETURN to spit the value back out to the calling code. In this case the calling code is first encountered where we see:
p1_result = rollDice()
Now p1_result will equal whatever the ran_num+ran_num resolved to inside the function.

Categories