Numbers Appearing blank - python

I'm trying to make a text-based RPG kinda game and whenever I try and print the damage done or hp or other things, it sometimes appears blank ( just a bigger space in between the strings) I'm using replit to run and edit my code. In addidtion to this (and this isnt that big of an issue) Whenever its printing out the players HP then it comes to something like 9.7999999999999, why is this?
LOGIC AND CALCULATION CODE BELOW
#Imports
from player import Player
from items import Item
from spells import Spells
from monsters import Monster
from gameplay import Fight
#Creating spells
# Type, Name, Damage, Cost
#Below are buff spells
buff_A = Spells("buff", "Buff", 1.1, 5)
buff_B = Spells("buff", "Stronger Buff", 1.3, 15)
buff_C = Spells("buff", "Strongest Buff", 1.5, 50)
#Below Are heal spells
heal_A = Spells("heal", "Heal", 5, 10)
heal_B = Spells("heal", "Stronger Heal", 20, 30)
heal_C = Spells("heal", "Strongest Heal", 50, 100)
#Creating Items
#Type, Name, Description, Amount
potion = Item("potion", "Health Potion", "Heals you for 10 HP", 10)
elixir = Item("elixir", "Mana Potion", "Regains 15 MP", 15)
#Assiging Variables For Player
player_spells = [buff_A, heal_A]
player_items = [potion, elixir]
#Creating player
#NAME, HP, MP, ATK, DEF, SPELLS, ITEMS
player = Player("Nathan", 10, 20, 5, 5, player_spells, player_items)
#Creating monster
cricket = Monster("Cricket", 3, 3, 7)
enemies = [cricket]
#Fight Setup
fighting = True
#gameplay
fight1 = Fight(player, cricket)
running = True
def player_hurt(enemy):
edamage = enemy.damage_dealt()
player.take_dmg(edamage)
print("You have taken " + str(edamage) + " damage")
print(str(player.hp) + " / " + str(player.maxhp))
#action = input("Please select an action, Attack, Magic, Items ")
while running:
print("1 for attack etc.")
choice = input(player.actions)
list_chooser = int(choice) - 1
#ATTACK CHOOSE
if list_chooser == 0:
dmg = player.generate_dmg()
enemies[0].damage_taken(dmg)
print("You did " + str(dmg) + " damage")
player_hurt(enemies[0])
if cricket.hp == 0:
print("You have killed the cricket")
running = False
#Add Exp element here later
#MAGIC CHOOSE
if list_chooser == 1:
print("Choose 1 for first spell, etc. ")
magic_choice = input()
magic_choice_real = int(magic_choice) - 1
if magic_choice_real == 0:
print("idek how to code this")
if magic_choice_real == 1:
if player.mp < heal_A.cost:
print("Insufficient mana")
if player.mp >= heal_A.cost:
player.heal(heal_A.dmg)
print("You healed for " + str(heal_A.dmg))
player.mp -= heal_A.cost
print("You lost " + str(heal_A.cost) + " mana")
player_hurt(cricket)
PLAYER CODE BELOW
# IMPORTS
import random
#CLASS PLAYER
class Player():
def __init__(self, name, hp, mp, atk, df, magic, items):
self.maxhp = hp
self.hp = hp
self.maxmp = mp
self.mp = mp
self.atklow = atk - 2
self.atkhigh = atk + 2
self.df = df - 100
self.dfc = df / 100
self.magic = magic
self.items = items
self.actions = ["Attack", "Magic", "Items", "Stats"]
self.name = name
#Dealing Damage
def generate_dmg(self):
return random.randrange(self.atklow, self.atkhigh)
#Taking Damage
def take_dmg(self, dmg):
self.hp -= dmg * self.dfc
if self.hp < 0:
self.hp = 0
return self.hp
#Healing
def heal(self, dmg):
self.hp += dmg
if self.hp > self.maxhp:
self.hp = self.maxhp
#Returning HP Values
def get_hp(self):
return self.hp
def get_maxhp(self):
return self.maxhp
#Mana Cost Logic
def reduce_mp(self, cost):
self.mp -= cost
#Actions
def get_stats(self):
print("HP")
print(self.hp)
print("--")
print(self.maxhp)
print("")
print("MP")
print(self.mp)
print("--")
print(self.maxmp)
print("")
print("ATK")
print(self.atklow + self.atkhigh)
print("DEF")
print(self.dfc)
MONSTER CODE BELOW
import random
class Monster:
def __init__(self, name, atk, df, hp):
self.name = name
self.atk = atk
self.hp = hp
self.maxhp = hp
self.atklow = self.atk - 2
self.atkhigh = self.atk + 2
def damage_dealt(self):
return random.randrange(self.atklow, self.atkhigh)
def damage_taken(self, dmg):
self.hp -= dmg
if self.hp < 0:
self.hp = 0
return self.hp
def get_hp(self):
return self.hp
def get_maxhp(self):
return self.maxhp
SPELLS
import random
class Spells:
def __init__(self, type, name, dmg, cost):
self.type = type
self.name = name
self.dmg = dmg
self.cost = cost
def generate_dmg(self):
low = self.dmg + 3
high = self.dmg - 3
return random.randrange(low, high)
ITEMS
class Item:
def __init__(self, type, name, desc, amount):
self.type = type
self.name = name
self.desc = desc
self.amount = amount
GAMEPLAY(not sure if this is gonna be used)
import random
import os
class Fight:
def __init__(self, enemy, player):
self.enemy = enemy
self.player = player
self.playert = True
self.enemyt = False
self.player_action_allowed = False
self.player_action_allowed = False
def turns(self):
if self.playert == True:
self.player_action_allowed = True
self.enemyt = True
self.playert = False
elif self.enemyt == True:
enemy_action_allowed = True
player_action_allowed = False
playert = True
enemyt = False
else:
playert = True

