d20 system mechanics in Godot - godot

I'm having trouble with the code below. The attacker is doing two rounds before reversing the turn, and the correct thing is to have a round of attack and alternate. Another detail is that the 'for' doesn't seem to be working... it gets information on how much dice the player has, but for some reason, the 'print' I put doesn't return 2 values (for example, for a player with two dice). I believe there is a lot to improve, creating more functions, but I am a beginner.
AutoLoad:
extends Node2D
var enemy_turn : bool = false
var critical_Hit : bool = false
func _start_combat(player, enemy):
if enemy_turn == false:
turn(enemy, player)
else:
turn(player, enemy)
func roll(dice) -> int:
var random_number = RandomNumberGenerator.new()
random_number.randomize()
return random_number.randi_range(1, dice)
func turn(target, attacker):
print(attacker.char_name, " attack ", target.char_name)
var iniciative_roll = roll(20)
print("Iniciative d20: ", iniciative_roll)
if iniciative_roll == 20:
print("Critical Hit!") #Tenho que verificar se eu estou saindo daqui sem passar para baixo visto que 20 >= abs()
critical_Hit = true
elif iniciative_roll >= abs(target.ac - attacker.thac0):
critical_Hit = false
else:
print(attacker.char_name, " miss.")
enemy_turn =! enemy_turn
_start_combat(attacker,target)
return
var dmg_roll : int = 0
for n in attacker.row:
dmg_roll += roll(attacker.dice)
print(dmg_roll)
return damage(target, attacker, dmg_roll)
func damage(target, attacker, aux):
if critical_Hit == true:
target.hp -= 2 * aux
else:
target.hp -= aux
print(attacker.char_name, " do ", aux, " damage ", target.char_name)
if target.hp <= 0:
target._death()
else:
enemy_turn =! enemy_turn
_start_combat(attacker,target)
Taking advantage, can the arguments that a function receives be the same as the variables sent? Is this not very ugly or wrong? Ex:
func turn(target, attacker):
...
return damage(target, attacker, dmg_roll)
func damage(target, attacker, dmg_roll):
...
Thanks

The attacker is doing two rounds before reversing the turn, and the correct thing is to have a round of attack and alternate.
Have another look at this code:
func _start_combat(player, enemy):
if enemy_turn == false:
turn(enemy, player)
else:
turn(player, enemy)
It will flip the order of the arguments of turn depending on enemy_turn.
The parameters of turn are like this:
func turn(target, attacker):
And then they do this:
enemy_turn =! enemy_turn
_start_combat(attacker,target)
Remember that enemy_turn controls if _start_combat flips the arguments or not. But also notice you are calling _start_combat with the arguments flipped. So there is always a flip, but depending on enemy_turn there is an extra flip… And the flips cancels out resulting in a repeated turn.
There is an extra wrinkle in that damage does the same thing that turn does:
enemy_turn =! enemy_turn
_start_combat(attacker,target)
This is the logic we need to change, and preferably we want to change it in a single place. A single source of truth of how to change turns.
You should refactor repetition out of damage. Furthermore…
I believe you want to have turn not be concerned with the order. Otherwise you would have put the logic you have in _start_combat inside of turn. Thus, don't have turn be concerned with the order at all! It should not be manipulating enemy_turn =! enemy_turn. In fact, it should not be calling _start_combat.
So we are separating these two concerns:
How to switch turns
How to execute turns
To do that we would put the logic of switching turn in _start_combat. It can have a loop where it calls turn one way, and then the other. Ah, but that reveals that we need to extract the end of combat logic.
Currently you are not having an stack overflow because combat is short enough. But your stack will be calls to _start_combat that call turn that call _start_combat that call turn that call _start_combat and so on.
Currently the end of combat logic is in damamge:
if target.hp <= 0:
target._death()
It ends combat by not calling _start_combat again.
So you can do something like this:
func _start_combat(player, enemy):
var target
var attacker
while true:
if enemy_turn == false:
target = enemy
attacker = player
else:
target = player
attacker = enemy
turn(target, attacker)
if target.hp <= 0:
target._death()
break
EDIT: In the above code I forgot to change enemy_turn. It should be in the loop:
func _start_combat(player, enemy):
var target
var attacker
while true:
if enemy_turn == false:
target = enemy
attacker = player
else:
target = player
attacker = enemy
turn(target, attacker)
if target.hp <= 0:
target._death()
break
enemy_turn =! enemy_turn
Then damage can be just this:
func damage(target, attacker, aux):
if critical_Hit == true:
target.hp -= 2 * aux
else:
target.hp -= aux
print(attacker.char_name, " do ", aux, " damage ", target.char_name)
And remove these from turn too:
enemy_turn =! enemy_turn
_start_combat(attacker,target)
I can tell you right now that the above code likely won't stand in the long run. Presumably you want to add animations, sound effects, or similar... Or simply wait for user input. Then you want to use yield. And if yield you problems (and it might) I will strongly encourage looking into using signals instead of method calls. You can define your own signals, emit them, connect methods to them. That is not for this answer, just something you might want to look into.
Ok, the other thing:
Another detail is that the 'for' doesn't seem to be working
Look here you are returning on the first iteration:
for n in attacker.row:
dmg_roll += roll(attacker.dice)
print(dmg_roll)
return damage(target, attacker, dmg_roll)
My intuition would be to call damage to be outside of the loop:
for n in attacker.row:
dmg_roll += roll(attacker.dice)
print(dmg_roll)
return damage(target, attacker, dmg_roll)
In fact, damage does not return, and you don't use the return value of turn, so you could also remove the return keyword…
for n in attacker.row:
dmg_roll += roll(attacker.dice)
print(dmg_roll)
damage(target, attacker, dmg_roll)
So if you actually meant to call damage in a loop, you can also do that:
for n in attacker.row:
dmg_roll += roll(attacker.dice)
print(dmg_roll)
damage(target, attacker, dmg_roll)

