我学习Python3已经有几个月了,刚刚开始学习面向对象编程。我在Stack Overflow上问了一个关于我正在尝试编写的文本冒险游戏的问题,它建议使用OOP会更好。
我做了一些搜索,因为我想要一个非常简单的战斗系统,可以在游戏中使用。我有游戏的基本框架,但我想要一些战斗系统方面的帮助。
以下是我到目前为止拥有的代码:
import random
import time as t
class Die:
def __init__(self, sides = 6):
self.sides = sides
def roll(self):
return random.randint(1, self.sides)
class Player:
def __init__(self):
self.hit_points = 10
def take_hit(self):
self.hit_points -= 2
class Enemy:
def __init__(self):
self.hit_points = 10
def take_hit(self):
self.hit_points -= 2
p = Player()
e = Enemy()
d = Die(6)
battle = 1
while battle != 0:
human = d.roll() + 6
print("Your hit score: ",human)
enemy = d.roll() + 6
print("Enemy hit score: ",enemy)
if human > enemy:
e.take_hit()
print("Your hit points remaining: ",p.hit_points)
print("Enemy points remaining: ", e.hit_points)
if e.hit_points == 0:
battle = 0
t.sleep(2)
elif human < enemy:
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
t.sleep(2)
die类用于模拟六面骰子,玩家和敌人用于游戏角色。之后,该代码被用来滚动随机数字,最高的数字赢得这一轮,直到玩家或敌人达到零点。
我不确定如何使用这三个类之后的最后几行代码,并从它创建一个类。
我需要能够在游戏中多次运行一场战斗,还需要存储玩家得分,每次战斗后都会扣分。
我真的很喜欢并喜欢使用对象,并希望变得更好,因此非常感谢您在这方面的任何帮助。
发布于 2018-08-07 07:06:31
您可以重用一个类,并从一个模板创建更多实例。Player
和Enemy
类具有相同的功能。只需使用带有不同参数的__init__
方法,就可以从一个类创建不同的实例。
import random
import time as t
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)
p = Player(hit_points=10, sides=6)
e = Player(hit_points=8, sides=6)
battle = 1
while battle != 0:
human = p.roll()
print("Your hit score: ",human)
enemy = e.roll()
print("Enemy hit score: ",enemy)
if human > enemy:
e.take_hit()
print("Your hit points remaining: ",p.hit_points)
print("Enemy points remaining: ", e.hit_points)
elif human < enemy:
p.take_hit()
print("Your hit points remaining: ",p.hit_points)
print("Enemy points remaining: ", e.hit_points)
t.sleep(2)
if e.hit_points == 0 or p.hit_points == 0:
battle = 0
https://stackoverflow.com/questions/51714705
复制相似问题