我目前正在阅读一本名为“艰难学习Python 3”的书。
我已经完成了练习43,其中编写了一个小文本冒险游戏来练习面向对象编程。
我完成了程序代码的输入,并使其正常工作,没有任何错误。然后在附加研究部分,作者要求在脚本中添加一个简单的战斗系统。
完整的脚本可以在这个链接中看到,我不想将ex43的整个脚本粘贴到这个问题中。
https://github.com/ubarredo/LearnPythonTheHardWay/blob/master/ex43.py
我创建了以下脚本作为战斗系统:
import random
import time
class Player:
def __init__(self, hit_points, sides):
self.hit_points = hit_points
self.sides = sides
def take_hit(self):
self.hit_points -= 2
def roll(self):
return random.randint(1, self.sides)
class Combat(Player):
def combat_start():
p = Player(hit_points = 10, sides = 6)
e = Player(hit_points = 8, sides = 6)
battle = 1
while battle != 0:
human = p.roll() + 6
print("Your hit score: ", human)
monster = e.roll() + 6
print("Enemy hit score: ", monster)
if human > monster:
e.take_hit()
print("Your hit points remaining: ", p.hit_points)
print("Enemy hit points remaining:", e.hit_points)
if e.hit_points == 0:
battle = 0
print("The Enemy is Dead!!!")
time.sleep(2)
elif human < monster:
p.take_hit()
print("Your hit points remaining: ", p.hit_points)
print("Enemy points remaining: ", e.hit_points)
if p.hit_points == 0:
battle = 0
print("You died in Battle!!!")
time.sleep(2)
Combat.combat_start()
这本身就工作得很好,我想在书中的脚本中使用它。
我尝试从CentralCorridor类调用它。在玩家输入"shoot“后,我通过添加以下内容调用我编写的脚本:
Combat.combat_start()
我所希望发生的是,我写的战斗职业将开始,然后当玩家获胜时,它将继续下一个场景,如果玩家失败,它将返回死亡职业。
经过多次尝试和失败,我将格斗类改为:
class Combat(Scene, Player):
添加了这一点后,脚本运行,然后中断循环。
Your hit score: 12
Enemy hit score: 12
Your hit score: 10
Enemy hit score: 11
Your hit points remaining: 8
Enemy points remaining: 4
Your hit score: 10
Enemy hit score: 10
Your hit score: 12
Enemy hit score: 7
Your hit points remaining: 8
Enemy hit points remaining: 2
Your hit score: 7
Enemy hit score: 9
Your hit points remaining: 6
Enemy points remaining: 2
Your hit score: 7
Enemy hit score: 8
Your hit points remaining: 4
Enemy points remaining: 2
Your hit score: 9
Enemy hit score: 10
Your hit points remaining: 2
Enemy points remaining: 2
Your hit score: 10
Enemy hit score: 9
Your hit points remaining: 2
Enemy hit points remaining: 0
The Enemy is Dead!!!
Traceback (most recent call last):
File "ex43.py", line 220, in <module>
a_game.play()
File "ex43.py", line 24, in play
next_scene_name = current_scene.enter()
AttributeError: 'NoneType' object has no attribute 'enter'
如果敌方玩家得分较高,则循环在一轮或两轮后中断。
我正在努力寻找这个问题的解决方案,如果能指出我的错误所在,我会非常感激的。
通过查看其他答案,我看到一些评论,认为这不是用Python编写OOP的理想方式。
在书中,它显示了:
class Scene(object):
据我所知,这是Python2风格的OOP。我发现作者更喜欢Python2而不是Python3,我很喜欢他在书中写的练习,并希望继续下一篇。
任何帮助,一如既往,将非常感谢。
--更新
这是我们请求的播放方法:
def play(self):
current_scene = self.scene_map.opening_scene()
last_scene = self.scene_map.next_scene('finished')
while current_scene != last_scene:
next_scene_name = current_scene.enter()
current_scene = self.scene_map.next_scene(next_scene_name)
# be sure to print out the last scene
current_scene.enter()
https://stackoverflow.com/questions/51804530
复制相似问题