简体   繁体   English

为什么我的python类方法本身的行为与我运行模块时的行为不同?

[英]Why does my python class method behave differently by itself than when I run the module?

I am making a small text game, and one of my methods is behaving unexpectedly, and I can't figure out why. 我正在制作一个小型文本游戏,我的一种方法表现得出乎意料,我无法弄清楚原因。 If I import the module and run the method in python, it works fine. 如果我导入模块并在python中运行该方法,它工作正常。 Some parts of the game aren't complete, but that parts that I need run fine. 游戏的某些部分并不完整,但我需要的部分运行良好。

With the module pasted below, choose method is changing a list into a string, but only when the module is run. 使用下面粘贴的模块, 选择方法是将列表更改为字符串,但仅在模块运行时。 I'm running this on 2.7.3, on a mac. 我在2.7.3上运行它,在mac上。

Edit: I figured it out. 编辑:我想通了。 The program execution had continued, and I was confused by the choose call in the match method. 程序执行仍在继续,我对匹配方法中的选择调用感到困惑。 The options parameter sent in match was a string, instead of the list it should have been, but that was simple to figure out why. match中发送的options参数是一个字符串,而不是它本来应该的列表,但这很容易找出原因。

import fighters
import weapons
from random import randint
from sys import exit

class Hero(object):
    weapons = ["spikeglove", "shortsword"]
    hp = {"actual":50, "base":50}
    score = 0

    def attack(self, weapon, method):
        return None

class Scene(object):

    # Returns one or more items from the provided choices    
    def choose(self, options, max_choices, prompt):
        chosen = []
        while len(chosen) < max_choices and len(options) > 0:
            print
            print prompt
            print options, chosen
            for o in options:
                print "- {}".format(o)    
            print type(options)
            choice = raw_input("> ")
            if choice in options:
                chosen.append(choice)
                options.remove(choice)
                print options, chosen
            else:
                print "That is not one of the options!"
        if len(chosen) == 1:
            return chosen[0]
        else:
            return chosen  


class Death(Scene):
    def enter(self):
        print "You are now dead"
        return "menu"

class Exit(Scene):
    def enter(self):
        print "Thanks for playing!"
        return exit(1)

class Menu(Scene):

    def enter(self):
        menu_options = ["play", "train", "exit"]
        choice = self.choose(menu_options, 1, "Welcome to the Arena!")
        return choice

class Level(Scene):

    def __init__(self):
        self.prologue = "Welcome to {}".format(self.__class__.__name__)

    next_scene = "level1"

    # A match is the fight between the Hero and a particular Enemy
    # A Hero must defeat each Enemy via a match to win the tournament/level
    def match(self, hp, weapons, enemy):
        hero_hp = hp
        enemy_hp = enemy.stats["hp"]
        last_attack = ""
        while hero_hp and enemy_hp:
            weapon_choice = self.choose(weapons, 1, "> ")
            attack_choice = self.choose(weapon_choice.available_attacks(last_attack), 1, "> ")
            last_attack = attack_choice
            hero_attack = hero.attack(attack_choice)
            enemy_attack = enemy.attack()
            print "Hero: {}          {}: {}".format(hero_hp, enemy, enemy_hp)
        if hero_hp:
            return "victory", hero_hp
        else:
            return "defeat"

    # The game cycles through the enemies that our hero has to face
    # passing the setup to the "match" function for the fighting   
    def enter(self):
        print
        print
        print self.prologue
        start_hp = hero.hp['actual']
        weapons = self.choose(hero.weapons, 2, "Choose a weapon")
        while self.enemies:
            enemy = fighters.roster[self.enemies.pop()]
            match_outcome, finish_hp = self.match(start_hp, weapons, enemy)            
            if match_outcome == "defeat":
                hero.hp['actual'] = hero.hp['base']
                return "death"
            # The Hero enters the next match with the current HP obtained from the previous match
            start_hp = finish_hp

        # Add our Hero's victory points, and get them some medical attention 
        # before heading back to the Barracks
        points_award = 5
        hero.points += points_award
        hero.hp['actual'] = hero.hp['base']
        new_weapon = "shortsword"
        hero.add_weapon(new_weapon)
        epilogue = """Congratulations! 
                    You have gained {} points for a total score of {}.\n
                     You have unlocked the \"{}\" """.format(
                            points_award, hero.points, new_weapon)
        return next_scene

class Train(Scene):
    pass

class Level1(Level):

    enemies = ["boxer", "boxer"]
    next_scene = "level2"

class Level2(Level):
    pass

class Level3(Level):
    pass

class Level4(Level):
    pass

class Level5(Level):
    pass

class Engine(object):
    def __init__(self, start_scene):
        self.start_scene = start_scene

    scenes = {
        "menu": Menu(),
        "death": Death(),
        "exit": Exit(),
        "play": Level1(),
        "level2": Level2(),
        "level3": Level3(),
        "level4": Level4(),
        "level5": Level5(),       
    }

    def next_scene(self, scene_name):
        return self.scenes[scene_name]

    def play(self):
        current_scene = self.scenes[self.start_scene]
        while True:
            next_scene = current_scene.enter()
            current_scene = self.scenes[next_scene]

if __name__ == "__main__":
    hero = Hero()        
    game = Engine("menu")
    game.play()        

Terminal output: 终端输出:

$ python arena.py
Welcome to the Arena!
['play', 'train', 'exit'] []
- play
- train
- exit
<type 'list'>
> play
['train', 'exit'] ['play']


Welcome to Level1

Choose a weapon
['spikeglove'] []
- spikeglove
<type 'list'>
> spikeglove
[] ['spikeglove']

> 
spikeglove []
- s
- p
- i
- k
- e
- g
- l
- o
- v
- e
<type 'str'>

Yet when I run in python: 然而,当我在python中运行时:

>>> import arena
>>> s = arena.Level1()
>>> s.choose(['shortsword', 'spikeglove'], 2, "Choose a weapon")

Choose a weapon
['shortsword', 'spikeglove'] []
- shortsword
- spikeglove
<type 'list'>
> shortsword
['spikeglove'] ['shortsword']

Choose a weapon
['spikeglove'] ['shortsword']
- spikeglove
<type 'list'>
> spikeglove
[] ['shortsword', 'spikeglove']
['shortsword', 'spikeglove']

if __name__ == "__main__":表示在if-statement之后缩进的代码部分将仅在执行脚本时执行,而不是在导入脚本时执行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当类在函数中时,为什么类中的全局行为会有所不同? - why does global in a class behave differently when the class is within a function? Python:为什么带有附加参数的方法的行为有所不同? - Python: Why Does a Method Behave Differently with an Added Parameter? 为什么RestrictedPython在与Python 3.6一起使用时表现不同? - Why does RestrictedPython behave differently when used with Python 3.6? 我的正则表达式在网上的表现与在 python 中的表现不同 - My regex behave differently online than in python 为什么不同的格式方法在 Python 中表现不同? - Why different format method behave differently in Python? 为什么 Python 3 for loop output 和行为不同? - Why does Python 3 for loop output and behave differently? 为什么Python3.1中的代码行为与Python2.6中的行为不同? - Why does this code behave differently in Python3.1 than in Python2.6? 您能否使 python 脚本在导入时和直接运行时表现不同? - Can you make a python script behave differently when imported than when run directly? 为什么在Python中将迭代器设置为变量与直接在列表推导中使用迭代器的行为有所不同? - Why does setting an iterator to a variable in Python behave differently than using it directly in a list comprehension? 为什么 for 循环的行为与“pop” function 的 while 循环不同? - Why does the for loop behave differently than the while loop for the “pop” function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM