Sushmit Chakraborty Ответов: 1

Python text based rpg (код работает в версии 3.6, но не в версии 2.7.8)


Я успешно скомпилировал этот код в python 3.6,но когда я пытаюсь сделать то же самое, он выдает ошибку-

Код-

from random import randint
class Dice:
    def die(num):
        die=randint(1,num)
        return die

class Character:
    def __init__(self,name,hp,damage):
        self.name=name
        self.hp=hp
        self.damage=damage

class Fighter(Character):
    def __init__(self):
        super().__init__(name=input("what is your character's name?"),
                       hp=20,
                       damage=12)
        self.prof= "fighter"
        
class Assasin(Character):
    def __init__(self):
        super().__init__(name=input("what is your character's name?"),
                       hp=15,
                       damage=14)
        self.prof= "assasin"

##NOW FOR ENEMIES

class Goblin(Character):
    def __init__(self):
        super().__init__(name="goblin",
                     hp=15,
                     damage=3)
        
        

class Ogre(Character):
    def __init__(self):
        super().__init__(name="ogre",
                     hp=25,
                     damage=6)

##ENEMIES

def profession():
    print("What is your class?",'\n',
          "Press f for fighter" , '\n',
          "Press a for assasin")
    pclass=input("Enter your choice>>>")
    if(pclass=="f"):
        prof=Fighter()
    elif(pclass=="a"):
        prof=Assasin()
    else:
        prof=Fighter()
    return prof

def ranmob():
    roll=Dice.die(10)
    if roll<8:
        mob=Ogre()
    else:
        mob=Goblin()
    return mob

def playerAttack():
    roll=Dice.die(10)
    print("You hit")
    if (hero.prof=="fighter"):
        if(roll<8):
            print("them for 12 damage")
            mob.hp-=12
            print("The",mob.name,"has",mob.hp,"hp left")
        else:
            print("You missed your attack")
    elif(hero.prof=="assasin"):
        if(roll<8):
            print("them for 14 damage")
            mob.hp-=14
            print("The",mob.name,"has",mob.hp,"hp left")
        else:
            print("You missed your attack")

def monsterAttack():
    roll=Dice.die(10)
    if (mob.name=="ogre"):
        print("THE OGRE SHRIEKS and attacks")
        if(roll<8):
            print("6 damage taken")
            hero.hp-=6
            print("You now have",hero.hp,"hp left")
        else:
            print("The attack misses")

    elif (mob.name=="goblin"):
        print("The goblin prepares his knife and jumps")
        if(roll<8):
            print("3 damage taken")
            hero.hp-=3
            print("You now have",hero.hp,"hp left")
        else:
            print("The attack misses")

def commands():
    if hero.prof=="fighter":
        print("press f to fight\n","press e to pass")
        command=input(">>>>>")
        if(command=="f"):
            playerAttack()
        elif command=="e":
            pass
    elif hero.prof=="assasin":
        print("press f to fight\n","press e to pass")
        command=input(">>>>>")
        if(command=="f"):
            playerAttack()
        elif command=="e":
            pass

mob=ranmob()
hero=profession()

print("name hp"'\n',hero.name,hero.hp)

while True:
    if mob.hp<=0:
        print('The',mob.name,'is dead')
        mob=ranmob()
    if hero.hp<=0:
        print(hero.name,'died!')
        hero=profession()
        print("name hp",'\n',hero.name,hero.hp)

    print("You see",mob.name,",",mob.name,"has",mob.hp,"hp")
    if hero.hp>0:
        commands()
    if mob.hp>0:
        monsterAttack()

Ошибка-

Traceback (most recent call last):
  File "C:\Users\Hi\Desktop\python programs\2.7trail.py", line 120, in <module>
    mob=ranmob()
  File "C:\Users\Hi\Desktop\python programs\2.7trail.py", line 59, in ranmob
    roll=Dice.die(10)
TypeError: unbound method die() must be called with Dice instance as first argument (got int instance instead)


Что я уже пробовал:

Не уверен насчет ошибки.(......................................)

1 Ответов

Рейтинг:
10

Thomas Daniels

Добавить а staticmethod оформитель:

class Dice:
    @staticmethod
    def die(num):
        die=randint(1,num)
        return die
Причина ошибки: Python 2 требует, чтобы первый аргумент был экземпляром самого класса; в Python 3 это может быть что угодно.

[Редактировать]

Однако одно это изменение не сделает ваш код идеально работающим в Python 2. Python 3-х годов input принимает входные данные и возвращает строку с этими входными данными, но эквивалент Python 2 этого raw_input. Python 2 имеет input функция тоже, но она не просто принимает входные данные, она также вычисляет их (так что Python 2 input было бы eval(input()) в Python 3). Видеть этот вопрос переполнения стека для обратно совместимых входных вызовов в Python[^].


Sushmit Chakraborty

Спасибо :-)