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

如何实现数值每秒逐步增长?Python中stamina每秒回复45点功能实现问询

实现方案

以下两种主流实现方式可根据你的项目场景选择:

场景1:非游戏项目/无需绑定主循环

适合普通Python应用,直接用线程定时器触发每秒回复,修改后的完整类逻辑如下:

import threading

class Player:
    def __init__(self):
        self.maximum_stamina = 1000 # 按需修改耐力最大值
        self.current_stamina = 0
        self._regen_enabled = False
        self._timer = None

    def stamina_regen(self, amount):
        # 原有逻辑可简化为边界判断+赋值
        self.current_stamina = min(self.current_stamina + amount, self.maximum_stamina)

    def _regen_cycle(self):
        if not self._regen_enabled:
            return
        self.stamina_regen(45)
        # 1秒后触发下一次回复
        self._timer = threading.Timer(1.0, self._regen_cycle)
        self._timer.start()

    def start_regen(self):
        """启动耐力回复"""
        if self._regen_enabled:
            return
        self._regen_enabled = True
        self._regen_cycle()

    def stop_regen(self):
        """停止耐力回复"""
        self._regen_enabled = False
        if self._timer:
            self._timer.cancel()

调用start_regen()即可开始每秒自动回复45点耐力,满值后自动卡在最大值,调用stop_regen()可随时终止回复流程。

注意:如果你的项目存在多线程同时修改current_stamina的情况,建议给stamina_regen方法加线程锁,避免出现数据竞争导致数值异常。

场景2:游戏项目/存在全局主循环

游戏项目不建议单独开线程做回复,直接在主循环里按时间差计算更稳定,避免线程同步问题:

import time

class Player:
    def __init__(self):
        self.maximum_stamina = 1000
        self.current_stamina = 0
        self._last_regen_timestamp = time.time()
        self.regen_per_second = 45

    def update(self):
        """每帧主循环调用该方法即可"""
        now = time.time()
        passed_seconds = now - self._last_regen_timestamp
        if passed_seconds >= 1:
            # 计算整秒数,掉帧也不会丢失回复量
            add_amount = self.regen_per_second * int(passed_seconds)
            self.current_stamina = min(self.current_stamina + add_amount, self.maximum_stamina)
            self._last_regen_timestamp = now

你只需要在游戏的每帧更新逻辑里调用实例的update()方法即可,掉帧、卡顿场景下也不会少算回复量,逻辑可控性更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 00:24:02