extends Node2D
var enemy_turn : bool = false
var critical_Hit : bool = false
func _start_combat(player, enemy):
var target
var attacker
while true:
if enemy_turn == false:
target = enemy
attacker = player
else:
target = player
attacker = enemy
turn(target, attacker)
if target.hp <= 0:
target._death()
break
func roll(dice) -> int:
var random_number = RandomNumberGenerator.new()
random_number.randomize()
return random_number.randi_range(1, dice)
func turn(target, attacker):
print(attacker.char_name, " atack ", target.char_name)
var iniciative_roll = roll(20)
print("Iniciative d20: ", iniciative_roll)
if iniciative_roll == 20:
print("Critical Hit!") #Tenho que verificar se eu estou saindo daqui sem passar para baixo visto que 20 >= abs()
critical_Hit = true
elif iniciative_roll >= abs(target.ac - attacker.thac0):
critical_Hit = false
else:
print(attacker.char_name, " miss.")
return
var dmg_roll : int = 0
for n in attacker.row:
dmg_roll += roll(attacker.dice)
print(dmg_roll)
damage(target, attacker, dmg_roll)
func damage(target, attacker, dmg_roll):
if critical_Hit == true:
target.hp -= 2 * dmg_roll
else:
target.hp -= dmg_roll
print(attacker.char_name, " do ", dmg_roll, " damage ", target.char_name)
See the DEBUG:
Player made an attack action...
Jobson atack Globin
Iniciative d20: 2
Jobson miss.
Jobson atack Globin
Iniciative d20: 16
10
Jobson do 10 damage Globin
Jobson atack Globin
Iniciative d20: 5
Jobson miss.
Jobson atack Globin
Iniciative d20: 13
16
Jobson do 16 damage Globin
Globin DIE!
He didn't reverse the turn.
And the curious thing is that precisely, the action occurs instantly. LOL
I didn't think to get around it for now. yield it doesn't seem good to use, it seems to give a lot of bugs.

Related

Making and updating score system in python (out of function)

