《抖音弹幕游戏开发专栏》是优雅草建立的专栏,由优雅草资深开发工程师云桂提供实战教学配对发布有对应的视频教程,以下内容为技术文稿,卓伊凡辅助。
抖音弹幕游戏开发之第15集:添加配置文件·优雅草云桧·卓伊凡
第15集:添加配置文件
为什么需要配置文件
- 不同游戏需要不同按键
- 不同直播风格需要不同冷却时间
- 快速调整触发规则
- 分享给不懂代码的朋友使用
创建config.json
{
"websocket_url": "ws://localhost:12011",
"cooldown": 2,
"triggers": {
"跳": "space",
"jump": "space",
"前进": "w",
"forward": "w",
"后退": "s",
"左": "a",
"右": "d"
},
"gifts": {
"玫瑰": "spin",
"爱心": "jump"
}
}
读取配置文件
def load_config():
"""加载配置文件"""
try:
with open('config.json', 'r', encoding='utf-8') as f:
return json.load(f)
except FileNotFoundError:
print("⚠️ 配置文件不存在,使用默认配置")
return {"websocket_url": "ws://localhost:12011", "cooldown": 2}
except json.JSONDecodeError as e:
print(f"⚠️ 配置文件格式错误: {e}")
return {"websocket_url": "ws://localhost:12011", "cooldown": 2}
使用配置
config = load_config()
WEBSOCKET_URL = config['websocket_url']
COOLDOWN = config['cooldown']
使用配置的触发规则
triggers = config.get('triggers', {})
for keyword, key in triggers.items():
if keyword in content.lower():
pyautogui.press(key)
print(f"✓ 触发: {keyword} -> {key}")
break
JSON格式注意事项
|------|---------|
| 注意点 | 说明 |
| 字符串 | 必须用双引号 |
| 最后一项 | 不能有逗号 |
| 编码 | 使用UTF-8 |
| 修改后 | 需要重启程序 |
本集总结
- ✅ 理解配置文件的必要性
- ✅ 创建JSON格式的配置文件
- ✅ 实现配置文件的读取和验证
- ✅ 使用配置文件管理触发规则
下一集:异常处理与稳定性