When i run my code, it will run the part of player1 however once it reaches the function it will loop back and do the player1 section again, code for it is here:
import random
playerscore2 = 0
EvenNums = [2,4,6,8,10,12]
OddNums = [3,5,7,9,11]
def playerscoretwo():
print("Player 2's turn")
rolling2 = input('would you like to roll?')
roll3 = rolling2.lower()
if rolling2 == 'Yes':
playerscore3 = 0
die3 = random.randint(1,6)
print('You got: ' +str(die3))
playerscore3 = int(playerscore3) + int(die3)
roll4 = input('Would you like to roll again?')
if roll4 == 'Yes':
die4 = random.randint(1,6)
print('You got: ' +str(die4))
playerscore4 = int(playerscore3) + int(die4)
int(playerscore4)
if playerscore3 in EvenNums:
playerscore4 = int(playerscore3) + 10
print("Player 2's total score is: " +str(playerscore4))
elif playerscore3 in OddNums:
playerscore4 = int(playerscore3) - 5
print("Player 2's total score is: " +str(playerscore4))
else:
print('Wrong input, please restart the game')
else:
print('Wrong input, please restart the game')
while True:
print("Player 1's turn")
rolling = input('would you like to roll?').lower()
if rolling == 'yes':
playerscore1 = 0
die1 = random.randint(1,6)
print('You got: ' +str(die1))
playerscore1 = int(playerscore1) + int(die1)
roll2 = input('Would you like to roll again?').lower()
if roll2 == 'yes':
die2 = random.randint(1,6)
print('You got: ' +str(die2))
playerscore1 = int(playerscore1) + int(die2)
int(playerscore1)
if playerscore1 in EvenNums:
playerscore2 = int(playerscore1) + 10
print("Player 1's total score is: " +str(playerscore2))
#player 2 section, p1 evennum
playerscoretwo()
elif playerscore1 in OddNums:
playerscore2 = int(playerscore1) - 5
print("Player 1's total score is: " +str(playerscore2))
#player 2 section, player 1 oddnum
playerscoretwo()
else:
print('Wrong input, please restart the game')
#note, section will be copy pasted with certain variables changed to make code easier to write,
and easier to test
else:
print('Wrong input, please restart the game')
elif rolling == 'no':
break
else:
print('Wrong input, please restart the game')
I have attempted to not use functions at all, however indentation becomes a drastic problem and will not run at all, even if it is a plain copy paste.
If anyone has any idea on what the problem is, it'd be greatly appreciated, thanks.
To answer you question the issue is - indentation
your
while True:
print("Player 1's turn")
rolling = input('would you like to roll?').lower()
is at the same indent level with
if rolling == 'yes':
so it never actually reaches that part since it's always runs the while loop, so you probably should put your if statement and everything that follows under the while loop.
Also as a suggestion, consider refactoring this code a bit and extract common pieces into reusable parametrized functions and call them instead, this way it would be much easier to read for everyone including yourself and since it will reduce the duplication and code amount chances that you will fall into a similar trap slightly reduce
Related
Could you, please, help me to understand how should I use try/except block and count tries at the same time.
Here is the code without try/except block (it seems it's working fine):
import random
number = random.randint(1, 10)
tries = 3
name = input('Hi! What is your name?\n')
answer = input(f'{name}, let\'s play a game! Yes or No?\n')
if answer == 'Yes':
print(f'But be aware: you have only {tries} tries!\nReady?')
chat = input('')
print('Ok, guess a number from 1 to 10!')
while tries != 0:
choice = int(input('Your choice: '))
tries -= 1
if choice > number:
print('My number is less!')
elif choice < number:
print('My number is higher!')
else:
print('Wow! You won!')
break
print(f'You have {tries} tries left.')
if tries == 0 and choice != number:
print(f'Sorry, {name}, you lost... It was {number}. Try next time. Good luck!')
else:
print('No problem! Let\'s make it another time...')
This one is with try/except block.. Not sure where should I place 'choice' variable and where count 'tries', it keeps looping and looping:
import random
number = random.randint(1, 10)
tries = 3
name = input('Hi! What is your name?\n')
answer = input(f'{name}, let\'s play a game! Yes or No?\n')
if answer == 'Yes':
print(f'But be aware: you have only {tries} tries!\nReady?')
chat = input('')
print('Ok, guess a number from 1 to 10!')
while True:
try:
choice = int(input('Your choice: '))
if 0 < choice < 11:
while tries != 0:
tries -= 1
if choice > number:
print(f'My number is less!')
elif choice < number:
print(f'My number is higher!')
else:
print('Wow! You won!')
break
print(f'You have {tries} tries left.')
if tries == 0 and choice != number:
print(f'Sorry, {name}, you lost... It was {number}. Try next time. Good luck!')
else:
print(f'Hey {name}, I said, print a number from 1 to 10!')
except ValueError:
print('Please, enter a number!')
else:
print('No problem! Let\'s make it another time...')
Thanks!
I am trying to make a simple guess the number program in python. When I run this code,an error generates saying that,"local variable 'chance' referenced before assignment". I looked up for a solution on internet but I could not rectify my error. Please help with this problem. How can I use the variable globally which is declared inside a function?
I am beginner in programming, so plese explain in simple words.
Here is the code..
Since I am a beginner,I will be pleased if my code can be rectified
import random
def Random():
chance = 3
number = random.randint(0,20)
return chance
return number
def main():
while chance > 0:
UserInput = int(input('Guess the number: '))
if UserInput == number:
print('You have guesses the secret number!')
elif UserInput > 20 and UserInput < 0:
print('Your guess is out of range!\n Try again!')
else:
chance -= 1
if chance == 1:
print('You are out of chances!')
print('Wrong Guess!\nTry again!')
print(f'You have {chance} chances left!')
Random()
main()
playAgain = input('Want to play again? ')
if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':
Random()
main()
else:
print('Thanks for playing!')
You can return a list or a tuple to the outside word:
import random
def example():
chance = 3
number = random.randint(0,20)
return (chance, number) # return both numbers as a tuple
chance, randNr = example() # decomposes the returned tuple
print(chance, randNr)
prints:
3, 17
There are more bugs in your program, f.e.:
if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':
is always True and you'll never be able to leave the game. Better would be
if playAgain.lower() in {'yes', 'yeah'}:
etc.
Here is a working example for your programs purpose:
import random
while True:
chances = 3
number = random.randint(0,20)
while chances > 0:
guess = int(input("Guess number: "))
if guess == number:
print("Correct")
break
else:
chances -= 1
print("Wrong, ", chances, " more tries to get it right.")
if chances == 0:
print ("You failed")
if not input("Play again? ")[:1].lower() == "y":
break
print("Bye.")
Read about tuples
Output:
Guess number: 1
Wrong, 2 more tries to get it right.
Guess number: 4
Correct
Play again? y
Guess number: 1
Wrong, 2 more tries to get it right.
Guess number: 2
Wrong, 1 more tries to get it right.
Guess number: 3
Wrong, 0 more tries to get it right.
You failed
Play again? n
Bye.
import random
def Random():
chance = 3
number = random.randint(0,20)
main(chance,number)
def main(chance,number):
while chance > 0:
UserInput = int(input('Guess the number: '))
if UserInput == number:
print('You have guesses the secret number!')
elif UserInput > 20 and UserInput < 0:
print('Your guess is out of range!\n Try again!')
else:
chance -= 1
if chance == 1:
print('You are out of chances!')
print('Wrong Guess!\nTry again!')
print('You have',chance,'chances left!')
Random()
playAgain = input('Want to play again? ')
if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':
Random()
else:
print('Thanks for playing!')
I am working on a number guessing game for python3 and the end goal of this is to show the user if they play more than one game that they'll receive an average number of guesses. However, I am unable to record how many times the game actually runs. Any help will do.
from random import randint
import sys
def guessinggame():
STOP = '='
a = '>'
b = '<'
guess_count = 0
lowest_number = 1
gamecount = 0
highest_number = 100
while True:
guess = (lowest_number+highest_number)//2
print("My guess is :", guess)
user_guess = input("Is your number greater than,less than, or equal to: ")
guess_count += 1
if user_guess == STOP:
break
if user_guess == a:
lowest_number = guess + 1
elif user_guess == b:
highest_number = guess - 1
print("Congrats on BEATING THE GAME! I did it in ", guess_count, "guesses")
PLAY_AGAIN = input("Would you like to play again? y or n: ")
yes = 'y'
gamecount = 0
no = 'n'
if PLAY_AGAIN == yes:
guessinggame()
gamecount = gamecount + 1
else:
gamecount += 1
print("thank you for playing!")
print("You played", gamecount , "games")
sys.exit(0)
return guess_count, gamecount
print('Hello! What is your name?')
myname = input()
print('Well', myname, ', I want you to think of number in your head and I will guess it.')
print("---------------------------------------------------------------------------------")
print("RULES: if the number is correct simply input '='")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is GREATER then the output, input '>'")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is LESS then the output, input '<'")
print("---------------------------------------------------------------------------------")
print(" ALRIGHT LETS PLAY")
print("---------------------------------------------------------------------------------")
guessinggame()
guess_count = guessinggame()
print(" it took me this many number of guesses: ", guess_count)
## each game the user plays is added one to it
## when the user wants to the game to stop they finish it and
## prints number of games they played as well as the average of guess it took
## it would need to take the number of games and add all the guesses together and divide it.
It is because you are either calling guessinggame() everytime user wants to play again or you are exiting the program. Also you are setting gamecount to 0 every time you call guessinggame(). You should move gamecount declaration and initialization out of your function. Also increment gamecount before you call guessinggame().
Here's the code which i'm not sure is completely sound but is almost correct as far as logic goes:
import random
print("Welcome to the two player guess game!")
print("A number between 1 and 100 will be chosen at random, you and the computer must try to guess it!")
print("Try to guess it in as few attempts as possible!\n")
while True:
player_guess = int(input("Take a guess: "))
if player_guess > the_number:
print("Player guess lower...\n")
if player_guess < the_number:
print("Player guess higher...\n")
if player_guess == the_number:
print("Game Over! The number was", the_number, "The Player wins.")
sys.exit()
if player_guess > the_number:
comp_guess = random.randint(1, player_guess)
print("The computer's guess was:", comp_guess)
print("Computer guess lower...\n")
if player_guess < the_number:
comp_guess = random.randint(player_guess, 100)
print("The computer's guess was:", comp_guess)
print("Computer guess higher...\n")
comp_tries += 1
if comp_guess == the_number:
print("The computer's guess was:", comp_guess)
print("Game Over! The number was", the_number, "The Computer wins.")
sys.exit()
input("\n\nPress the enter key to exit.")
Here's what happens when I run the code:
Welcome to the two player guess game!
A number between 1 and 100 will be chosen at random, you and the computer must try to guess it!
Try to guess it in as few attempts as possible!
Take a guess: 11
Take a guess: 12
Take a guess: 13
Take a guess:
When ever I run it, the program is supposed to tell me whether or not I need to guess higher or lower all while the computer guesses but instead it just keeps asking for a number.
while True:
player_guess = int(input("Take a guess: "))
These two lines are the problem. Python is all about indents and the indented line of code that says player_guess = is within the while loop and since True is always True the player_guess = line is going to run forever. Try changing it so that you indent all the lines like so:
while True:
player_guess = int(input("Take a guess: "))
if player_guess > the_number:
print("Player guess lower...\n")
if player_guess < the_number:
print("Player guess higher...\n")
if player_guess == the_number:
print("Game Over! The number was", the_number, "The Player wins.")
sys.exit()
if player_guess > the_number:
comp_guess = random.randint(1, player_guess)
print("The computer's guess was:", comp_guess)
print("Computer guess lower...\n")
if player_guess < the_number:
comp_guess = random.randint(player_guess, 100)
print("The computer's guess was:", comp_guess)
print("Computer guess higher...\n")
comp_tries += 1
if comp_guess == the_number:
print("The computer's guess was:", comp_guess)
print("Game Over! The number was", the_number, "The Computer wins.")
sys.exit()
input("\n\nPress the enter key to exit.")
Or instead of sys.exit() You could just do break
I'm currently making a simple rogue-like dungeon game for an assignment, i'm pretty new to coding so I've run into problems along the way. I want my game to end when the player's health reaches 0 so i've written this function
def main_game():
global room_count
global player_health
welcome_text()
while player_health >= 1:
room_enter(empty_room, ghost_room, monster_room, exit_room)
else:
print("Game Over :(")
print("Number of rooms entered: ", room_count)
time.sleep(7)
quit()
For whatever reason when the health reaches 0 the game continues to carry on and I can't figure out why, it's far from finished but here's the full game code below:
import time
import random
import sys
player_health = 1
room_count = 1
def scroll_text(s):
for c in s:
sys.stdout.write( "%s" % c )
sys.stdout.flush()
time.sleep(0.03)
def welcome_text():
scroll_text("\nYou wake up and find yourself in a dungeon.")
time.sleep(1.5)
scroll_text("\nYou have no idea how long you have been trapped for.")
time.sleep(1.5)
scroll_text("\nSuddenly, one day, for no apparent reason, your cell door opens.")
time.sleep(1.5)
scroll_text("\nEven though weak from having no food, you scramble out as the door closes behind you.")
time.sleep(1.5)
scroll_text("\nYou see many paths and many rooms ahead of you.")
print("\n ")
print( "-"*20)
def room_enter(empty_room, ghost_room, monster_room, exit_room):
global player_health
global room_count
security = True
while security == True:
direction = input("\nYou have the option to go Left (l), Forward (f), or Right (r), which direction would you like to go? ")
if direction == "l" or direction == "f" or direction == "r":
security == False
room_no = random.randint(1,8)
if room_no == 1 or room_no == 2 or room_no == 3:
empty_room()
room_count = room_count + 1
if room_no == 4 or room_no == 5 or room_no == 6:
ghost_room()
room_count = room_count + 1
if room_no == 7:
monster_room()
room_count = room_count + 1
if room_no == 8:
exit_room()
room_count = room_count + 1
else:
print("\nInvalid Entry")
return player_health
def empty_room():
global player_health
scroll_text("You enter a cold empty room, doesn't look like anyone has been here in years.")
player_health = player_health - 1
print("\n ")
print("-"*20)
print("| Your Health: ", player_health, "|")
print("-"*20)
print("Number of rooms entered: ", room_count)
return player_health
def ghost_room():
global player_health
scroll_text("You enter a room and feel a ghostly presence around you")
time.sleep(1)
scroll_text("\nWithout warning, the ghostly mist surrounding you pools together and the shape of a human-like figure emerges.")
time.sleep(1)
scroll_text("\nI AM THE SPIRIT OF AN UNFORTUNATE EXPLORER KILLED IN THEIR PRIME, DOOMED TO SPEND AN ETERNITY TRAPPED IN THIS CHAMBER!")
time.sleep(1)
scroll_text("\nANSWER MY QUESTION MORTAL AND CONTINUE IN PEACE, GET IT WRONG HOWEVER AND YOU WILL BE BEATEN!")
time.sleep(1)
x = random.randint(1,500)
y = random.randint(1,500)
time.sleep(1)
print("\nTELL ME WHAT", x, "PLUS", y, "IS!")
okay = False
while not okay:
try:
player_answer = int(input("\nWHAT IS YOUR ANSWER?! "))
okay = True
if player_answer == x+y:
scroll_text("\nCONGRATULATIONS YOU GOT IT CORRECT! HAVE A BIT OF HEALTH!")
player_health = player_health + 2
else:
scroll_text("\nUNFORTUNATELY FOR YOU THAT ANSWER IS WRONG! PREPARE FOR THE BEATING!")
player_health = player_health - 1
print("\n ")
print("-"*20)
print("| Your Health: ", player_health, "|")
print("-"*20)
print("Number of rooms entered: ", room_count)
except ValueError:
print("\nInvalid Entry")
return player_health
def monster_room():
global player_health
scroll_text("\nYou hear grunting noises as you enter the room and your worst fears are confirmed when your eyes meet the gaze of a giant monster guarding the other doors.")
time.sleep(1)
scroll_text("\nWith no way to fight the creature, you manage to slip around it however as you are making your escape the beast swipes at you and lands a blow to your back.")
player_health = player_health - 5
print("\n ")
print("-"*20)
print("| Your Health: ", player_health, "|")
print("-"*20)
print("Number of rooms entered: ", room_count)
return player_health
def exit_room():
global player_health
scroll_text("\nYou stumble into the room, almost passing out from the lack of food and energy.")
time.sleep(1)
scroll_text("\nIs that...")
time.sleep(1)
scroll_text("\n... You can't believe your eyes! It's the exit from the dungeon at last!")
time.sleep(1)
print("\nWINNER WINNER CHICKEN DINNER")
print("\n ")
print("-"*21)
print("| Final Health: ", player_health, "|")
print("-"*21)
print("Number of rooms entered: ", room_count)
return player_health
def main_game():
global room_count
global player_health
welcome_text()
while player_health >= 1:
room_enter(empty_room, ghost_room, monster_room, exit_room)
else:
print("Game Over :(")
print("Number of rooms entered: ", room_count)
time.sleep(7)
quit()
main_game()
In room_enter you have a typo - security == False instead of security = False, causing an infinite loop in room_enter, so the condition in main_game is never checked.
it is very simple,
if direction == "l" or direction == "f" or direction == "r":
security == False
you basically never set security to false. It should be
if direction == "l" or direction == "f" or direction == "r":
security = False
Btw, if you declare playerHealth to be global, you don't need to return it at the end of every function you'll have the current value anyways.
Also, I think you don't need those parameters on "room_enter" since they are just functions to be executed. If you find an error saying that they are not declared, just move the declaration above the function room_enter
Let me know if something wasn't clear! Happy coding!