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

Python游戏开发:如何从字典读取时长传入time.sleep()函数?

嘿,这个需求实现起来很简单,我来一步步给你说明:

首先,你需要确保已经导入了Python的time模块,因为time.sleep()依赖它才能生效。

基础实现方式

你已经有了存储制作时间的字典TimeToCraft,要获取某个物品的等待秒数,直接通过键名访问字典即可,然后把这个值传给time.sleep()就完成了核心逻辑。

举个完整的代码例子:

import time

# 你的制作时间字典
TimeToCraft = { 'missile' : 10, 'otherThing' : 100, }

# 假设用户当前要制作的物品是'missile'
item_to_craft = 'missile'

# 从字典中取出对应的等待时间
craft_time = TimeToCraft[item_to_craft]

# 执行等待逻辑
print(f"开始制作{item_to_craft},需要等待{craft_time}秒...")
time.sleep(craft_time)
print(f"{item_to_craft}制作完成!")

处理物品不存在的异常情况

如果游戏中用户可能输入字典里没有的物品名称,直接用TimeToCraft[item_to_craft]会抛出KeyError导致程序崩溃。这时候可以用字典的get()方法来规避问题,还能设置默认等待时间:

item_to_craft = 'unknown_item'
# 如果物品不在字典中,默认等待5秒(你可以改成自己需要的数值)
craft_time = TimeToCraft.get(item_to_craft, 5)

print(f"开始制作{item_to_craft},需要等待{craft_time}秒...")
time.sleep(craft_time)
print(f"{item_to_craft}制作完成!")

更贴合游戏场景的封装写法

如果是游戏中用户选择物品后触发制作流程,你可以把逻辑封装成函数,让代码更整洁、复用性更强:

import time

TimeToCraft = { 'missile' : 10, 'otherThing' : 100, }

def craft_item(item_name):
    # 获取制作时间,默认5秒
    craft_time = TimeToCraft.get(item_name, 5)
    print(f"正在制作{item_name},请等待{craft_time}秒...")
    time.sleep(craft_time)
    print(f"{item_name}制作完成!")

# 调用函数制作指定物品
craft_item('otherThing')

这样不管用户要制作什么物品,只要调用这个函数传入物品名称就行,非常方便~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:55:43