first of all, I'm new to Python.
I want to increase "humanscore" or "computerscore" in win and lose conditions.
This increase occurs in the win and lose functions, that is, +1 is added to the variables, but it becomes 0 again when you switch to the other function.
import random
R = "ROCK"
P = "PAPER"
S = "SCİSSORS"
print("Welcome to 'Rock Paper Scissors' game!\n")
humanscore = 0
computerscore = 0
def end():
print("\n\n\n\n\n")
print("Computer's weapon =", computer)
print("Your weapon =", human, "\n\n\n")
def win(humanscore):
print("You win!")
humanscore += 1
return humanscore
def lose(computerscore):
print("You lose!")
computerscore += 1
return computerscore
def Score(humanscore, computerscore):
score = (f"Human Score = {humanscore}, Computer Score = {computerscore}")
print(score)
while True:
allweapon = (R, P, S)
computer = random.choice(allweapon)
print(f"1. {R}\n2. {P}\n3. {S}\n")
human = str.upper(input("Choose your weapon!\n"))
if human == R:
if computer == S and human == R:
end()
win(humanscore)
Score(humanscore, computerscore)
elif computer == P and human == R:
end()
lose(computerscore)
Score(humanscore, computerscore)
if human == S:
if computer == P and human == S:
end()
win(humanscore)
Score(humanscore, computerscore)
elif computer == R and human == S:
end()
lose(computerscore)
Score(humanscore, computerscore)
if human == P:
if computer == S and human == P:
end()
lose(computerscore)
Score(humanscore, computerscore)
elif computer == R and human == P:
end()
win(humanscore)
Score(humanscore, computerscore)
if human == computer:
end()
Score(humanscore, computerscore)
print("Tied!")
if human != R:
print("There is no such weapon!\n")
I want to increase the score system properly.

I am trying to simplify my code by making a function outside of a while loop but the conditionals I want to put in function have break statements

Below is a sample of my code. I am trying to make a function for my 4th conditional statement outside of the while loop, but some of the nested conditionals have a break statement. How can I create the function outside of the loop but still break out of the loop when I need too.
current_room = 'security room'
directions = ['north', 'south', 'east', 'west']
all_items = ['Thermal Rifle', 'Blood Wine', 'Protein Bar', 'Bandages', 'Keys', 'Time Grenade', 'Note']
while True:
# Print current room
print('-' * 60)
print(f'You are in {current_room.title()}')
print('Inventory:', inventory)
prompt = 'What is your move:\n$ '
user_command = input(prompt).lower().strip()
split_command = user_command.split(' ', 1)
if user_command == 'quit':
print()
print('Exiting game....')
break
elif user_command == 'show items':
print(all_items)
time.sleep(1)
elif user_command == 'help':
menu()
time.sleep(2)
# if command direction is in rooms update current room to new room
elif split_command[0] == 'go':
# This is code I want to turn into a function outside of the loop
# but my issue is the two break statements in the code
if split_command[1] in directions:
if split_command[1] in rooms[current_room]:
current_room = rooms[current_room][split_command[1]]
# if command direction is kahmeetes office congratulate and break out of loop
if current_room == 'kahmeete\'s office' and len(inventory) == len(all_items):
print(f'\nCongratulations! You have collected all items and reached {current_room}!')
print('You have successfully defeated Kahmeete and saved the Princess of Time!')
break
elif current_room == 'kahmeete\'s office' and len(inventory) != len(all_items):
print(f'\nYou are in {string.capwords(current_room)}')
print('\nYou do not have enough items to defeat Kahmeete!')
print('Kahmeete used the T.T.A.D. "Time Traveling Alien Device on you!"')
print('You are lost in the past and you will never rescue the Princess of Time!')
break
else:
print('You cannot go that way!')
time.sleep(1)
Here is the basis of the function:
def moving_rooms(command, direction, room, current_loc, item, all_item_list):
if command[1] in direction:
if command[1] in room[current_loc]:
current_loc = room[current_loc][command[1]]
# if command direction is cellar congratulate and break out of loop
if current_loc == 'kahmeete\'s office' and len(item) == len(all_item_list):
print(f'\nCongratulations! You have collected all items and reached {string.capwords(current_loc)}!')
print('You have successfully defeated Kahmeete and saved the Princess of Time!')
# This is where the break statement would be
elif current_loc == 'kahmeete\'s office' and len(item) != len(all_item_list):
print(f'\nYou are in {string.capwords(current_loc)}')
print('You do not have enough items to defeat Kahmeete!')
print('Kahmeete used the T.T.A.D. "Time Traveling Alien Device on you!"')
print('You are lost in the past and you will never rescue the Princess of Time!')
# This would of been where the break statement was
else:
print('You cannot go that way!')
time.sleep(1)
else:
print('Invalid input')
time.sleep(1)
Your function can return a value that tells the calling code if it should break the loop or not.
elif split_command[-] == 'go':
done = handle_go_command(args)
if done:
break
Now, just return True in your function when you wanted to break, and return False where you want the outer loop to keep going.