Related

How can I move around a list filled with class calls and when I'm on the class' indexspot how can I call it?

I've recently been trying to make a Textadventure but I'm having a big problem with the idea of "moving" around a List (x_achses) with a List inside(y-achses) it (my father called it a matrix) and in the second list (y-achses) there are a bunch of random types of things like an enemy. In that "Matrix" I wanna move around and on certain fields it should activate the assigned class(here it should simply print the classes name).
I've tried using the index of the list and changing dependently but it didn't work, I've tried using the len() function and changing it dependently but nothing ever seems to be happening. No classes or anything seem to be called. I have no idea what to do.
import random
import secrets
class Character:
def __init__(self, hp, ad, name):
self.hp = hp
self.ad = ad
self.name = name
def get_hit(self, ad):
self.hp = self.hp - ad
if self.hp <= 0:
self.die()
def is_dead(self):
return self.hp <= 0
def die(self):
print(self.name + " died")
class Human_enemies(Character):
def __init__(self):
super().__init__(self, 10, 3, "Mermaids")
Human_enemies.enemie_amount = random.randint(1, 9)
print("Mermaids")
def enemie_amount(self):
enemie_amount = random.randint(1, 9)
enemies = []
for i in range(enemie_amount):
enemies.append(Human_enemies())
class Vessel:
def __init__(self, hp, ad, storage, name):
self.hp = hp
self.ad = ad
self.storage = storage
self.name = name
def get_hit(self, ad):
self.hp = self.hp - ad
if self.hp <= 0:
self.die()
def is_dead(self):
return self.hp <= 0
def die(self):
print(self.name + " died")
class Sloop_ship(Vessel):
def __init__(self):
super().__init__(self, 1000, 50-100, 0, "Sloop")
def type(self):
print("Sloop")
class Brigattine_ship(Vessel):
def __init__(self):
super().__init__(self, 2500, 70-110, 15, "Brig")
def type(self):
print("Brig")
class Galleon_ship(Vessel):
def __init__(self):
super().__init__(self, 5000, 150-200, 40, "Galleon")
def type(self):
print("Galleon")
class Shipwreck:
def __init__(self):
print("Shipwreck")
wanna_loot = input("Do you want to check the wreck for any loot or survivors?\n")
#TODO: Make this better, sth. like chance of death or sth.
class Fields:
def Rougethingi(self):
random1 = random.randint(0, 5)
if random1 == 0:
return Shipwreck
elif random1 == 1:
return Human_enemies
elif random1 == 2:
return Sloop_ship
elif random1 == 3:
return Brigattine_ship
elif random1 == 4:
return Galleon_ship
else:
return None
class Map():
def __init__(self, x, y):
self.rowsX = []
self.x = x
self.y = y
for i in range(x):
self.rowsY = []
for r in range(y):
self.rowsY.append(Fields.Rougethingi(self))
self.rowsX.append(self.rowsY)
def print_map(self):
for j in self.rowsX:
print("")
for f in self.rowsY:
if f == None:
print("0 ", end = "")
elif f != None:
print("1 ", end = "")
print("\n")
class Player(Character):
def __init__(self):
super().__init__(self, 100, 1, player_name)
def start(self):
self.player_x = 1
self.player_y = 1
n.rowsX[self.player_x].__init__()
n.rowsY[self.player_y].__init__()
def move_right(self):
self.player_x = self.player_x + 1
if self.player_x >= n.x or self.player_x >= n.x - n.x:
print("You can't go further right")
def move_left(self):
self.player_x = self.player_x - 1
if self.player_x >= n.x or self.player_x >= n.x - n.x:
print("You can't go further right")
def move_up(self):
self.player_y = self.player_y + 1
if self.player_y >= n.y or self.player_y >= n.y - n.y:
print("You can't go further right")
def move_down(self):
self.player_y = self.player_y - 1
if self.player_y >= n.y or self.player_y >= n.y - n.y:
print("You can't go further right")
def quit_game():
exit("And the mighty adventurer decided to rest for the day...")
def print_help():
utility = print("(help, save, load, map,)")
movement = print("(forward, backwards, starboard, port)")
utility
movement
def save():
#TODO: Make a save system
pass
def load():
#TODO: Make a load system
pass
if __name__ == "__main__":
player_name = input("What is thy title scalywag?\n")
n = Map(30, 30)
m = Player.start
print("You shall call us for 'help' to help you with your role of Captain\n")
#? This is the main input loop --------------------------------------v
while True:
cmd = input(">>>")
if cmd == "help":
print_help()
continue
elif cmd == "map":
n.print_map()
continue
elif cmd == "quit":
quit_game()
elif cmd == "save":
save()
continue
elif cmd == "load":
load()
continue
elif cmd == "forward":
Player.move_up
continue
elif cmd == "backwards":
Player.move_down
continue
elif cmd == "starboard":
Player.move_right
continue
elif cmd == "port":
Player.move_left
continue
else:
print("I dont understand that... \n")
continue
#? This is the main input loop --------------------------------------v

