You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python文字roguelike RPG开发:杀敌计数每次重置为0问题求助

问题修复方案

核心问题原因

  • 原代码中杀敌计数count是battle函数的局部变量,每次触发战斗都会被初始化为0,且战斗循环内每次循环也会执行count = 0重置数值,完全无法实现累计
  • 计数没有和玩家对象绑定,跨战斗场景无法保留数值
  • 额外存在两个隐性bug:升级逻辑中self.hp == self.max_hp是判断语句,没有实现升级满血的效果;主逻辑的BOSS生成判断只在程序启动时执行一次,后续永远不会触发BOSS战斗

修改方案

参考b_count的全局累计逻辑,将杀敌计数作为玩家固有属性绑定到Player类中,同步修复上述隐性bug,修改后完整代码如下:

import random
import math
import time


# 定义基础角色类和属性
class Base:
    def __init__(self, name, lvl, max_hp, hp, strength, defense, wpn):
        self.name = name
        self.lvl = lvl
        self.max_hp = max_hp
        self.hp = hp
        self.wpn = wpn
        self.strength = strength
        self.defense = defense


# 玩家类继承基础类,新增经验、升级所需经验、杀敌计数属性
class Player(Base):
    def __init__(self, exp, lvlUp, **kwargs):
        super().__init__(**kwargs)
        self.exp = exp
        self.lvlUp = lvlUp
        self.kill_count = 0  # 新增累计杀敌计数属性

    # 升级逻辑
    def LevelUp(self):
        while self.exp >= self.lvlUp:
            self.lvl += 1
            self.exp -= self.lvlUp  # 修复原逻辑清0全部经验的问题,只扣掉升级所需经验
            self.lvlUp *= 1.125
            hp_gain = round(self.max_hp * 0.125)
            str_gain = round(self.strength * 0.25)
            dfn_gain = round(self.defense * 0.25)
            self.max_hp = round(self.max_hp * 1.125)
            self.hp = self.max_hp  # 修复原逻辑判等错误,实现升级满血
            self.strength += str_gain
            self.defense += dfn_gain
            print("你升级了!获得{}点生命值、{}点力量、{}点防御。\n你感觉全身充满了力量".format(hp_gain, str_gain, dfn_gain))
        else:
            pass

    # 治疗逻辑
    def heal(self):
        gain = random.randrange(4 , math.ceil(self.max_hp * 0.75), 2)
        if self.hp + gain >= self.max_hp:
            max_gain = self.max_hp - self.hp
            self.hp = self.max_hp
            return max_gain
        else:
            self.hp += gain
            return gain

    # 攻击逻辑
    def attack(self, other):
        # 基于力量和武器计算伤害
        dmg = math.floor(random.uniform(self.strength * self.wpn, (self.strength * self.wpn) * 2) - other.defense)
        dmg = max(dmg, 0) # 避免出现负伤害
        time.sleep(0.2)
        print("你造成了{}点伤害".format(dmg))
        other.hp -= dmg
        if other.hp > 0:
            print("{}剩余{}点生命值".format(other.name, other.hp))
        # 敌人死亡时加经验、回血、加杀敌数
        else:
            new_exp = random.randrange(2, 16, 2)
            heal = self.heal()
            self.kill_count += 1 # 杀敌计数自增
            print(f"你击杀了{other.name}。你恢复了{heal}点生命值,获得{new_exp}点经验")
            self.exp += new_exp
            self.LevelUp()
            print("下一级{}: [{}/{}]".format(self.lvl + 1, self.exp, round(self.lvlUp)))


# 小怪类
class Mob(Base):
    def __init__(self, *args):
        super().__init__(*args)

    # 小怪攻击逻辑
    def attack(self, other):
        dmg = math.floor(random.uniform(self.strength * self.wpn, (self.strength * self.wpn) * 2) - other.defense)
        if dmg <= 0:
            dmg = 0
            print("{}造成了{}点伤害".format(self.name, dmg))

        elif dmg >= other.hp:
            print("{}造成了{}点伤害,你死了".format(self.name, dmg))
            other.hp -= dmg

        else:
            other.hp -= dmg
            print("{}造成了{}点伤害".format(self.name, dmg))
            print("你剩余{}点生命值".format(other.hp))

