python-3.x - Python 3 - 面向对象编程 - 类和函数

标签 python-3.x

我已经学习 Python 3 几个月了,刚刚开始研究面向对象编程。我在 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类是模拟六面骰子,玩家和敌人用于游戏角色。之后,代码用于滚动随机数,最大的数字赢得该回合,直到玩家或敌人达到零分。

我不确定如何使用三个类之后的最后几行代码并从中创建一个类。

我需要能够在游戏中多次运行一场战斗,并存储玩家得分并在每次战斗后扣除分数。

我真的很喜欢并享受使用物体,并且希望变得更好,因此非常感谢任何有关这方面的帮助。

最佳答案

您可以重复使用类并从一个模板创建更多实例。 PlayerEnemy 类具有相同的功能。您只需使用带有不同参数的 __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

关于python-3.x - Python 3 - 面向对象编程 - 类和函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51714705/

相关文章:

python - 比较两个列表中的元素

python - 如何在 mac 上的 vscode 中自动加载 venv/bin/activate

python - 为什么Python中使用多线程没有输出?

python - 如何将整数转为列表

python - 在 Python 3 上将文件转换为 base64 字符串

python - "other"在 python 中是什么意思?

python-3.x - 绘图时的 Matplotlib 索引错误

python - 我如何从包含分页的网站中提取链接?(使用 Selenium )

python - discord.py 问题 : How to check the first user that joined in voice chat in discord

python - 联立线性方程组求解中的 NaN 和奇异矩阵误差