Error: List index out of range in game code - python

I'm having trouble with a list index error, the code may not be the sharpest. But I only know so much about coding in python, but I know enough to code a game.
The code that the function are used in:
#Checks if the move counter is more than 3, if it is, the player gets to decide what he/she wants to do
if Moves != 0:
Do = input('What do you do? Help to see all commands ')
#Tests for if the player wants a magic spell
if Do == 'Magic':
if Moves == 3:
ListToDo = MagicDmg(ListToDo, Moves)
if ListToDo[0] == 'Ice' or 'Fire' or 'Bolt':
Mana = CheckMagicCost1(ListToDo, Mana, Moves)
else:
Moves = Moves - 1
elif Moves == 2:
ListToDo = MagicDmg(ListToDo, Moves)
Mana = CheckMagicCost2(ListToDo, Mana, Moves)
Moves = Moves - 1
else:
ListToDo = MagicDmg(ListToDo, Moves)
Mana = CheckMagicCost3(ListToDo, Mana, Moves)
Moves = Moves - 1
#This function does not handle damage
def MagicDmg(ListToDo, Moves):
print('Which magic? Ice, Fire or Bolt')
MagicDo = input()
if MagicDo != 'Ice' or 'Fire' or 'Bolt':
if MagicDo == 'Ice':
ListToDo.append('Ice')
elif MagicDo == 'Fire':
ListToDo.append('Fire')
elif MagicDo == 'Bolt':
ListToDo.append('Bolt')
else:
LIstToDo.remove(MagicDo)
print('That is not a valid spell')
Moves = Moves + 1
return(ListToDo)
#Subtracts the mana cost of spells from mana
def CheckMagicCost1(ListToDo, Mana, Moves):
if ListToDo[0] and Mana >= 10 == 'Ice':
Mana = Mana - 10
elif ListToDo[0] and Mana >= 15 == 'Fire':
Mana = Mana - 15
elif ListToDo[0] and Mana >= 25 == 'Bolt':
Mana = Mana - 25
else:
print('You do not have enough Mana')
Moves = Moves + 1
return(Mana)
def CheckMagicCost2(ListToDo, Mana, Moves):
if ListToDo[1] and Mana >= 10 == 'Ice':
Mana = Mana - 10
elif ListToDo[1] and Mana >= 15 == 'Fire':
Mana = Mana - 15
elif ListToDo[1] and Mana >= 25 == 'Bolt':
Mana = Mana - 25
else:
print('You do not have enough Mana')
Moves = Moves + 1
return(Mana)
def CheckMagicCost3(ListToDo, Mana, Moves):
if ListToDo[2] and Mana > 9 == 'Ice':
Mana = Mana - 10
elif ListToDo[2] and Mana > 14 == 'Fire':
Mana = Mana - 15
elif ListToDo[2] and Mana > 24 == 'Bolt':
Mana = Mana - 25
else:
print('You do not have enough Mana')
Moves = Moves + 1
return(Mana)
The result:
A Azure Drake appeared! With 500 HP!
HP = 250 Mana = 250
Moves left: 3
Boss's HP: 500
What do you do? Help to see all commands Magic
Which magic? Ice, Fire or Bolt
i (False spell)
Traceback (most recent call last):
File "D:\Python\Battle Test V2.py", line 186, in <module>
if ListToDo[0] != 'Ice' or 'Fire' or 'Bolt':
IndexError: list index out of range

I can't immediately tell if this is your only problem, but this line will definitely not work.
if MagicDo != 'Ice' or 'Fire' or 'Bolt':
What that really is checking is the following:
if (MagicDo != 'Ice') or ('Fire' != None) or ('Bolt' != None):
A possible fix for this is changing to this:
if MagicDo in(['Ice','Fire','Bolt']):
This will check if MagicDo is one of the three spells you want. Again, I'm not sure if this is your only problem, but it's definitely a problem.
EDIT: I'm also noticing a problem in your CheckMagicCost functions. None of your conditionals will do what you want them to do. for example, the line
if ListToDo[0] and Mana >= 10 == 'Ice':
is really checking the following
if (ListToDo[0] != None) and ((Mana >= 10) == 'Ice'):
I'm guessing what you want is something more like the following:
if ListToDo[0] == 'Ice' and Mana >= 10:
This change should be propagated out to the rest of your conditionals in the CheckMagicCost1, CheckMagicCost2, and CheckMagicCost3 functions.

Without the error code there's not much to go on, but my gut feeling is you are going to run into trouble with these kinds of statements in your functions:
if ListToDo[1]
Might be better to wrap in a try block and catch the IndexError? Just a thought
try:
#code
except IndexError:
#contingency plan

Related

Doesn't run IF statement even though condition is true, but loops other IF

