Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am having a problem with my attack loop, when it runs it gets to the checkAtk function then restarts the direction loop.
I don't have a clue what's wrong with this code (and need to fix it before next Saturday). I welcome any advice or hint you might have.
import random
import time
#We define the intro function to introduce the player to the world
def displayIntro():
# [...] content: calls to print() and sleep()
#Define a function to ask the player what direction they want to go
def chooseDir():
direction = ''
while direction != '1' and direction != '2' and direction != '3' and direction != '4':
# [...] content: calls to print() and sleep()
direction = input()
return direction
#Define a function that check if the direction = a random int that the computer generates
def checkDir(direction, health, mana, money):
# [...] content: calls to print() and sleep()
friendlyDir = random.randint(1, 4)
#If it does the player recieves 100 Rupees
if direction == friendlyDir:
# [...] content: calls to print() and sleep()
health = 100
mana = 100
money = money + 100
#if it dosent match we prepare for a fight
else:
# [...] content: calls to print() and sleep()
#define a function to ask the player to choose an attack
def chooseAtk(mana):
chooseAtk = ''
while chooseAtk != '1' and chooseAtk != '2' :
# [...] content: calls to print() and sleep()
#if players mana is > 0 they get a choice of a strength or a mana attack
if mana > 0:
# [...] content: calls to print() and sleep()
chooseAtk = int(input())
#if players mana < 0 the attack automatically goes to strength
else:
chooseAtk = 1
return chooseAtk
#define a function to check the attack against Player Attack Power vs Monster Defense
def checkAtk(chooseAtk, health, mana, money):
while chooseAtk == 1 and health > 0:
if playerAp > monsterDef:
# [...] content: calls to prin() and sleep()
money = money + 100
else:
# [...] content: calls to print() and sleep()
health = health - 10
#if player chooses a mana based attack its Player Magic Power vs Monster Defense
while chooseAtk == 2 and health > 0 and mana > 0:
if playerMp > monsterDef:
# [...] content: calls to print() and sleep()
money = money + 100
mana = mana - 10
else:
# [...] content: calls to print() and sleep()
health = health - 10
mana = mana - 10
#Set global variables
health = 100
mana = 100
money = 0
playerAp = random.randint(1,50)
playerMp = random.randint(1,50)
monsterDef = random.randint(1,50)
#Initiate the loop
displayIntro()
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
if health > 0:
print('------------------------------')
print('Health: ' + str(health))
print('Mana: ' + str(mana))
print('Rupees: ' + str(money))
print('------------------------------')
chosenDir = chooseDir()
checkDir(chosenDir, health, mana, money)
chooseAtk(mana)
checkAtk(chooseAtk, health, mana, money)
while health == 0:
print('Do you want to play again? (yes or no)')
playAgain = input()
In this function call:
checkAtk(chooseAtk, health, mana, money)
The chooseAtk argument isn't going to work as expected, it's passing the function instead of the return value.
Consider this:
>>> def a():
return 'a'
>>> def b(a):
print a
>>> b(a)
<function a at 0x01E5C130>
>>> b(a())
a
I think this will work...
Here's where you went wrong:
1: You completely replaced function names with variables..
2: The return-value of checkMana was never used, you passed a function to checkAtk, see this code difference:
chooseAtk(mana)
checkAtk(chooseAtk, health, mana, money)
Vs working:
chosenAttack = chooseAtk(mana)
checkAtk(chosenAttack, health, mana, money)
3: The following code will never break because 1 != '1'.
def chooseAtk(mana):
chooseAtkString = -1
while chooseAtkString != 1 and chooseAtkString != 2 :
print(' You must fight. ')
if mana > 0:
chooseAtkString = int(input())
else:
chooseAtkString = 1
return chooseAtkString
4: The reason for an endless loop is not my fault even tho it sounds like I created that issue and I hate when people do that. This is your mess, not mine. I'm cleaning it up.
Here's why the loop occurs:
while AttackChosen == 1 and health > 0:
if playerAp > monsterDef:
money = money + 100
else:
health = health - 10
For the first if block, you don't loose any HP.. It's as simple as that.
So i did:
while AttackChosen == 1 and health > 0:
if playerAp > monsterDef:
money = money + 100
health = health - 10
5: Why isn't mana/health updated? because...
Defining a function like this def checkAtk(AttackChosen, health, mana, money): will create local variables called health, mana, money instead of using the globals you've defined. Which means you will need to return these local variables back to the originating call which is:
checkAtk(chosenAttack, health, mana, money)
Try replacing that with:
health, mana, money = checkAtk(chosenAttack, health, mana, money)
and inside checkAtk do the following and the end:
return health, mana, money
Working code (For the love of the internets, next time post less code..)
import random
import time
#We define the intro function to introduce the player to the world
def displayIntro():
print('You awake in a land like no other.')
#Define a function to ask the player what direction they want to go
def chooseDir():
direction = ''
while direction != '1' and direction != '2' and direction != '3' and direction != '4':
print('In which direction do you continue North(1), South(2), East(3) or West(4)? ')
direction = input()
return direction
#Define a function that check if the direction = a random int that the computer generates
def checkDir(direction, health, mana, money):
print('You are walking briskly through the forest when you hear a creature cry out ')
friendlyDir = random.randint(1, 4)
#If it does the player recieves 100 Rupees
if direction == friendlyDir:
print('In the clearing there is a treasure chest and a natural spring')
health = 100
mana = 100
money = money + 100
#if it dosent match we prepare for a fight
else:
print('Dno what this does, but your code gave a ident syntax error because else: must be followed by something...')
#define a function to ask the player to choose an attack
def chooseAtk(mana):
chooseAtkString = -1
while chooseAtkString != 1 and chooseAtkString != 2 :
print(' You come face to face with a creature you cannot identify ')
if mana > 0:
print( ' Will you use your Strength(1) or your Wisdom(2) to vanquish this foe ')
chooseAtkString = int(input())
else:
chooseAtkString = 1
return chooseAtkString
#define a function to check the attack against Player Attack Power vs Monster Defense
def checkAtk(AttackChosen, health, mana, money):
while AttackChosen == 1 and health > 0:
if playerAp > monsterDef:
print(' The creature charges at you with his sword held high ')
money = money + 100
else:
print(' The creature charges at you with his sword held high ')
print(' You lose 10 health ')
health = health - 10
#if player chooses a mana based attack its Player Magic Power vs Monster Defense
while AttackChosen == 2 and health > 0 and mana > 0:
if playerMp > monsterDef:
print(' The creature charges at you with his sword held high ')
money = money + 100
mana = mana - 10
else:
print(' The creature charges at you with his sword held high ')
health = health - 10
mana = mana - 10
return health, mana, money
#Set global variables
health = 100
mana = 100
money = 0
playerAp = random.randint(1,50)
playerMp = random.randint(1,50)
monsterDef = random.randint(1,50)
displayIntro()
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
if health > 0:
print('------------------------------')
print('Health: ' + str(health))
print('Mana: ' + str(mana))
print('Rupees: ' + str(money))
print('------------------------------')
chosenDir = chooseDir()
checkDir(chosenDir, health, mana, money)
chosenAttack = chooseAtk(mana)
health, mana, money = checkAtk(chosenAttack, health, mana, money)
while health == 0:
print('Do you want to play again? (yes or no)')
playAgain = input()
Related
I'm writing a simple Python program which is a text-based fighting simulator, and I'm using classes to allow myself to create heroes and enemies. I've created an attack function within my hero class, but it doesn't seem to be subtracting the enemy health from the hero strength like I want it to.
Here's the code:
import random
class Enemy:
eName = "Name"
eHealth = 0
eStrength = 0
def __init__ (self, eName, eHealth, eStrength):
self.eName = eName
self.eHealth = eHealth
self.eStrength = eStrength
def attack (self):
print("The enemy attacked you and dealt", self.eStrength, "damage!")
Hero.health -= self.eStrength
def __repr__(self):
if self.eName == "Zombie":
return "Zombie"
elif self.eName == "Skeleton":
return "Skeleton"
else:
return "Spider"
class Hero:
name = "Name"
health = 0
strength = 0
def __init__ (self, name, health, strength):
self.name = name
self.health = health
self.strength = strength
def attack(self, enemy):
print("You attacked", enemy, "for", self.strength, "damage!\n")
Enemy.eHealth -= self.strength
print(enemy, "now has", enemy.eHealth, "health points left!\n")
print("Welcome to my fighting simulator!")
hName = input("Please input your character's name:\n")
hHealth = int(input("Please enter your hero's amount of health points (10-25):\n"))
hStrength = int(input("Please enter your hero's amount of strength points (2-4): \n"))
character = Hero(hName, hHealth, hStrength)
zombie = Enemy("Zombie", 25, 3)
skeleton = Enemy("Skeleton", 15, 4)
spider = Enemy("Spider", 20, 2)
randEnemy = random.randint(1, 3)
if randEnemy == 1:
print("\nYour enemy will be a zombie!\n")
chosenEnemy = zombie
elif randEnemy == 2:
print("\nYour enemy will be a skeleton!\n")
chosenEnemy = skeleton
else:
print("\nYour enemy will be a spider!\n")
chosenEnemy = spider
while True:
if character.health == 0:
print("You died!")
elif chosenEnemy.eHealth == 0:
print("You won!")
action = input("What would you like to do? (h = heal, a = attack): ")
if (action == 'a') or (action == 'A'):
character.attack(chosenEnemy)
The main things that need to be seen are the variables in the Enemy class, the attack function in the Hero class, and the input variables for the heroes stats.
You just had a typo. In the attack() method, you wrote
Enemy.eHealth -= self.strength
instead of
enemy.eHealth -= self.strength
And since you are unable to subtract health from the Enemy class, the described problem that you mentioned occurs.
I have this bit of code
health = 12
manager_health = 10
def manager_boss_fight_used_for_backup():
sleep(1)
print("manager health is ",manager_health)
print("your health is ",health)
sleep(1)
print("the boss gets first attack")
manager_boss_damage = random.randint(1,8)
print(manager_boss_damage)
print(health)
health = health - manager_boss_damage
sleep(1)
print("the boss did",manager_boss_damage,"damage")
sleep(1)
print("your health is now",health)
if health <= 0:
sleep(1)
print("you have died")
sleep(1)
print("better luck next time")
exit()
sleep(1)
print("your turn to attack")
sleep(1)
heal_or_attack = input("Do you wish to heal or attack?(1/2)")
if heal_or_attack == "1":
healing = random.randint(1,7)
print("you have healed by",healing)
health = health + healing
manager_boss_fight_used_for_backup()
if heal_or_attack == "2":
print("you attack the boss")
sleep(1)
attack_damage = random.randint(1,6)
print("You did",attack_damage,"damage")
manager_health = manager_health - attack_damage
if manager_health <= 0:
sleep(1)
print("You have killed the boss")
sleep(1)
if manager_health > 0:
manager_boss_fight_used_for_backup()
and in the parts of code where for example health = health - manager_boss_damage it will error out. I have fiddled with global variables and all that but I cant get it to work so I came here. Any answers appreciated!
As probably everyone will tell you, using global variables is pretty bad. Why don't you use OOP instead? You can create a class Manager: and a class Player: with health as property and damage and take_damage as a method of the class, for example:
class Manager:
def __init__(self):
self.health = 10
def attack(self):
damage = ramdom.randint(1,8)
return damage
def take_damage(self, damage):
self.health -= damage
if (self.health <= 0):
self.health = 0
return self.health
then the Player class would be more or less the same:
class Player:
def __init__(self):
self.health = 12
def attack(self):
damage = ramdom.randint(1,8)
return damage
def take_damage(self, damage):
self.health -= damage
if (self.health <= 0):
self.health = 0
return self.health
def heal(self, amount):
self.health += amount
return self.health
Ideally of course, you can create one class called "Actor" or "Enemy" and derive those from there, but let's stick with this for now:
# Instantiate the classes like this:
manager = Manager()
player = Player()
# and then just invoke the methods from the classes:
sleep(1)
print("manager health is ",manager.health)
print("your health is ",player.health)
sleep(1)
print("the boss gets first attack")
damage = manager.Attack()
print("You were hit by {} points".format(damage))
player.take_damage(damage)
print("Your Health is {}".format(player.health))
Etc.
Whenever you make an assignment to health inside the manager_fight_used_for_backup() function, Python attempts to assign a new variable called health by default.
The fastest fix is to use the global keyword at the beginning of the function body, to make it clear that you're referring to the health variable outside of the function:
global health
This will tell Python that you're referring to the health variable outside of the function. However, the best solution is to refactor this code so that functions don't modify a shared global state.
So, I have recently got into coding and I am currently developing a small turn-based RPG, but I have encountered some real issue with the battle system. I am still learning and I never thought about asking questions here. Anyway, after getting many things done correctly, I have encountered this issue where using the defend command rises the player hp for some reason. Here is the code:
import random
import sys
import os
class Entity():
def __init__(self, hp, atk, dif):
self.hp = hp
self.atk = atk
self.dif = dif
class Battle():
def Attack(self, attacker, defender):
damage = attacker.atk - defender.dif
defender.hp -= damage
def Combat(self, player, enemy):
turns = []
while True:
while len(turns) < 5:
turn = random.randint(1, 2)
if turn == 1:
turns.append("player")
else:
turns.append("enemy")
for current_turn in turns:
print(player.hp, enemy.hp)
if current_turn == "player":
print(f"TURNS: \n{current_turn}\n{turns[turns.index(current_turn)+ 1:]}")
choice = input("1. Attack\n2. Defend\n")
if choice == "1":
self.Attack(player, enemy)
player.dif = 20
elif choice == "2":
player.dif *= 2
else:
print("Lost your chance!")
elif current_turn == "enemy":
print("Enemy turn!")
print(f"Next turns are: {turns}")
enemy_choice = random.randint(1, 2)
if enemy_choice == 2:
print("He attacks you!")
self.Attack(enemy, player)
enemy.dif = 0
else:
print("He defends himself.")
enemy.dif = 10
os.system("clear")
turns.pop(0)
if player.hp <= 0:
print("You died!")
sys.exit(0)
elif enemy.hp <= 0:
print("YOU WON!")
sys.exit(0)
break
charachter = Entity(100, 15, 15)
boss = Entity(300, 40, 0)
testbattle = Battle()
testbattle.Combat(charachter, boss)
In your Battle.Attack method:
def Attack(self, attacker, defender):
damage = attacker.atk - defender.dif
defender.hp -= damage
If attacker.atk - defender.dif is a negative number, then you'll be subtracting a negative number from defender.hp, increasing it.
If I'm the player, and my defense starts out as 15, and then I defend, my defense will become 30 because of player.dif *= 2. If I defend again the next turn, my defense will be 60, which is greater than the boss' attack of 40. So, if the boss then attacks me in Battle.Attack, we would get damage = 40 - 60, which is damage = -20, effectively healing the player by twenty points.
The entity will be healed if the attackers attack value is less than the defender's defence value. Perhaps instead of subtracting the 2 values you could use a defence divisor/ multiplier
I'm trying to create a text-based adventure game in python, in which there will be fights with monsters and shops in which you can increase your health and damage. I realize that using global variables in functions isn't advised, but I haven't been able to find another way of implementing what I want to do. The fights and shops appear at multiple points in the game, so I thought defining them would be the best way to use them repeatedly. Here is a small section referring to an item available in a shop:
import random
own_health = 15
gold = 10
helmet = False
def helmet():
global own_health
global gold
global helmet
health_boost = random.randint(2,5)
cost = random.randint(7,10)
print("There is a helmet that costs", cost, "and will increase your health by", health_boost)
buy = input("Would you like to buy and equip the helmet? (y/n): ")
if buy == "y":
if gold - cost > -1 and helmet == False:
gold -= cost
own_health += health_boost
helmet = True
elif gold - cost < 0:
print("You don't have enough money to buy this helmet.")
elif helmet == True:
print("You are already wearing a helmet.")
elif buy == "n":
print("You didn't buy the helmet.")
else:
print("Invalid input.")
helmet()
print(own_health)
print(gold)
print(helmet)
The results of this code are that own_health, gold and helmet are set back to the original values that they had before the function helmet() were carried out. Is there a way to fix this so that the global variables are set permanently once the function has been carried out? If not, I am eager to hear any different ways that I could code the program.
if gold - cost > -1 and helmet == False:
This condition will never succeed, because helmet is never False inside the function. The helmet you create just below own_health and gold gets overwritten when you define a function with the same name. Try giving your function a different name, for example get_helmet. Then your globals should update as desired:
c:\Users\Kevin\Desktop>test.py
There is a helmet that costs 7 and will increase your health by 2
Would you like to buy and equip the helmet? (y/n): y
17
3
True
Global variables should indeed be avoided. Passing them as arguments would be preferred.
You have multiple instances of the same variables. Your global variables should not be declared within the function, but rather somewhere externally. If the globals are used outside of the file in which they are declared, import that file and append the file name to the beginning of the global variable.
import fileName
fileName.gold...
I would create a class:
import random
class myClass:
def __init__(self, own_health, gold, helmet):
self.own_health = own_health
self.gold = gold
self.helmet = helmet
def buyHelmet(self):
health_boost = random.randint(2,5)
cost = random.randint(7,10)
print("There is a helmet that costs", cost, "and will increase your health by", health_boost)
buy = input("Would you like to buy and equip the helmet? (y/n): ")
if buy == "y":
if self.gold - cost > -1 and self.helmet == False:
self.gold -= cost
self.own_health += health_boost
self.helmet = True
elif self.gold - cost < 0:
print("You don't have enough money to buy this helmet.")
elif self.helmet == True:
print("You are already wearing a helmet.")
elif buy == "n":
print("You didn't buy the helmet.")
else:
print("Invalid input.")
kbball = myClass(15, 10, False)
print(kbball.own_health)
print(kbball.gold)
print(kbball.helmet)
kbball.buyHelmet()
print(kbball.own_health)
print(kbball.gold)
print(kbball.helmet)
#output
15
10
False
There is a helmet that costs 10 and will increase your health by 2
17
0
True
One way you can solve this problem is by using OOP.
class Game():
def __init__(self):
self.own_health = 15
self.gold = 10
self.helmet = 5
def helmet(self):
health_boost = random.randint(2,5)
cost = random.randint(7,10)
print("There is a helmet that costs", cost, "and will increase your health by", health_boost)
buy = input("Would you like to buy and equip the helmet? (y/n): ")
if buy == "y":
if self.gold - cost > -1 and self.helmet == False:
self.gold -= cost
self.own_health += health_boost
self.helmet = True
elif self.gold - cost < 0:
print("You don't have enough money to buy this helmet.")
elif self.helmet == True:
print("You are already wearing a helmet.")
elif buy == "n":
print("You didn't buy the helmet.")
else:
print("Invalid input.")
And then define some functions that returns you the values of the global variables.
def get_own_health(self):
return self.own_health
Now you can check the variable values as follows:
game = Game()
game.helmet()
print(game.get_own_health())
this is my first attempt at python coding, or any coding for that matter.
I have made this simple little game, and it seems to be running fine but I want to add another option to it.
the code generate a random character with HP, attack power, XP and level, then generates a dragon with HP and attack power, the game then decides each time who strikes, and if the player wins he gets to get some Xp and level up, if the dragon wins the player is dead and it asks you to play again.
what I want to add is what if I'm in the middle of a fight, and don't want to continue, I want ask the user if they want to continue fighting, if not the game ends.
I've tried to do that but I failed.
Also , if there is anything I can do to enhance my code.
thanks in advance.
import random
def charGen():
char = [random.randint(1,10),random.randint(1,3), 0, 0]#[hp, power,xp,level]
return char
def drgnGen():
drgn = [random.randint(1,5),random.randint(1,5)]
return drgn
def playAgain():
print('do you want to play again?(y)es or no')
return input().lower().startswith('y')
def xpValues(levels):
for i in range(levels):
n=0
n=((i+2)**2)
xpLevels.append(n)
def xpIncrement(XP,xpLevels,char):
#returns the level of the character( the bracket in which the character XP level lies within)
#level = char[3]
for i in range(len(xpLevels)):
if XP>= xpLevels[i] and XP<xpLevels[i+1]:
#level = i+1
return i
def levelUp(char,level):
if level+1>char[3]:
char[0] += 1
char[3] += 1
print ('you are now at level %s!, your health now is %s points'%((level+1),char[0]))
def isNotDead(char):
if char[0]>0:
return True
else:
return False
while True:
XP = 5 #the default XP gain after battle win
char = charGen() #generate the character
xpLevels=[]
xpValues(15)
print (xpLevels)
print ('______________________________________')
print ('Welcome to the Battle of the dragons!')
print ("you are a fierce Warrior with %s health points and A power of %s points" %(char[0],char[1]))
print ('------------------------------------------------------------------------')
while isNotDead(char):
print(' ')
print ('While adventuring you have met a scary looking dragon')
print('Without hesitation you jump to fight it off!')
print('=============================================')
print(' ')
drgn = drgnGen() #generate a dragon
while True:
roll = random.randint(0,1)
if roll == 0:
print("the dragon hits you for %s points" %drgn[1])
char[0] = char[0] - drgn[1]
if isNotDead(char) :
print("you have %s health left!" %char[0])
input('Press Enter to continue')
print(' ')
else:
print("you're dead!Game Over")
print(' ')
break
else:
print("you hit the dragon for %s points"%char[1])
drgn[0] = drgn[0] - char[1]
if drgn[0] >0:
print("the dragon have %s health left!" %drgn[0])
input('Press Enter to continue')
print(' ')
else:
char[2]+= XP
print("Horaay!you have killed the dragon!and your experience points are now %s"%char[2])
levelUp(char,(xpIncrement(char[2],xpLevels,char)))
input('Press Enter to continue')
break
if not playAgain():
break
A quick fix to get what you want is to have a couple of flags marking whether the user is fighting or not. Also you can delay printing output until the end of the innermost loop, to avoid having to repeat too much printing:
new_dragon = True
while new_dragon:
print(' ')
print ('While adventuring you have met a scary looking dragon')
print('Without hesitation you jump to fight it off!')
print('=============================================')
print(' ')
drgn = drgnGen() #generate a dragon
fighting = True
while fighting:
message = []
roll = random.randint(0,1)
if roll == 0:
message.append("the dragon hits you for %s points" %drgn[1])
char[0] = char[0] - drgn[1]
if isNotDead(char) :
message.append("you have %s health left!" %char[0])
else:
message.append("you're dead!Game Over")
fighting = False
new_dragon = False
else:
message.append("you hit the dragon for %s points"%char[1])
drgn[0] = drgn[0] - char[1]
if drgn[0] >0:
message.append("the dragon have %s health left!" %drgn[0])
else:
char[2]+= XP
message.append("Horaay!you have killed the dragon!and your experience points are now %s"%char[2])
levelUp(char,(xpIncrement(char[2],xpLevels,char)))
continue_flag = False
for m in message:
print (m)
print ('')
if fighting:
r = input("Press enter to continue or enter q to quit")
if r is 'q':
fighting = False
To improve the code more generally:
make a Character class and classes for Player and Dragon that inherit shared properties from the Character class
the check for whether to level up can be greatly simplified by just comparing whether new_xp > xpLevels[previous_xp]
the programme will soon get over-complicated if you continue to expand it just using nested while loops. What you want is a single while loop, functions (or a class) for each stage/status of the game, variables that record the game's current status (e.g. any dragons present), and a condition that decides what to do next.
give things clear descriptive names, using classes, e.g. player.power instead of char[2]
E.g. the following...
import random
class Character:
def __init__(self, max_hp, max_power):
self.hp = random.randint(1, max_hp)
self.power = random.randint(1, max_power)
def is_dead(self):
return self.hp <= 0
def hit_by(self, enemy):
self.hp -= enemy.power
class Player(Character):
def __init__(self):
Character.__init__(self, max_hp=10, max_power=3)
self.xp = 0
self.level = 0
self.xp_thresholds = [(i + 2) ** 2 for i in range(15)]
def battle_win(self):
self.xp += battle_win_xp
if self.level < len(self.xp_thresholds) and self.xp > self.xp_thresholds[self.level + 1]:
self.level_up()
def level_up(self):
self.hp += 1
self.level += 1
print('you are now at level %s!, your health now is %s points' % (self.level + 1, self.hp))
def begin():
game.player = Player()
print('______________________________________')
print('Welcome to the Battle of the dragons!')
print("you are a fierce Warrior with %s health points and A power of %s points" %(game.player.hp, game.player.power))
print('------------------------------------------------------------------------')
def new_dragon():
print('While adventuring you have met a scary looking dragon')
print('Without hesitation you jump to fight it off!')
print('=============================================')
game.dragon = Character(5, 5)
def fight():
player, dragon = game.player, game.dragon
if random.randint(0, 1):
player.hit_by(dragon)
print("the dragon hits you for %s points" % dragon.power)
if player.is_dead():
print("you're dead! Game over")
return
else:
print("you have %s health left!" % player.hp)
else:
dragon.hit_by(player)
print("you hit the dragon for %s points" % player.power)
if dragon.is_dead():
print("Horaay!you have killed the dragon!and your experience points are now %s"%player.xp)
player.battle_win()
game.dragon = None
return
else:
print ("the dragon have %s health left!" %dragon.hp)
print "Press enter to continue (q to quit)"
if input() is 'q':
game.finished = True
def play_again():
print 'do you want to play again?(y)es or no'
if input().lower().startswith('y'):
game.__init__()
else:
game.finished = True
battle_win_xp = 5 #the default XP gain after battle win
class Game:
def __init__(self):
self.dragon = None
self.player = None
self.finished = False
game = Game()
while not game.finished:
if not game.player:
begin()
elif game.player.is_dead():
play_again()
elif not game.dragon:
new_dragon()
else:
fight()