# BOSS类(开发中)
class Boss(Base):
    def __init__(self, *args):
        super().__init__(*args)
        

# 设置玩家名称
hero_name = input("输入你的名字...")

# 初始化玩家基础属性
hero = Player(exp=0, lvlUp=32, name=hero_name, lvl=1, max_hp=64, hp=64, strength=8, defense=4, wpn=1.125)

cmdlist = [
    ["a", "attack"],
    ["h", "heal"],
    ["r", "run"]]

# 小怪列表
mobs = [
    Mob("哥布林", 1, 16, 16, 4, 2, 1),
    Mob("狼", 1, 24, 24, 6, 2, 1),
    Mob("小恶魔", 1, 16, 16, 4, 2, 1.125),
    Mob("牛头人", 1, 32, 32, 4, 4, 1.25),
    Mob("强盗", 1, 24, 24, 8, 4, 1.125),
    Mob("魅魔", 1, 24, 24, 4, 4, 1.25),
    Mob("石像鬼", 1, 32, 32, 6, 2, 1.25),
    Mob("熊", 1, 48, 48, 6, 4, 1.375),
    Mob("奇美拉", 1, 48, 48, 6, 4, 1.375),
    Mob("亡灵法师", 1, 32, 32, 6, 4, 1.5)]

# BOSS列表
bosses = [
    Boss("牛头人首领", 1, 64, 64, 8, 8, 1.25),
    Boss("强盗头子", 1, 48, 48, 16, 8, 1.125),
    Boss("巨熊", 1, 96, 96, 12, 8, 1.375),
    Boss("奇美拉领主", 1, 96, 96, 12, 8, 1.375),
    Boss("巫妖", 1, 64, 64, 12, 8, 1.5)]


# 战斗逻辑
def battle(player, enemy):
    print("{}向你冲了过来!".format(enemy.name))
    # 战斗循环
    while player.hp > 0 and enemy.hp > 0:
        print("[{}] 杀敌数: {}".format(player.name, player.kill_count))
        print("[生命值: {}] [下一级{}: [{}/{}]]".format(player.hp, player.lvl + 1, player.exp, round(player.lvlUp)))
        command = input("(A)攻击, (H)治疗 或者 (R)逃跑? \n")
        if command.lower() in cmdlist[0]:
            player.attack(enemy)
            print("---------------------")
            time.sleep(.5)
            if enemy.hp <= 0:
                return
            enemy.attack(player)
            print("---------------------")
            time.sleep(.2)
        elif command.lower() in cmdlist[1]:
            heal = player.heal()
            print("你恢复了{}点生命值".format(heal))
            continue
        elif command.lower() in cmdlist[2]:
            chance = random.randint(1, 20)
            if chance in range(11, 21):
                print("你成功逃脱,没有受伤")
                break
            elif chance in range(1, 11):
                dmg = round(random.uniform((enemy.strength * enemy.wpn / 4), (enemy.strength * enemy.wpn) / 2))
                player.hp -= dmg
                print("你成功逃脱,但受了点轻伤。[-{}点生命值] \n你剩余{}点生命值".format(dmg, hero.hp))
                time.sleep(0.5)
                break

if __name__ == "__main__":
    b_count = 0
    while hero.hp > 0:
        b_count +=1
        # 修复原逻辑BOSS生成判断只执行一次的问题
        if b_count <5 or b_count %3 !=0:
            battle(hero, random.choice(mobs))
        else:
            print("这个家伙看起来不好惹")
            battle(hero, random.choice(bosses))

内容的提问来源于stack exchange,提问作者Justice Brinston

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 04:24:03