import random
player_health = 100
boss_health = 80
guard1_health = 10
guard1_status = "alive"
guard2_health = 15
gladiator_health = 20
weapon = 0
level = 0
turn = 0
def choose_weapon():
global weapon
global level
weapon = int(input("Choose your weapon:\n 1: Sword \n 2: Daggers \n 3: Bow \n Type here to choose:"
"\n--------------------------"))
if weapon == 1:
weapon = str("Sword")
print("You have chosen", weapon)
elif weapon == 2:
weapon = str("Daggers")
print("You have chosen", weapon)
else:
weapon = str("Bow")
print("You have chosen", weapon)
level += 1
choose_weapon()
def level_1_enemy():
global guard1_status
global guard1_health
global level
global turn
global weapon
print("Player turn")
if guard1_status == "alive" and guard1_health > 0 and turn == 1:
print("test")
if weapon == 1:
guard1_health -= 8
print("Guard health:", guard1_health)
turn -= 1
elif weapon == 2:
guard1_health -= 5
print("Guard health:", guard1_health)
turn -= 1
elif weapon == 3:
bow_crit = random.randint(1, 10)
if bow_crit == 1:
guard1_health -= 20
print("Guard health:", guard1_health)
else:
guard1_health -= 5
print("Guard health:", guard1_health)
if guard1_health <= 0:
print("You defeated the Guard, next level!")
guard1_status = "dead"
level += 1
return
def level_1_player():
global player_health
global weapon
global level
global turn
if player_health > 0 and turn == 0:
if weapon == 2:
dodge = random.randint(1, 3)
if dodge == 1:
print("You dodged the attack!")
return
else:
player_health -= 5
print("\n\nThe enemy hit you! (-5 hp)")
print("Enemy health: ", guard1_health)
print("Your health: ", player_health)
return
else:
player_health -= 5
print("\n\nThe enemy hit you! (-5 hp)")
print("Enemy health: ", guard1_health)
print("Your health: ", player_health)
return
print("You have died, Game Over.")
return
while level == 1:
if turn == 0:
level_1_player()
turn += 1
elif turn == 1:
level_1_enemy()
turn -= 1
I want to have the game loop through player and enemy turns until either the player is dead or the enemy. It reaches the first IF in level_1_enemy and prints "test", but does not continue to the next if statement even though the condition "weapon == 1" is true.
The last while loop is meant to repeat the level_1_enemy and level_1_player functions. It does do both but will also not stop looping once the guard or player is dead.

Problem developing a turn-based battle system

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

Camel Game, trouble with native distance values