i would like to assign subclasses to the charecter? how do i do this?

the problem i has is that the errors that occur are found in the code that works. it doesnt make sence.
my code is:
import random
import pickle
class person():
def __init__(self, name, hp, luck, xp, level, gold, age, location, strength, intellegence):
self.name = name
self.hp = hp
self.luck = luck
self.xp = xp
self.level = level
self.strength = strength
self.gold = gold
self.location = location
self.age = age
self.intellegence = intellegence
#self.x = 0
#self.y = 0
def talk(self):
return "hello my name is %s. i have %d strength. i am %d years old. i am from %s. I have %d intellence" %(self.name,self.strength,self.age,self.location, self.intellegence)
#def walk(self,newlocation):
# self.x += movex
# self.y += movey
# self.location = newlocation
def takedmg(self, amount):
self.hp = self.hp - amount
def heal(self, amount):
self.hp = self.hp + amount
def attack(self):
pass
allpeople = []
def createperson():
global allpeople
name = input("enter name: ")
hp = 100
luck = random.randint(1,15)
xp = 0
level = 1
gold = 0
age = int(input("enter age: "))
location = input("enter location: ")
strength = random.randint(1,25)
intellegence = 50
aperson = person(name, hp, luck, xp, level, gold, age, location, strength, intellegence)
allpeople.append(aperson)
savedata()
def findchara():
charaname = input("enter the name of the charecter: ")
for foundchara in allpeople:
if foundchara.name == charaname:
print("found \n")
return(foundchara)
return""
def savedata():
savedata = open("mypeople.pickle","wb")
pickle.dump(allpeople,savedata)
savedata.close()
def loaddata():
global allpeople
loaddata = open("mypeople.pickle","rb")
allpeople = pickle.load(loaddata)
loaddata.close()
class warrior(person):
def __init__(self, name, hp, luck, xp, level, gold, age, location, strength, intellegence):
person.__init__(self)
class1 = warrior
class mage(person):
def __init__(self, name, hp, luck, xp, level, gold, age, location, strength, intellegence):
person.__init__(self)
class1 = mage
class trader(person):
def __init__(self, name, hp, luck, xp, level, gold, age, location, strength, intellegence):
person.__init__(self)
class1 = trader
def talk_warrior(person, warrior):
self.strength = self.strength + 15
self.intellegence = self.intellegence - self.intellegence + random.randint(0,5)
return "Hi, name is %s. %d strength. I am %d. from %s. intellegence? %d" %(self.name,self.strength,self.age,self.location,self.intellegence)
def talk_mage(person, mage):
self.strength = self.strength - self.strength + random.randint(0,5)
self.intellegence = self.intellegence + 50
return "Hello my name is The Great MAGE %s. I have %d strength DONT QUESTION MY STRENGTH. I am %d years old. I happened to be from %s. my intellegence also happens to be %d which is superior to everyone else." %(self.name,self.strength,self.age,self.location,self.intellegence)
def talk_trader(person, trader):
return "Hello my name is %s. I have %d strength. I am %d years old. I am from %s. I am very average and my intellegence is %d " %(self.name,self.strength,self.age,self.location,self.intellegence)
loaddata()
def classmenu():
charaloop = True
while charaloop == True:
option = int(input("1. warrior \n2. mage \n3. trader \n9. change class \n0. exit \n"))
if option == 1:
classchara = findchara()
class1 = warrior
print("Class has been set to warrior.")
talk_warrior()
elif option == 2:
classchara = findchara()
class1 = mage
print("Class has been set set to mage.")
talk_mage()
elif option == 3:
classchara = findchara()
class1 = trader
print("Class has been set to trader.")
talk_trader()
elif option == 9:
pass
elif option == 0:
print("returning to main menu. :) \n")
charaloop = False
savedata()
else:
print("invalid choice")
def menu():
mainloop = True
while mainloop == True:
option = int(input("1. create character. \n2. character list. \n3. look for a charecter. \n4. select charecter class. \n8. continue... \n9. delete character from list. \n0. exit \n choice: "))
if option == 1:
print("you will now create your character!!!")
createperson()
elif option == 2:
for aPerson in allpeople:
print(aPerson.talk())
elif option == 3:
findchara()
elif option == 4:
classmenu()
elif option == 8:
if class1 == warrior:
talk_warrior()
elif class1 == mage:
talk_mage()
elif class1 == trader:
talk_trader()
else:
print("ERROR!")
elif option == 9:
chara = findchara()
allpeople.remove(chara)
print("charecter removed")
savedata()
elif option == 0:
print("bye!!! :)")
mainloop = False
savedata()
else:
print("invalid choice")
menu()
the errors are:
Traceback (most recent call last):
File "D:\python stuff\python chara game ulsfdgklfsgnklfs.py", line 173, in <module>
menu()
File "D:\python stuff\python chara game ulsfdgklfsgnklfs.py", line 151, in menu
classmenu()
File "D:\python stuff\python chara game ulsfdgklfsgnklfs.py", line 118, in classmenu
talk_warrior()
TypeError: talk_warrior() missing 2 required positional arguments: 'person' and 'warrior'
the code is meant to run in the shell and is a simple class and subclass game that the player creates a character and then assigns it a subclass which changes the attributes of the character. this is where my problems started. in the future I want the character to be able to travel and then will encounter monsters attack and receive damage.
id like to hear some advice on what I could do to improve and make the code better smoother and also fix these problems that have occurred. I've only been coding for a while so there is allot of things wrong with this code.

