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

Python实现秒表到达8的倍数时变量自增(pygame怪物调速问题)

问题原因

你的代码bug根源是range()的结束参数为开区间:当time_elapsed = 8时,此时x的值刚好等于8,list(range(8, x, 8))实际是range(8,8,8),生成的是空列表,所以判断条件永远不成立,速度不会增加。
而且当前逻辑冗余度很高,不需要额外维护x变量、也不需要生成8的倍数列表来判断,直接判断已运行时间是否为8的正整数倍即可。

线程版本修改方案

直接替换对应逻辑即可:

from time import time, sleep
import threading

monsters_speed = 0.3

def time_speed():
    global monsters_speed
    start_time = time()
    last_trigger = 0 # 记录上次提速的时间点,避免重复触发
    while True:
        time_elapsed = round(time() - start_time)
        # 当时间到8的倍数,且还没触发过本次提速
        if time_elapsed > 0 and time_elapsed % 8 == 0 and time_elapsed != last_trigger:
            monsters_speed += 1
            last_trigger = time_elapsed
        print(monsters_speed)
        print(time_elapsed)
        sleep(1)


time_speed_thread = threading.Thread(target=time_speed, daemon=True) # 设为守护线程,主程序退出时自动销毁
time_speed_thread.start()
更适合Pygame的无线程方案

Pygame开发不需要额外开线程做计时,直接用内置的ticks计时即可,放在主循环里运行不会阻塞,还能避免多线程全局变量读写的竞态问题:

import pygame

pygame.init()
# 其他初始化代码...
monsters_speed = 0.3
last_speed_up = pygame.time.get_ticks() # 记录上次提速的毫秒数

# 游戏主循环
running = True
while running:
    current_ticks = pygame.time.get_ticks()
    # 每8000毫秒=8秒提速一次
    if current_ticks - last_speed_up >= 8000:
        monsters_speed += 1
        last_speed_up = current_ticks # 更新上次提速时间
    
    # 其他游戏逻辑:事件处理、怪物移动、渲染等...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 13:06:04