I'm trying to write the Camel game using functions instead of so many nested if statements. I think I've done something wrong though, I've had to tinker with the native distance portion a lot as I kept getting into parts where they only got further away not closer. But now after trying to change the randomint values I can never escape them. Any suggestions for improvement are much appreciated!
Here is my code:
import random
def quitGame():
print("I am guitting now.")
return True
def status(milesTraveled, thirst, camelTiredness, distanceNativesTraveled, drinks):
print(
"""
You have traveled %d miles
Your Camel Status is %d (lower is better)
You have %d drinks left in your canteen
Your thirst is %d (lower is better)
The Natives are %d miles behind you
"""%(milesTraveled,camelTiredness,drinks,thirst,distanceNativesTraveled))
def rest():
print("The camel is happy")
distanceN = random.randint(7,14)
return(distanceN)
def fullSpeed():
distanceT = random.randint(10,20)
print("You travel %d miles"%distanceT)
camelT = random.randint(1,3)
distanceN = random.randint(7,14)
return(distanceT,camelT,distanceN)
def moderateSpeed():
distanceB = random.randint(5,12)
print("You travel %d miles"%distanceB)
nativesB = random.randint(7,14)
return(distanceB,nativesB)
def thirsty(drinksLeft):
drinksL = drinksLeft - 1
return(drinksL)
def main():
choice = ""
done = False # loop variable
#variables for game
milesTraveled = 0
thirst = 0
camelTiredness = 0
distanceNativesTraveled = -20
drinks = 5
print(
"""
Welcome to the Camel Game!
You have stolen a camel to make your way across the great Mobi desert.
The natives want their camel back and are chasing you down. Survive your
desert trek and out run the native.
"""
)
while not done:
findOasis = random.randint(1,20)
print(
"""
Here are your choices:
A - Drink from you canteen.
B - Ahead moderate speed.
C - Ahead full speed.
D - Stop and rest for night.
E - Status check.
Q - Quit the Game
"""
)
choice = input(" Your choice?\n")
if choice.upper() == "Q":
done = quitGame()
elif findOasis is 1 :
print("Wow! You've found an Oasis. Your thirst is quenched, canteen topped off, \
and your camel is now well rested and happy.")
drinks = 5
thirst = 0
camelTiredness = 0
elif choice.upper() == "A":
if drinks > 0:
drinks = thirsty(drinks)
thirst = 0
else:
print("Error: Uh oh! No water left.")
elif choice.upper() == "B":
milesB,nativesB = moderateSpeed()
milesTraveled += milesB
camelTiredness += 1
thirst += 1
distanceNativesTraveled += nativesB
elif choice.upper() == "C":
milesT,camelTired,nativesT= fullSpeed()
milesTraveled += milesT
camelTiredness += camelTired
distanceNativesTraveled += nativesT
thirst += 1
elif choice.upper() == "D":
distanceT = rest()
camelTiredness = 0
distanceNativesTraveled += distanceT
elif choice.upper() == "E":
statusCheck = status(milesTraveled, thirst, camelTiredness, distanceNativesTraveled, drinks)
else:
print("That was not a correct choice - Enter (A through E or Q)")
if thirst > 4 and thirst <= 6:
print("You are thirsty")
elif thirst > 6:
print("GAME OVER \nYou died of thirst!")
done = True
elif camelTiredness > 5 and camelTiredness <= 8:
print("Your camel is getting tired")
elif camelTiredness > 8:
print("GAME OVER \nYour camel is dead.")
done = True
elif distanceNativesTraveled >= 0:
print("GAME OVER \nThe natives have captured you!")
done = True
elif distanceNativesTraveled > -15:
print("The natives are getting close!")
elif milesTraveled >= 200:
print("YOU WIN \nCongrats, you made it across the desert!")
done = True
# call main
main()
The game ends when distanceNativesTraveled >= 0 and yet there's no code at all to decrease distanceNativesTraveled. So with every turn distanceNativesTraveled keeping increasing, the game is bound to end quickly.
What you really want here is to check if distanceNativesTraveled has surpassed milesTraveled, so change:
elif distanceNativesTraveled >= 0:
to:
elif distanceNativesTraveled >= milesTraveled:
And for the check to see if natives are getting close, change:
elif distanceNativesTraveled > -15:
to:
elif distanceNativesTraveled - milesTraveled > -15:
And to properly show the how many miles the natives are behind you, you should show the difference between the miles you and the natives traveled, so change:
"""%(milesTraveled,camelTiredness,drinks,thirst,distanceNativesTraveled))
to:
"""%(milesTraveled,camelTiredness,drinks,thirst,milesTraveled - distanceNativesTraveled))

Why does my program exit unexpectedly when I call input?