Rock-Paper-Scissors-Pencil-Fire game with functions doesn't work

I am trying to make a game of rock-paper-scissors-pencil-fire with functions and it doesn't work. It seems that it can't go inside the compare function(named findwinner()) and return the results.
i looked throw the web for help but i couldn't find anything. i tried assigning the variables in many different ways but with no luck.
python
#Rock-Paper-Scissors-Fire-Pencil Game
#Game:
#The player must choose his weapon and 'fight' against the computer following #the rules above.
#The player can choose between the following: Rock, Scissors, Fire, Pencil and #Paper.
#Rules: The rock beats the scissors, the scissors beat the fire, the fire #beats the pencil, the pencil beats the paper and the paper beats the rock
#Player1 is the human player
#Player2 is the computer
import random
#The game welcomes the player.
print("Wellcome to the Rock-Paper-Scissors-Fire-Pencil game!")
#The player can play as many times as he/she wants until he/she type anything #else except yes in the "Do you want to play again?" question.
def getuser():
choices = ["rock", "scissors", "fire", "pencil", "paper"]
#The computer chooses it's 'weapon'.
player2 = choices[random.randint(0,4)]
player1 = None
while player1 not in choices:
#The player must choose his/her 'weapon'
player1 = input("\n PLAYER 1 - Please make a choice (rock/paper/scissors/fire/pencil):")
print (f"\nPlayer1 choose {player1}")
print (f"\nPlayer2 choose {player2}")
return ()
def findwinner():
winner = None
p1 = getuser()[1]
p2 = getuser()[2]
#The game keeps how many times the player1 has won, lost or tied with the computer in the variables bellow.
wins = 0
losses = 0
ties = 0
#The game compares the choises of the players and announces if the human player won, lost or tied with the computer.
#Then it adds the win, the lost or the tie to the summary of wins, losses or ties.
if p1 != p2:
if p1 == "rock":
if p2 == "scissors" or p2 == "pencil" or p2 == "fire":
print("\n Player1 wins this round!")
winner = p1
wins += 1
else:
print("\n Player2 wins this round!")
winner = p2
losses += 1
if p1 == "paper":
if p2 == "rock":
print("\n Player1 wins this round!")
winner = p1
wins += 1
else:
print("\n Player2 wins this round!")
winner = p2
losses += 1
if p1 == "scissors":
if p2 == "paper" or p2 == "pencil":
print("\n Player1 wins this round!")
winner = p1
wins += 1
else :
print("\n Player2 wins this round!")
winner = p2
losses += 1
if p1 == "pencil":
if p2 == "paper":
print("\n Player1 wins this round!")
winner = p1
wins += 1
else:
print("\n Player2 wins this round!")
winner = p2
losses += 1
if p1 == "fire":
if p2 == "paper" or p2 == "scissors" or p2 == "pencil":
print("\n Player1 wins this round!")
winner = p1
wins += 1
else:
print("\n Player2 wins this round!")
winner = p2
losses += 1
else:
print("\n The round is a tie!")
winner = None
ties += 1
print (f"\nThe winner of this round is {winner}")
return (winner, wins, losses, ties)
play_again = "yes"
while play_again == "yes":
#The game shows the choises of the players.
player1 = getuser()[1]
player2 = getuser()[2]
findwinner(player1, player2)
#The game askes the player if he/she wants to play again.
play_again = input("\nDo you want to play again?:")
else:
#If the player doesn't want to play again, the game prints the results of all the rounds of the game and closes.
print(f"The player1 won {findwinner()[2]} times")
print(f"The player1 lost {findwinner()[3]} times")
print(f"The player1 tied {findwinner()[4]} times")
print("\n Good Bye")
You got a couple of problems:
getuser() just prints the choices but does not return them, to fix this just change the return to player1, player2
findwinner() does not get any parameters according to the signature, you have to change the signature to findwinner(p1, p2)
If you are receiving the players choices by argument in findwinner(), you don't have to call getuser() again.
Wins, losses and ties counters are going to be reset each time you call findwinner() you have to declare them as globals outside the function, and then update them inside the function.
After fixing these, you end up with this:
import random
#The game keeps how many times the player1 has won, lost or tied with the computer in the variables bellow.
# 4 FIX) declare counters as globals
wins = 0
losses = 0
ties = 0
#The game welcomes the player.
print("Welcome to the Rock-Paper-Scissors-Fire-Pencil game!")
#The player can play as many times as he/she wants until he/she type anything
#else except yes in the "Do you want to play again?" question.
def getuser():
choices = ["rock", "scissors", "fire", "pencil", "paper"]
#The computer chooses it's 'weapon'.
player2 = choices[random.randint(0,4)]
player1 = None
while player1 not in choices:
#The player must choose his/her 'weapon'
player1 = input("\n PLAYER 1 - Please make a choice (rock/paper/scissors/fire/pencil):")
print (f"\nPlayer1 choose {player1}")
print (f"\nPlayer2 choose {player2}")
return player1, player2 # 1 FIX) return players choice
# 2 FIX) add players choice as parameters
def findwinner(p1, p2):
winner = None
# 3 FIX) do not call getuser since you have the player choices as arguments
# 4 FIX) use them as globals in the function scope
global wins, losses, ties
#The game compares the choises of the players and announces if the human player won, lost or tied with the computer.
#Then it adds the win, the lost or the tie to the summary of wins, losses or ties.
if p1 != p2:
if p1 == "rock":
if p2 == "scissors" or p2 == "pencil" or p2 == "fire":
print("\n Player1 wins this round!")
winner = p1
wins += 1
else:
print("\n Player2 wins this round!")
winner = p2
losses += 1
if p1 == "paper":
if p2 == "rock":
print("\n Player1 wins this round!")
winner = p1
wins += 1
else:
print("\n Player2 wins this round!")
winner = p2
losses += 1
if p1 == "scissors":
if p2 == "paper" or p2 == "pencil":
print("\n Player1 wins this round!")
winner = p1
wins += 1
else :
print("\n Player2 wins this round!")
winner = p2
losses += 1
if p1 == "pencil":
if p2 == "paper":
print("\n Player1 wins this round!")
winner = p1
wins += 1
else:
print("\n Player2 wins this round!")
winner = p2
losses += 1
if p1 == "fire":
if p2 == "paper" or p2 == "scissors" or p2 == "pencil":
print("\n Player1 wins this round!")
winner = p1
wins += 1
else:
print("\n Player2 wins this round!")
winner = p2
losses += 1
else:
print("\n The round is a tie!")
winner = None
ties += 1
print (f"\nThe winner of this round is {winner}")
return winner # 4 FIX) no need to return the counters anymore
play_again = "yes"
while play_again == "yes":
#The game shows the choises of the players.
player1, player2 = getuser() # 1 FIX) save player choices
findwinner(player1, player2)
#The game askes the player if he/she wants to play again.
play_again = input("\nDo you want to play again?:")
else:
#If the player doesn't want to play again, the game prints the results of all the rounds of the game and closes.
# 4 FIX) Use the global variables
print(f"The player1 won {wins} times")
print(f"The player1 lost {losses} times")
print(f"The player1 tied {ties} times")
print("\n Good Bye")
I can tell you have problems understanding function returns. Each time you do findwinner() you are calling the function AGAIN, to run it only once and save the result you assign it to a variable. As done for getuser():
player1, player2 = getuser()

Unable to record how many times my while loop runs- Python3

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

How can I get my game to finish when the player runs out of health?

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!

Resources