Subtracting giving too little of a result

Been trying to code a small game for the past week now and whenever I calculate the damage and print the enemy's hp and the damage dealt, theres a difference of 2 every single time. Enemy's Hp is 2 less than the supposed "damage dealt". Also, is there any way to round numbers up and down?
Main
#Imports
import os
from player import Player
from items import Item
from spells import Spells
from monsters import Monster
from gameplay import Fight
#Creating spells
# Type, Name, Damage, Cost
#Below are buff spells
buff_A = Spells("buff", "Buff", 1.1, 5)
buff_B = Spells("buff", "Stronger Buff", 1.3, 15)
buff_C = Spells("buff", "Strongest Buff", 1.5, 50)
#Below Are heal spells
heal_A = Spells("heal", "Heal", 5, 10)
heal_B = Spells("heal", "Stronger Heal", 20, 30)
heal_C = Spells("heal", "Strongest Heal", 50, 100)
#Creating Items
#Type, Name, Description, Amount
potion = Item("potion", "Health Potion", "Heals you for 10 HP", 10)
elixir = Item("elixir", "Mana Potion", "Regains 15 MP", 15)
#Assiging Variables For Player
player_spells = [buff_A, heal_A]
player_items = [potion, elixir]
#Creating player
#NAME, HP, MP, ATK, DEF, SPELLS, ITEMS
player = Player("Nathan", 10, 20, 5, 5, player_spells, player_items, 1, 0)
#Creating monster
cricket = Monster("Cricket", 3, 3, 7)
enemies = [cricket]
#Fight Setup
fighting = True
#gameplay
fight1 = Fight(player, cricket)
running = True
def player_hurt(enemy):
edamage = enemy.damage_dealt()
player.take_dmg(edamage)
print("You have taken " + str(edamage) + " damage")
print(str(player.hp) + " / " + str(player.maxhp))
def enemy_hurt(es):
pdamage = player.generate_dmg()
enemies[es].damage_taken(pdamage)
print("Enemies HP is " + str(enemies[es].hp) + " / " + str(enemies[es].maxhp))
#action = input("Please select an action, Attack, Magic, Items ")
while running:
print("1 for attack etc.")
print("Please note that items are not available")
choice = input(player.actions)
list_chooser = int(choice) - 1
#ATTACK CHOOSE
if list_chooser == 0:
dmg = player.generate_dmg()
enemy_hurt(0)
print("You did " + str(dmg) + " damage")
player_hurt(enemies[0])
if cricket.hp == 0:
os.system('clear')
print("You have killed the cricket")
player.hp = player.maxhp
running = False
#Add Exp element here later
#MAGIC CHOOSE
if list_chooser == 1:
print("Choose 1 for first spell, etc. ")
magic_choice = input("Heal")
magic_choice_real = int(magic_choice) - 1
if magic_choice_real == 0:
if player.mp < heal_A.cost:
print("Insufficient mana")
if player.mp >= heal_A.cost:
player.heal(heal_A.dmg)
print("You healed for " + str(heal_A.dmg))
player.mp -= heal_A.cost
print("You lost " + str(heal_A.cost) + " mana")
player_hurt(cricket)
if list_chooser == 3:
player.get_stats()
Player
# IMPORTS
import random
#CLASS PLAYER
class Player():
def __init__(self, name, hp, mp, atk, df, magic, items, lv, exp):
self.lv = lv
self.exp = exp
self.exp_next = lv * 50
self.maxhp = hp
self.hp = hp
self.maxmp = mp
self.mp = mp
self.atklow = atk - 2
self.atkhigh = atk + self.lv
self.df = df - 100
self.dfc = df / 100
self.magic = magic
self.items = items
self.actions = ["Attack", "Magic", "Items", "Stats"]
self.name = name
#Dealing Damage
def generate_dmg(self):
return random.randrange(self.atklow, self.atkhigh)
#Taking Damage
def take_dmg(self, dmg):
self.hp -= dmg
if self.hp < 0:
self.hp = 0
return self.hp
#Healing
def heal(self, dmg):
self.hp += dmg
if self.hp > self.maxhp:
self.hp = self.maxhp
#Returning HP Values
def get_hp(self):
return self.hp
def get_maxhp(self):
return self.maxhp
#Mana Cost Logic
def reduce_mp(self, cost):
self.mp -= cost
#Actions
def get_stats(self):
print("HP")
print(self.hp)
print("--")
print(self.maxhp)
print("")
print("MP")
print(self.mp)
print("--")
print(self.maxmp)
print("")
print("ATK")
print(self.atklow + self.atkhigh)
print("LV")
print(self.lv)
print("EXP AND EXP TO NEXT")
print(str(self.exp) + " / " + str(self.exp_next))
def level_up(self):
self.lv += 1
self.exp = 0
self.maxhp += self.lv
self.atk += self.lv
Monster
import random
class Monster:
def __init__(self, name, atk, df, hp):
self.name = name
self.atk = atk
self.hp = hp
self.maxhp = hp
self.atklow = self.atk - 2
self.atkhigh = self.atk + 2
def damage_dealt(self):
return random.randrange(self.atklow, self.atkhigh)
def damage_taken(self, dmg):
self.hp -= dmg
if self.hp < 0:
self.hp = 0
return self.hp
def get_hp(self):
return self.hp
def get_maxhp(self):
return self.maxhp
items
class Item:
def __init__(self, type, name, desc, amount):
self.type = type
self.name = name
self.desc = desc
self.amount = amount
Spells
import random
class Spells:
def __init__(self, type, name, dmg, cost):
self.type = type
self.name = name
self.dmg = dmg
self.cost = cost
def generate_dmg(self):
low = self.dmg + 3
high = self.dmg - 3
return random.randrange(low, high)
gameplay
import random
import os
class Fight:
def __init__(self, enemy, player):
self.enemy = enemy
self.player = player
self.playert = True
self.enemyt = False
self.player_action_allowed = False
self.player_action_allowed = False
def turns(self):
if self.playert == True:
self.player_action_allowed = True
self.enemyt = True
self.playert = False
elif self.enemyt == True:
enemy_action_allowed = True
player_action_allowed = False
playert = True
enemyt = False
else:
playert = True
Your loop generates damage, and then calls enemy_hurt:
while running:
# ...
dmg = player.generate_dmg()
enemy_hurt(0)
print("You did " + str(dmg) + " damage")
But enemy_hurt also generates damage of its own:
def enemy_hurt(es):
pdamage = player.generate_dmg()
enemies[es].damage_taken(pdamage)
print("Enemies HP is " + str(enemies[es].hp) + " / " + str(enemies[es].maxhp))
Surely you want to only generate damage once, right? You're generating two different damage values, one you print, the other you actually subtract from the enemy's health.