I'm trying to get this RPG program to work, but I can't figure it out. I run it and well, you will see when you run the program. For some reason when I run this it stops at 1,2,3,4 after every move I make. Am I not returning anything? What am I doing wrong here, and how can I improve my organization and code in the future?
import math
import random
class character:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
class enemy:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
charspells = ['Fireball']
Loop = True
def fireball(character, enemy):
enemy.hp -= character.int
print('You did, ',character.int ,'to the enemy')
print('Enemy.hp', enemy.hp)
return enemy.hp
items = []
mainc = character(100, 100, 10, 0, 10)
tai_lopez = enemy(30, 30, 5, 0, 10)
def character_battle(character, enemy):
choice = input('What would you like to do?\n 1. Attack \n 2. Spells \n 3. Items \n 4. Run')
if choice == input('1'):
print('You attack the enemy!')
enemy.hp -= character.att
print('You dealt', character.att, 'to the enemy!')
print('Enemy hp =', enemy.hp)
if choice == input('2'):
spellchoice = input('Which spell do you wish to call?')
print('1.', charspells[0],'\n' '2.', charspells[1], '\n' 'q', 'exit')
if spellchoice == ('1'):
print('You used fireball!')
fireball(character, enemy)
elif spellchoice == ('2'):
if charspells[1] != 'Lightning bolt':
print('It doesnt exist, sorry')
# ill add more spell fucntions later
if spellchoice == ('3'):
print('You went back to the menu')
if choice == input('3'):
if items == []:
print('You have no items')
if items == ['potions']:
print ('response')
#placeholder ill add the fucntion later
elif choice == input('4'):
Loop = False
def enemy_battle(enemy, character):
a = random.randint(0,50)
if a <= 35:
print('The enemy attacks you!')
character.hp -= enemy.att
print('Your hp =', character.hp)
elif a <= 50:
print('The enemy uses mind attacks bruh')
character.hp -= enemy.int
print('Your hp =', character.hp)
def battle_loop(character, enemy):
Loop1 = True
while Loop1 == True:
while enemy.hp > 0 and character.hp > 0:
character_battle(character, enemy)
enemy_battle(character, enemy)
if enemy.hp <= 0:
print('You Won')
Loop1 = False
if character.hp <= 0:
print('You lost')
exit()
battle_loop(mainc, tai_lopez)
The problem is you are using input() in if statement. Whenever interpreter tries to check if condition is true or not it executes the input() which demands an input even when you didn't expect it. In one of the methods your input was in wrong order so I fixed that too. So correct code should be :-
import math
import random
class character:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
class enemy:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
charspells = ['Fireball']
Loop = True
def fireball(character, enemy):
enemy.hp -= character.int
print('You did, ',character.int ,'to the enemy')
print('Enemy.hp', enemy.hp)
return enemy.hp
items = []
mainc = character(100, 100, 10, 0, 10)
tai_lopez = enemy(30, 30, 5, 0, 10)
def character_battle(character, enemy):
choice = input('What would you like to do?\n 1. Attack \n 2. Spells \n 3. Items \n 4. Run \n')
if choice == '1':
print('You attack the enemy!')
enemy.hp -= character.att
print('You dealt', character.att, 'to the enemy!')
print('Enemy hp =', enemy.hp)
elif choice == '2':
spellchoice = input('Which spell do you wish to call?')
print('1.', charspells[0],'\n' '2.', charspells[1], '\n' 'q', 'exit')
if spellchoice == ('1'):
print('You used fireball!')
fireball(character, enemy)
elif spellchoice == ('2'):
if charspells[1] != 'Lightning bolt':
print('It doesnt exist, sorry')
# ill add more spell fucntions later
if spellchoice == ('3'):
print('You went back to the menu')
elif choice == '3':
if items == []:
print('You have no items')
if items == ['potions']:
print ('response')
#placeholder ill add the fucntion later
elif choice == '4':
Loop = False
def enemy_battle(character, enemy):
a = random.randint(0,50)
if a <= 35:
print('The enemy attacks you!')
character.hp -= enemy.att
print('Your hp =', character.hp)
elif a <= 50:
print('The enemy uses mind attacks bruh')
character.hp -= enemy.int
print('Your hp =', character.hp)
def battle_loop(character, enemy):
Loop1 = True
while Loop1 == True:
while enemy.hp > 0 and character.hp > 0:
character_battle(character, enemy)
enemy_battle(character, enemy)
if enemy.hp <= 0:
print('You Won')
Loop1 = False
if character.hp <= 0:
print('You lost')
exit()
battle_loop(mainc, tai_lopez)
You didn't need two classes here clearly. But I suppose you might be thinking of adding some more features in future I guess. You can study more about oop and inheritance and figure out a smarter solution in general. I think you should focus on basics. Also try not to name the temporary variable same as that of class. It is a very hastly written code imo. But I fixed it's working.
Looks interesting, send me a copy after you finish will ya?
so basically you use too much input()
you have to enter a value for every input() function
you need to organize your code, maybe look at how others write their code
this is a quick fix, but it doesn't mean that this is the standard, you still have a lot to learn
import random
class character:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
charspells = ['Fireball','iceblock']
Loop = True
items = []
mainc = character(100, 100, 10, 0, 10)
tai_lopez = character(30, 30, 5, 0, 10) # enemy
def fireball(character, enemy):
enemy.hp -= character.int
print('You did, ',character.int ,'to the enemy')
print('Enemy.hp', enemy.hp)
return enemy.hp
def character_battle(character, enemy):
choice = input('What would you like to do?\n 1. Attack \n 2. Spells \n 3. Items \n 4. Run')
if choice == '1':
print('You attack the enemy!')
enemy.hp -= character.att
print('You dealt', character.att, 'to the enemy!')
print('Enemy hp =', enemy.hp)
if choice == '2':
print('Which spell do you wish to call?')
print('1.', charspells[0],'\n' '2.', charspells[1], '\n' 'q', 'exit')
spellchoice = input()
if spellchoice == ('1'):
print('You used fireball!')
fireball(character, enemy)
elif spellchoice == ('2'):
if charspells[1] != 'Lightning bolt':
print('It doesnt exist, sorry')
# ill add more spell fucntions later
if spellchoice == ('3'):
print('You went back to the menu')
if choice == '3':
if items == []:
print('You have no items')
if items == ['potions']:
print ('response')
#placeholder ill add the fucntion later
elif choice == '4':
print("You cowardly run away")
exit()
def enemy_battle(enemy, character):
a = random.randint(0,50)
if a <= 35:
print('The enemy attacks you!')
character.hp -= enemy.att
print('Your hp =', character.hp)
else:
print('The enemy uses mind attacks bruh')
character.hp -= enemy.int
print('Your hp =', character.hp)
def battle_loop(character, enemy):
Loop1 = True
while Loop1:
while enemy.hp > 0 and character.hp > 0:
character_battle(character, enemy)
enemy_battle(character, enemy)
if enemy.hp <= 0:
print('You Won')
Loop1 = False
if character.hp <= 0:
print('You lost')
exit()
battle_loop(mainc, tai_lopez)

Python code unexpected behavior when entering my loop [closed]

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

Categories