来自di的可变函数调用

2024-10-02 00:41:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个比较新的有相当多经验的人,我正在尝试做一个基于文本的冒险,我正在做一个战斗系统,希望有不同能力的敌人。我不是每次都为不同的敌人重现战斗,而是尝试为每个敌人使用可互换的字典。我的目标是创建一个函数调用,该函数调用根据敌方在战斗中的位置而变化,而不必进入对象。我下面有一个例子,想知道是否有一种方法可以做类似的事情。你知道吗

wolf = {'ability': 'bite'}
bear = {'ability': 'claw'}
enemy = {}

def claw():
    print('stuff')

def bite():
    print('different stuff')

def use_ability():
    enemy = wolf
    enemy['ability']()

use_ability()

Tags: 文本use系统def经验冒险print函数调用
2条回答

你可以做到:

def claw():
    print('stuff')

def bite():
    print('different stuff')

wolf = {'ability': bite}
bear = {'ability': claw}

def use_ability(enemy):
    enemy['ability']()

use_ability(wolf)
# different stuff

但这并不意味着你应该这样做。你知道吗

使用面向对象编程。如果您只想使用dict和函数,那么您可能应该改为编写Javascript。你知道吗

我忍不住要做一个小程序,解释如何用面向对象的语言来做:

You should look up some guides how OOP-Languages work, because when making a game it will be really helpfull if you do it that way

http://www.python-course.eu/object_oriented_programming.php

# This is the SUPERCLASS it holds functions and variables 
# that all classes related to this object use
class Enemy(object):
    # Here we initialise our Class with varibales I've given an example of how to do that
    def __init__(self, HP, MAXHP, ability):
        self.HP = HP
        self.MAXHP = MAXHP
        self.ability = ability

    # This function will be used by both Bear and Wolf!
    def use_ability(self):
        print(self.ability)

# This is our Wolf Object or Class
class Wolf(Enemy):
    # Here we init the class inheriting from (Enemy)
    def __init__(self, ability, HP, MAXHP):
        super().__init__(HP, MAXHP, ability)

    # Here we call the superfunction of this Object.
    def use_ability(self):
        super().use_ability()

# Same as Wolf
class Bear(Enemy):
    def __init__(self, ability, HP, MAXHP):
        super().__init__(HP, MAXHP, ability)

    def use_ability(self):
        super().use_ability()

# How to init Classes
wolf_abilities = 'bite'
w = Wolf(wolf_abilities, 10, 10)

bear_abilities = 'claw'
b = Bear(bear_abilities, 10, 10)

# How to use methods from Classes
b.use_ability() # This will print 'bite'
w.use_ability() # This will print 'claw'

相关问题 更多 >

    热门问题