List index out of range in class

All code
import random
import time
class Enemy():
def __init__(self):
self.health = 100
self.power = random.randint(10,20)
def hit(self, player):
player.health -= self.power
class player():
def __init__(self):
self.health = 300
self.power = 50
def hit(self, Enemy):
Enemy.health -= self.power
player1 = player()
enemies = []
for i in range(5): # create 5 enemy
enemies.append(Enemy())
print("Play - Help - Quit")
action1 = input("Type 'hit' for enemies\n>>>> ")
while action1 != 'q':
print("---------------")
for i in range(len(enemies)):
print("#{}.enemy heatlh-->{}".format(i, enemies[i].health))
print("----------------")
random_enemy = random.randint(1, 5)
action = input(">>>> ")
if action == 'hit':
which = int(input("Which enemy? there are {} enemies\n>>>>".format(len(enemies))))
if enemies[which].health == 0:
enemies[which].health = 0
print("\nThis is a death enemy")
else:
player1.hit(enemies[which])
damage_enemy = random.randint(1,5)
if enemies[random_enemy].health == 0:
continue
else:
if damage_enemy == 1 or damage_enemy == 3 or damage_enemy == 4:
if enemies[which].health == 0 or enemies[which].health <= 0:
enemies[which].health = 0
print("{}. enemy death HP: {} ".format(which, enemies[which].health))
else:
enemies[random_enemy].hit(player1)
print("{}. enemy hit you {} damage, your HP: {} ".format(random_enemy,enemies[random_enemy].power,player1.health))
elif enemies[which].health != 0 or enemies[which].health >= 0:
print("{}. enemy HP: {} ".format(which, enemies[which].health))
elif action == 'q':
break
I get this error at random time, my list size is 5, enemies die and their healths are 0. They stay there, but for some reason sometimes I get this error.
#0.enemy heatlh-->100
#1.enemy heatlh-->100
#2.enemy heatlh-->0
#3.enemy heatlh-->0
#4.enemy heatlh-->100
if enemies[random_enemy].health == 0:
continue
The random.randint(1, 5) can return 5. Your list has 5 elements, but the indices are from 0 to 4.
P.S. Also, the minimum value that you get is 1. Not 0.

Game getting stuck

I'm following a Python course on Udemy.com and we are practicing Python by building an RPG game. So far the game was working fine for a single player but as soon as we added 3 players the game seems to just get stuck after executing all 3 players attacks.
The concept is that there are 3 players or so, as the game starts the player stats are shown, after all the players have attacked each other this includes the enemy as well, the player stats are printed as shown below in the picture and the game asks for input from all the three players again, but it's just running once as shown below in the picture.
I followed the code for word to word and also posted a question regarding it. So I thought I should try StackoverFlow.
Below is my code kindly see why is it not going in loop as it should.
Mainfile
# -*- coding: utf-8 -*-
from game_class.invin import Item
from game_class.game import player
from game_class.magic import Spell
import time
# Player and Enemies magic create
Fire_Shot = Spell('Fire Shot', 10, 45, "Black Magic")
Thunder_Storm = Spell("Thunder Storm",25,65,"Black Magic")
Ninja_Summon = Spell("Ninja Summon",45,75,"Ninjustu")
The_End = Spell("THE END",80,300,"Finisher")
Heal = Spell("HEAL ME",60,140,'Heal')
player_magic = [Fire_Shot,Thunder_Storm,Ninja_Summon,Heal,The_End]
enemy_magic = [
{'Name': "Big Punch", 'cost': 30, "DMG": 45},
{'Name': "Slap", 'cost': 15, "DMG": 25},
{'Name': "Rock Throw", 'cost': 20, "DMG": 30},
{'Name': "Kick", 'cost': 45, "DMG": 60}
]
boss_magic = [
{'Name': "STORM", 'cost': 10, "DMG": 45},
{'Name': "DARK BACK-BITTING", 'cost': 10, "DMG": 25},
{'Name': "D.D.T", 'cost': 10, "DMG": 30}
]
# Items create
potion = Item("Potion", 'Potion', 'Heals for 50 HP', 50)
high_potion = Item("Potion+", 'Potion', 'Heals for 120 HP', 120)
super_potion = Item("Ultra Potion", 'Potion', 'Heal for 250 HP', 250)
elixir = Item("Elixir", 'Elixir', 'Give 1 EVERYTHING BACK', 9000)
high_elixir = Item("Omega Elixir", 'Elixir', 'Give all EVERYTHING BACK', 9000)
bomb = Item("Bomb",'Attack','Deals 350 Damage',350)
player_items = [ {"item":potion,"quantity":3},
{'item':high_potion,"quantity":2}
,{"item":super_potion,"quantity":1}
,{'item':elixir,"quantity":2}
,{'item':high_elixir,"quantity":1}
,{"item": bomb, "quantity": 2} ]
# PLAYER CREATE
Player1 = player('Night Man ',1000, 100, 145, 140, player_magic, player_items)
Player2 = player('Ray Wills ', 1000, 100, 155, 135, player_magic, player_items)
Player3 = player("Randy Orton",1000, 100, 150, 120, player_magic, player_items)
Enemy1 = player("Door Keeper",1500, 200, 250, 150, enemy_magic, None)
BOSS = player("Boss Man",1200, 200, 45, 300, boss_magic, None)
players = [Player1,Player2,Player3]
# Game starts
run = True
i = 1
while run is True:
print ("=======================================")
print("\n\n")
print(" NAME HP MP\n")
for player in players:
player.get_stats()
for player in players:
print("\n")
player.chose_action()
print("=========\n")
print (player.name)
print ("=============")
choice = input("CHOSE ACTION: ")
index = int(choice) - 1
if index == 0:
dmg = player.gen_dmg()
Enemy1.get_dmg(dmg)
print(player.name+ " attacked for " + str(dmg) + " damage points")
elif index == 1:
player.chose_magic()
magic_choice = (int(input("Chose Spell: ")) - 1)
spell = player.magic[magic_choice]
magic_dmg = spell.gen_spell_dmg()
current_mp = player.get_mp()
if magic_choice == -1:
continue
if spell.cost > current_mp:
print ("\nNOT ENOUGH MANA")
continue
if spell.stype == "Heal":
player.heal(magic_dmg)
print (str(magic_dmg) +' HP restored')
print("Remaining Magic Points: " + str(player.get_mp()) +
"/" + str(player.get_max_mp()))
elif spell.stype == "Black Magic" or spell.stype == "Ninjustu" or spell.stype == "Finisher":
player.reduce_mp(spell.cost)
Enemy1.get_dmg(magic_dmg)
print (str(spell.name) + ' did damage of '+ str(magic_dmg) +" points")
print ("Remaining Magic Points: " + str(player.get_mp()) +"/" +str(player.get_max_mp()))
elif index == 2:
player.chose_item()
item_choice = (int(input("Chose Spell: ")) - 1)
if item_choice == -1:
continue
item = player.items[item_choice]['item']
if player.items[item_choice]['quantity'] == 0:
print("No Item...")
continue
player.items[item_choice]['quantity'] -= 1
if item.itype == 'Potion':
player.heal(item.prop)
print("\n"+ str(item.name) + " used and healed for "+ str(item.prop) + " HP")
elif item.itype == "Elixir":
player.hp = Player1.maxhp
player.mp = Player1.maxmp
print ("\n"+"STATS RESTORED BECASUE OF " +str(item.name))
elif item.itype == "Attack":
Enemy1.get_dmg(item.prop)
print ("You used a Bomb & that dealt damage of: " + str(item.prop))
enemy_choice = 1
enemy_dmg = Enemy1.gen_dmg()
Player1.get_dmg(enemy_dmg)
print("========================================")
print("\n")
print ("ENEMY ATTACKED YOU FOR " + str(enemy_dmg) + " POINTS")
print ("ENEMY HP: "+str(Enemy1.get_hp()) +'/'+ str(Enemy1.get_maxhp()))
if Enemy1.get_hp() == 0:
print('')
print ('ENEMY DEAD')
run = False
elif Player1.get_hp() == 0:
print('')
print('YOU DIED')
run = False
elif index == 3:
print("Arigato Gozaimasu for playing")
time.sleep(1)
print ("BYE BYE")
run = False
invin.py
class Item:
def __init__(self, name,itype,desc,prop):
self.name = name
self.itype = itype
self.desc = desc
self.prop = prop
magic.py
import random
class Spell():
def __init__(self, name, cost,dmg,stype):
self.name = name
self.cost = cost
self.dmg = dmg
self.stype = stype
def gen_spell_dmg(self):
low = self.dmg - 15
high = self.dmg + 10
return random.randrange(low,high)
game.py
# -*- coding: utf-8 -*-
from .magic import Spell
import random
class player:
def __init__(self,name, hp , mp , atk ,df ,magic,items):
self.hp = hp
self.name = name
self.items = items
self.mp = mp
self.magic = magic
self.df = df
self.maxhp = hp
self.atkH = atk + 25
self.atkL= atk - 10
self.actions=['Attack',"Magic","Items"]
self.maxmp = mp + 10
def gen_dmg(self):
return random.randrange(self.atkL,self.atkH)
def get_dmg(self,dmg):
self.hp -= dmg
if self.hp < 0:
self.hp = 0
return self.hp
def get_hp(self):
return self.hp
def get_maxhp(self):
return self.maxhp
def get_max_mp(self):
return self.maxmp
def get_mp(self):
return self.mp
def reduce_mp(self,cost):
self.mp -= cost
def spell_cost(self, i):
return self.magic[i]["cost"]
def chose_action(self):
print ("Actions")
print ("===========")
i = 1
for item in self.actions:
print(" " + str(i)+":" + str(item))
i += 1
def chose_magic(self):
print ("Spells")
print ("===========")
i = 1
for spell in self.magic:
print (" " + str(i) + ": " + str(spell.name) + str( " (Cost: " + str ( spell.cost ) +")" ) )
#the 3rd str helps to print it without the brackets
i += 1
def chose_item(self):
print ("Items")
print ("===========")
i = 1
for item in self.items:
print(" " + str(i) + ": " +
str(item['item'].name) + str(" (" + str(item['item'].desc) + ") ") + " (x"+str(item['quantity'])+")")
#the 3rd str helps to print it without the brackets
i += 1
def heal(self,dmg):
self.hp += dmg
def get_stats(self):
hp_bar = ''
bar_ticks = ( (self.hp/self.maxhp) * 100 ) / 4
mp_bar = ''
mp_bar_ticks = ( (self.mp/self.maxmp) * 100 ) / 10
while bar_ticks > 0:
hp_bar += '█'
bar_ticks -= 1
while len(hp_bar) < 25:
hp_bar = " "
while mp_bar_ticks > 0:
mp_bar += '▒'
mp_bar_ticks -= 1
while len(mp_bar) < 10:
mp_bar = " "
hp_string = str(self.hp) + "/"+str(self.maxhp)
current_hp = ''
if len(hp_string) < 9:
decreased = 9 - len(hp_string)
while decreased > 0:
current_hp += ' '
decreased -= 1
current_hp += hp_string
else:
current_hp = hp_string
mp_string = str(self.mp) +"/"+str(self.maxmp)
current_mp = ''
if len(mp_string) < 9:
mp_decreased = 9 - len(mp_string)
while mp_decreased > 0:
current_mp += ' '
mp_decreased -= 1
current_mp += mp_string
else:
current_mp = mp_string
print(" _________________________ __________")
print(str(self.name) + " " + str(hp_string) +
" |"+ hp_bar+"| " + str(mp_string) + " |"+mp_bar+"|")
The game is an RPG replica and it works by using while loop.
Each player gets a turn and then the player stats are shown after all 3 players have attacked.
This is how the loop should show player stats after all 3 players attacked
But I'm getting this
If we compare the "This is how the loop should show player stats after all 3 players attacked" and "But I'm getting this" screenshots, we can see, by looking at the code, that the issue is caused on the second run of player.get_stats(). This method is defined in the game.py file.
Inside the method we can see the following 2 lines of code:
while len(hp_bar) < 25:
hp_bar = " "
If the while-loop ever gets to run, it will be stuck forever. This is because if len(hp_bar) < 25 is True, the code does hp_bar = " ", which in turns makes len(hp_bar) to be equal to 1 now. This now gets the while loop to check if len(hp_bar) < 25 again, which returns True (as len(hp_bar) is 1) so the while-loop runs again. This creates an endless loop.

Categories