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

Python游戏中守护线程无法提升每秒自动冰淇淋产量(aips)的问题

冰淇淋自动产量线程修复方案

你的代码存在几个关键问题导致自动产量线程不生效,以下是修复点和完整代码:

核心问题与修改

  • 线程创建方式错误:创建线程时,target=aips()会直接执行aips函数并阻塞主线程,正确写法是传入函数引用target=aips,让线程独立执行该函数。
  • sleep调用错误:代码中导入的是sleep函数而非time模块,因此aips函数里应使用sleep(1)代替time.sleep(1),否则会触发NameError导致线程崩溃。
  • 线程启动位置错误:原代码将线程启动放在主循环之后,主循环不结束就永远不会执行到启动代码,需将线程启动代码移到主循环之前。
  • stop命令逻辑错误:playing == False是比较操作,无法修改变量值,应改为playing = False来终止主循环。

修改后的完整代码

from threading import Thread
from time import sleep

icecream = 0
dollars = 0
machineLvl = 1
ips = 1
playing = True

def aips():
    while playing:  # 用playing控制线程退出,避免无限循环
        global ips, icecream 
        icecream += ips
        sleep(1)

def make_icecream(lvl, icecream):
    icecream += lvl
    print(f' + {str(lvl)} ')
    return icecream

def sell_icecream(icecream, coins):
    coins += icecream
    icecream = 0
    return [icecream, coins]

def stats(coins, icecream, lvl):
    print(f'''    dollars: {coins}
    ice cream: {icecream}
    Level: {lvl}''')

# 启动守护线程
t1 = Thread(target=aips, daemon=True)
t1.start()

while playing:
    command = input(">  ")
    if command == 'sell':
        icecream, dollars = sell_icecream(icecream, dollars)
    elif command == 'make':
        icecream = make_icecream(machineLvl, icecream)
    elif command == 'stats':
        stats(dollars, icecream, machineLvl)
    elif command == 'stop':
        playing = False
    else: 
        print("Error, could not read command.")

print("Bye!")

额外优化:将aips函数的while True改为while playing,这样当主循环终止时,线程也会自动退出,避免线程残留。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 06:15:07