我正在努力弄清楚如何在这里组织事情。 我正在建立一场比赛。有球员和赛马场。玩家拥有名称,年龄等属性。竞赛课程也有一组属性,包括难度。我想做的一件事是,当一名球员跑完球场时,他们的能量水平会根据球场的难度而下降。我很困惑的是,因为难度是球场的一个属性,能量水平是球员的一个属性,我怎么能影响这两个?
以代码为例......
class Player():
energy_level = 0
def __init__(self, name, ability)
self.name = name
self.ability = ability
def run(self):
#code to run course here, reduces energy level when running course. Energy level is reduced based on player ability
class Course():
def __init__(self, name, difficulty)
self.name = name
self.difficulty = difficulty
player1 = Player("Bob", 90)
course1 = Course("Advanced Track", 15)
也许我说这一切都错了?当然需要成为一个班级吗?
感谢您的任何意见。
答案 0 :(得分:3)
我如何影响这两个?
这可以通过将类型为Course的对象传递给run
函数来实现,如下所示:
class Player():
energy_level = 0
def __init__(self, name, ability)
self.name = name
self.ability = ability
def run(self, course):
#use course.difficulty to reduce self.energy_level
class Course():
def __init__(self, name, difficulty)
self.name = name
self.difficulty = difficulty
player1 = Player("Bob", 90)
course1 = Course("Advanced Track", 15)
player1.run(course1) # this will pass course1 to the run function and run will reduce the energy level according to the difficulty of course1
答案 1 :(得分:0)
你可以让课程成为球员类的成员
class Player():
course = null;
energy_level = 0
def __init__(self, name, ability)
self.name = name
self.ability = ability
self.course1 = Course("Advanced Track", 15)
def run(self):
#code to run course here, reduces energy level when running course. Energy level is reduced based on player ability
#change self.energy based on self.course1.difficulty
当然这是过于简单化了。您需要添加方法来打开新课程,而不是在构造函数中对其进行硬编码。