I am working on a simple text based battle game, and I have come across a(nother) problem. I have a main function and a battle function and in the battle function once you finish the battle, you gain a certain amount of XP, which is then (or should be) remembered by changing the value of player1.xp. Right after the battle sequence I set it so in the code if player1.xp >= 1 it will change the value of player1.level to "2". Though, whenever I run the code, for some reason the xp value gets lost when the battle function is finished. I know this because it prints out the value of player1.xp after the battle function, and it says "0". Here is the code:
import random
xp1 = random.randint(1,2)
class player:
def __init__ (self, name, health, strength, defense, potion, xp, level):
self.health = health
self.strength = strength
self.defense = defense
self.name = name
self.potion = potion
self.xp = xp
self.level = level
def changeHealth(self, h):
self.health = h
def addLevel(self):
self.level += 1
def subHealth(self, num):
self.health -= num
return self.health
def subPotion(self):
self.potion -= 1
return self.health
def addPotion(self, num1):
self.potion += num1
def addHealth(self):
self.health +=2
def addXP(self):
self.xp += xp1
def battle1(enemy, player1, name1):
player1 = player(name1, player1.health, player1.strength, player1.defense, player1.potion, player1.xp, player1.level)
enemy = player("Rat", enemy.health, enemy.strength, enemy.defense, player1.potion, enemy.xp, enemy.level)
print("Fight!")
s = 0
while s == 0:
attack =input("Type 1 to attack, type 2 to use a potion.")
if attack == "1":
enemy.subHealth(15)
elif attack == "2":
if player1.potion > 0:
print("You used a potion.")
elif player1.potion <= 0:
print("You don't have any potions! You are forced to attack.")
enemy.subHealth(15)
else:
print("Your life depends on this!")
if enemy.health <= 0:
print("Congratulations, you won! You recieved", xp1, "xp!")
player1.addXP()
s = 2
def main():
name1 = input("What would you like your name to be?")
print("Hello,", name1, "you are on a quest to save otis from the evil Dongus. You must slay him, or Otis will poop.")
player1 = player(name1, 10, 2, 1, 0, 0, 1)
enemy = player("Rat", 15, 0, 0, 0, 0, 0)
pick = input("You were walking along the path and found a potion! Press 'p' to pick it up.")
if pick == "p":
print("You added a potion to your inventory.")
player1.addPotion = 1
else:
print("You have no potions, you should probably pick this one up.")
print("You added a potion to your inventory.")
player1.addPotion = 1
battle1(enemy, player1, name1)
print(player1.xp)
if player1.xp >= 1:
print("You leveled up. You are now level 2.")
player1.addLevel()
else:
print("You have 0 xp.")
main()
Does anybody have a clue why this is happening? Thanks!
In main you create two player (should be Player) instances, and pass them to battle1:
player1 = player(name1, 10, 2, 1, 0, 1)
enemy = player("Rat", 15, 0, 0, 0, 0)
battle1(enemy, player1, name1)
In battle1 you create two new player instances, based on the two argument instances, modify the new instances, and don't return anything:
# take three parameters (one of which is unnecessary)
def battle1(enemy, player1, name1):
# replace two of the arguments with copies
player1 = player(name1, player1.health, player1.strength, player1.defense, player1.xp, player1.level)
enemy = player("Rat", enemy.health, enemy.strength, enemy.defense, enemy.xp, enemy.level)
# original arguments now inaccessible
It is not clear why you expected that this would work, but the minimal fix is to stop creating new instances in battle1. Also, it might be clearer if you moved xp1 = random.randint(1,2) inside battle1.
Related
I have created this game. User is giving a number from 1 to 100. Computer is trying to guess it. User is giving hint to computer to go lower or go higher. I am open for any feedback.
Thank you in advance.
import os
import random
os.system('clear')
user = int(input("Please enter a number between 1-100: "))
print("Your Number is: " + str(user))
comp_list = list(range(1,101))
comp_selection = random.choice(comp_list)
count = 0
def game(num, a = 1, b = 100):
global count
print("I have chosen " + str(num) + "\nShould I go Higher or Lower or Correct? ")
user = input("Your Selection: ")
if user == "L":
count = count + 1
low_game(a, num)
elif user == "H":
count = count + 1
high_game(num, b)
else:
print("I have guessed correctly in " + str(count) + " tries")
def low_game(old_low, new_High):
x = new_High
new_comp_list = list(range(old_low, x))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection, old_low, x)
def high_game(new_low, old_high):
x = new_low + 1
new_comp_list = list(range(x, old_high))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection,x, old_high)
game(comp_selection)
I agree, you have over complicated the game with recursive functons.
Here is a much simplified game with penalties for player who does not answer correctly
or falsifies the answer:)
import sys, random
wins = 0
loss = 0
while 1:
user = input('Please enter a number between 1-100: (return or x = quit) > ' )
if user in [ '', 'x' ]:
break
elif user.isnumeric():
user = int( user )
if user < 1 or user > 100:
sys.stdout.write( 'Number must be between 1 and 100!!\n' )
else:
low, high, count = 1, 100, 0
while 1:
p = random.randint( low, high )
count += 1
while 1:
answer = input( f'Is your number {p}? Y/N > ').upper()
if answer in [ 'Y','N' ]:
break
else:
sys.stderr.write( 'Answer must be Y or N\n' )
if answer == 'N':
if p != user:
if input( f'Is my number (H)igher or (L)ower? > ').upper() == 'H':
if user < p:
high = p - 1
else:
sys.stderr.write( f'Wrong!! Your number was lower. You loss\n' )
loss =+ 1
break
else:
if user > p:
low = p + 1
else:
sys.stderr.write( f'Wrong!! Your number higher. You loss\n' )
loss =+ 1
break
else:
sys.stderr.write( f'Cheat!! Your number is {user}!! You loss\n')
loss =+ 1
break
else:
if user == p:
sys.stdout.write( f'I guessed Correctly in {count} guesses\n' )
wins += 1
else:
sys.stderr.write( f'Cheat!! This is not your number. You loss\n' )
loss =+ 1
break
print( f'Computer won = {wins} : You lost = {loss}' )
Happy coding.
You have really overly complicated the problem. The basic process flow is to have the computer guess a number within a fixed range of possible numbers. If the guess is incorrect, the user tells the computer how to adjust the list by either taking the guessed number as the low end or the high end of the guessing range. So to accomplish this, I would do the following:
from random import randint
# Function to request input and verify input type is valid
def getInput(prompt, respType= None):
while True:
resp = input(prompt)
if respType == str or respType == None:
break
else:
try:
resp = respType(resp)
break
except ValueError:
print('Invalid input, please try again')
return resp
def GuessingGame():
MAX_GUESSES = 10 # Arbritray Fixed Number of Guesses
# The Game Preamble
print('Welcome to the Game\nIn this game you will be asked to provide a number between 1 and 100 inclusive')
print('The Computer will attempt to guess your number in ten or fewer guesses, for each guess you will respond by telling the computer: ')
print('either:\n High - indicating the computer should guess higher\n Low - indicating the computer should guess lower, or')
print(' Yes - indicating the computer guessed correctly.')
# The Game
resp = getInput('Would You Like To Play?, Respond Yes/No ')
while True:
secret_number = None
if resp.lower()[0] == 'n':
return
guess_count = 0
guess_range = [0, 100]
secret_number = getInput('Enter an Integer between 1 and 100 inclusive', respType= int)
print(f'Your secret number is {secret_number}')
while guess_count <= MAX_GUESSES:
guess = randint(guess_range[0], guess_range[1]+1)
guess_count += 1
resp =getInput(f'The computer Guesses {guess} is this correct? (High?Low/Yes) ')
if resp.lower()[0] == 'y':
break
else:
if resp.lower()[0] == 'l':
guess_range[1] = guess - 1
else:
guess_range[0] = guess + 1
if guess == secret_number:
print (f'The Computer has Won by Guessing your secret number {secret_number}')
else:
print(f'The Computer failed to guess your secret number {secret_number}')
resp = getInput('Would You Like To Play Again?, Respond Yes/No ')
# Import Modules
from Dice import dice
d10 = dice(10,1) #I use dice, but you could just as easily use random.randint()
d4 = dice(4,1)
d20 = dice(20,1)
# Assign Classes
class Player_Character:
inventory = []
def __init__(self, HP, MaxHP, AC, ToHitAdjustment, Surprise_Adjustment,
Initiative_Adjustment, Exp, \
MaxExp, Gold, Damage):
self.HP = int(HP)
self.MaxHP = int(MaxHP)
self.AC = int(AC)
self.ToHitAdjustment = int(ToHitAdjustment)
self.Surprise_Adjustment = int(Surprise_Adjustment)
self.Initiative_Adjustment = int(Initiative_Adjustment)
self.Exp = int(Exp)
self.MaxExp = int(MaxExp)
self.Gold = int(Gold)
self.Damage = int(Damage)
this next section may be where the error is, although I doubt it because when I run through the code the character is assigned exp and gold and they seem to grow at the correct rate.
def attack(self, goblin, Player_Character):
Player_attack_roll = d20.die_roll() + Player_Character.ToHitAdjustment
if (Player_attack_roll >= goblin.AC):
print('you did', Player_Character.Damage, 'damage')
goblin.HP -= Player_Character.Damage
if (goblin.HP <= 0):
print("congratulations you killed the goblin")
Player_Character.Exp += goblin.ExpReward
if (Player_Character.Exp >= Player_Character.MaxExp):
print("Congratulations you have leveled up")
Player_Character.LevelUp()
print('you have', Player_Character.Exp, 'exp ')
Player_Character.Gold += goblin.Gold
print("you have", Player_Character.Gold, 'gold ')
del goblin
else:
print("You miss ")
def flee(self):
print("you run away ")
quit()
def heal(self, Player_Character):
Player_Character.HP += d10.die_roll()
if Player_Character.HP >= Player_Character.MaxHP:
Player_Character.HP = Player_Character.MaxHP
print("You have reached max HP ")
this may be where the error is, I expect it to assign the variable name 'MrHezy' which was previously assigned to Player_Character to FighterLvl1, but when I run the code it continuously says that I am leveling up, which I am unsure if that means that the character is remaining as Player_Character, or if there is something else wrong
def LevelUp(self):
MrHezy = FighterLvl1(25, 25, 15, 10, 2, 2, 25, 75, 20, d10.die_roll()+5)
This next section has code is where my question of inheritance comes into play. Even though FighterLvl1 has inherited from (Player_Character) my IDE says things like "unresolved attribute reference 'Exp' for FighterLvl1" Also I am unsure if adding the 'attack' method under FighterLvl1 does anything; I expect it to overwrite the 'attack' method from Player_Character
class FighterLvl1(Player_Character):
def attack(self, goblin, Player_Character):
Player_attack_roll = d20.die_roll() + Player_Character.ToHitAdjustment
if (Player_attack_roll >= goblin.AC):
print('you did', Player_Character.Damage, 'damage')
goblin.HP -= Player_Character.Damage
if (goblin.HP <= 0):
print("congratulations you killed the goblin")
FighterLvl1.Exp += goblin.ExpReward
if (FighterLvl1.Exp >= FighterLvl1.MaxExp):
print("Congratulations you have leveled up")
FighterLvl1.LevelUp()
print('you have', FighterLvl1.Exp, 'exp ')
FighterLvl1.Gold += goblin.Gold
print("you have", FighterLvl1.Gold, 'gold ')
del goblin
def LevelUp(self):
MrHezy = FighterLvl2(Player_Character)
class FighterLvl2(Player_Character):
def LevelUp(self):
MrHezy = FighterLvl3(Player_Character)
class FighterLvl3(Player_Character):
def MaxLevel(self):
print("Congratulations you are level 3, this is the highest programmed level in the game
")
class goblin:
def __init__(self, HP, MaxHP, AC, ToHitAdjustment, Surprise_Adjustment,
Initiative_Adjustment, \
ExpReward, Gold, Damage):
self.HP = int(HP)
self.MaxHP = int(MaxHP)
self.AC = int(AC)
self.ToHitAdjustment = int(ToHitAdjustment)
self.Surprise_Adjustment = int(Surprise_Adjustment)
self.Initiative_Adjustment = int(Initiative_Adjustment)
self.ExpReward = int(ExpReward)
self.Gold = int(Gold)
self.Damage = int(Damage)
def attack(self, Player_Character, goblin):
if (goblin.HP <= 0):
print("the goblin is inert")
else:
goblin_attack_roll = d20.die_roll() + goblin.ToHitAdjustment
if (goblin_attack_roll >= Player_Character.AC):
goblin_damage = d4.die_roll()
print("you take", goblin_damage, 'damage')
Player_Character.HP -= goblin_damage
if (Player_Character.HP <= 0):
print("oh dear you have died")
del Player_Character
quit()
else:
print("the goblin misses ")
MrHezy = Player_Character(20, 20, 10, 5, 0, 0, 0, 25, 0, d10.die_roll())
def spawn_goblin(goblin):
G1 = goblin(5, 10, 8, 2, 0, 0, 25, 5, d4.die_roll())
return G1
goblin1 = spawn_goblin(goblin)
def battle(goblin1):
# user input
player_initiative_adjustment = MrHezy.Initiative_Adjustment
monster_initiative_adjustment = goblin1.Initiative_Adjustment
#define while loop for the battle
while True:
if (goblin1.HP <= 0):
print('oh dear looks like we need a new goblin')
break
#use random.randint(a,b) to generate player and monster base initiative
player_base_initiative = d10.die_roll()
monster_base_initiative = d10.die_roll()
#subtract the adjustment to get player and monster initiative
player_initiative = player_base_initiative - player_initiative_adjustment
monster_initiative = monster_base_initiative - monster_initiative_adjustment
#compare the initiatives and display the results
if (player_initiative < monster_initiative):
attack_flee_heal = input("congratulations you go first. Would you like to attack,
flee, or heal?")
if attack_flee_heal == 'attack':
MrHezy.attack(goblin1, MrHezy)
elif attack_flee_heal == 'heal':
MrHezy.heal(MrHezy)
print("the goblin attacks")
goblin1.attack(MrHezy)
elif attack_flee_heal == 'flee':
MrHezy.flee()
else:
print("uhoh, the monsters go first, they attack!")
goblin1.attack(MrHezy, goblin1)
attack_flee_heal = input("Would you like to attack, flee, or heal? ")
if attack_flee_heal == 'attack':
MrHezy.attack(goblin1, MrHezy)
elif attack_flee_heal == 'heal':
MrHezy.heal(MrHezy)
print("the goblin attacks")
goblin1.attack(MrHezy, goblin1)
elif attack_flee_heal == 'flee':
MrHezy.flee()
#main game loop
while True:
spawn_goblin(goblin)
battle(goblin1)
print("spawn another goblin")
goblin1.HP = 0
goblin1.HP += d10.die_roll()
This code runs perfectly well, please enter it into your IDE.
The problem that I have is a logic error, when a goblin is killed instead of leveling up the character first to level 1 then level 2 then level 3 instead the character levels up to level 1 over and over and over.
I agree with Danny Varod, in that there are very many improvements that need to be made, and I definitely recommend following his advice.
However if you are simply looking to make what you have work you need to specify in your level up methods that you are referencing the global MrHezy variable.
eg:
def LevelUp(self):
global MrHezy
MrHezy = FighterLvl2(Player_Character)
The level up replaces a variable in the object, what you should do, if you want to use a class per level (not necessarily a good idea) is:
Create a Character class.
In Character class define an implementation field.
Initialize implementation field e.g. implementation = SomeSpeciesLevel1().
To "level-up": implementation = implementation.level_up()
This way you have a constant wrapper that doesn't change which wraps the level-changing implementation.
A better design would be to have one class with functionality based on level-dependant formulas.
class CharImpl:
#abstractmethod
def can_level_up() -> bool:
return NotImplemented
#abstractmethod
def next_level() -> CharImpl:
return NotImplemented
pass
class Character:
def __init__(initial_impl: CharImpl=None):
self.impl = initial_impl.copy() if initial_impl else HumanLevel1()
pass
def level_up():
if self.impl.can_level_up():
self.impl = self.impl.next_level()
pass
pass
class Human(CharImpl):
pass
class HumanLevel1(Human):
def __init__(src: Human):
# TODO: copy relevant fields from src
pass
def can_level_up() -> bool:
return True
def next_level() -> CharImpl:
return HumanLevel2(self)
pass
class HumanLevel2(Human):
def __init__(src: Human):
# TODO: copy relevant fields
pass
def can_level_up() -> bool:
return False
def next_level() -> CharImpl:
return self
pass
I found this code, and I'm having trouble understanding the lines 'user_hand = rps[int(user_input) - 1]' , 'com_hand = choice(rps)' , ' if rps_dict[user_hand]['strong'] == com_hand:' , 'print_result(**game_result)' , '
Why should I subtract 1 from user_input? Why put rps inside brackets next to choice? Why do you win 'if rps_dict[user_hand]['strong'] == com_hand ? Why if user_hand equal to com_hand? It doesnt make sense to me.. I know '**game_result' means it's a kwark, but I dont know why I need to declare it as a kwarg. I'm sorry if these questions seem stupid, but I'm frustrated.
from random import choice
rps = ('rock', 'paper', 'scissors')
rps_dict = {
'rock': {'strong': 'scissors', 'weak': 'paper'},
'paper': {'strong': 'rock', 'weak': 'scissors'},
'scissors': {'strong': 'paper', 'weak': 'rock'}
}
def print_result(user_score, com_score, win, lose, tie):
print('Result:', end=' ')
if user_score > com_score:
print('You win!')
elif user_score < com_score:
print('You lose...')
else:
print('Draw.')
print('--------------------')
# Print scores
print(f'Your score: {user_score}')
print(f'Computer score: {com_score}')
print('--------------------')
# Print statistics
print(f'Win: {win}')
print(f'Lose: {lose}')
print(f'Tie: {tie}')
def play(rounds):
game_result = {
'user_score': 0,
'com_score': 0,
'win': 0,
'lose': 0,
'tie': 0
}
while rounds > 0:
user_input = input(
'Enter your choice (1: Rock, 2: Paper, 3: Scissors, 0: Quit): ')
# Check whether the input is in the options
if user_input in ('1', '2', '3'):
rounds -= 1
user_hand = rps[int(user_input) - 1]
com_hand = choice(rps)
# user_hand is strong against com_hand
if rps_dict[user_hand]['strong'] == com_hand:
game_result['user_score'] += 1
game_result['win'] += 1
result = 'You win!'
# user_hand is weak against com_hand
elif rps_dict[user_hand]['weak'] == com_hand:
game_result['com_score'] += 1
game_result['lose'] += 1
result = 'You lose...'
# Tie
else:
game_result['tie'] += 1
result = 'Tie.'
print(
f'You -> {user_hand}. Computer -> {com_hand}. {result}')
elif user_input == '0':
break
else:
print('Invalid input!')
print()
print_result(**game_result)
if __name__ == "__main__":
print('Welcome to Rock-Paper-Scissors Game!')
try:
rounds = int(input('How many rounds you want to play? '))
play(rounds)
except ValueError:
print('Please input a valid number!')
This is an interesting question, and I'll do my best to discuss the lines that you said you have trouble with:
user_hand = rps[int(user_input) - 1]
The user_hand variable is used to store the choice the user inputs. user_input is the text the user directley entered. This will be saved as a string, so the code stransforms it into an integer with the int class. Next, it subtracts one from the user input (computers count from zero rather than 1). Then, it grabs the element from the list that has that index. For example, if I entered one, it would grab the list item at index 0 ("rock").
com_hand = choice(rps)
This line here is used to gather the computer's choice. As you can see from the first line, the choice function from the random module is imported directly. This allows you to use the function without specifying the module it came from. The choice function selects a random item from the specified list, which is the same rps list as before.
if rps_dict[user_hand]['strong'] == com_hand:
The if statement here gathers data from the rps_dict and compares it to the computer's hand. The rps_dict is a dictionary that contains data on which hand beats or loses to another. To translate the if statement into simpler english, it means if the hand the user's hand would beat (which can be found with rps_dict[user_hand]["strong"]), is the computer's hand, the user will win. In addition, to avoid confusion, the == operator check's for equality, and doesn't assign the variable to com_hand.
print_result(**game_result)
Here you said that you don't understand why the parameters are passed in this way. You don't really need to do it in this format, but the person who created the script decided to (possibly as it is simpler to read).
Thank you, and if you have any other questions, please comment and I'll do my best to answer them!
I have been studying Python 3 for a few months now and have just begun looking at Object Oriented programming. I asked a question on Stack Overflow about a text adventure game I was trying to write and it was suggested that it would be better to use OOP.
I did some searching as I wanted a very simple combat system that could be used in the game. I have the basic framework from the game but I would like some help with the combat system side.
Here is the code I have so far:
import random
import time as t
class Die:
def __init__(self, sides = 6):
self.sides = sides
def roll(self):
return random.randint(1, self.sides)
class Player:
def __init__(self):
self.hit_points = 10
def take_hit(self):
self.hit_points -= 2
class Enemy:
def __init__(self):
self.hit_points = 10
def take_hit(self):
self.hit_points -= 2
p = Player()
e = Enemy()
d = Die(6)
battle = 1
while battle != 0:
human = d.roll() + 6
print("Your hit score: ",human)
enemy = d.roll() + 6
print("Enemy hit score: ",enemy)
if human > enemy:
e.take_hit()
print("Your hit points remaining: ",p.hit_points)
print("Enemy points remaining: ", e.hit_points)
if e.hit_points == 0:
battle = 0
t.sleep(2)
elif human < enemy:
p.take_hit()
print("Your hit points remaining: ",p.hit_points)
print("Enemy points remaining: ", e.hit_points)
if p.hit_points == 0:
battle = 0
t.sleep(2)
The Die class is to simulate a six sided die, and player and enemy are used for game characters. After that the code is used to roll random number and the highest number win the round until either the player or the enemy reach zero points.
I am unsure how to use those last lines of code after the three classes and create a class from it also.
I need to be able to run a battle multiple times in the game and also store the player score with points deducted after each battle.
I really like and enjoy the use of objects and would like to become better, so any help with this is very much appreciated.
You can re-use a class and create more instances from one template. The Player and Enemy class have a identical functionality. You can create different instances from one class simply using the __init__ method with different arguments.
import random
import time as t
class Player:
def __init__(self, hit_points, sides):
self.hit_points = hit_points
self.sides = sides
def take_hit(self):
self.hit_points -= 2
def roll(self):
return random.randint(1, self.sides)
p = Player(hit_points=10, sides=6)
e = Player(hit_points=8, sides=6)
battle = 1
while battle != 0:
human = p.roll()
print("Your hit score: ",human)
enemy = e.roll()
print("Enemy hit score: ",enemy)
if human > enemy:
e.take_hit()
print("Your hit points remaining: ",p.hit_points)
print("Enemy points remaining: ", e.hit_points)
elif human < enemy:
p.take_hit()
print("Your hit points remaining: ",p.hit_points)
print("Enemy points remaining: ", e.hit_points)
t.sleep(2)
if e.hit_points == 0 or p.hit_points == 0:
battle = 0
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!