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

Pygame点击增加金币异常:数值拼接而非算术累加如何解决

问题根因
  • 你调用文件对象的read()方法读取到的cps和totalcoin都是字符串类型,Python中字符串使用+=运算符会执行拼接逻辑,而非算术累加,这是你看到数值拼接现象的核心原因。
  • 你原代码中直接用MOUSEBUTTONDOWN常量未加pygame.前缀,实际运行会报未定义错误,也需要同步修正。
修复方案
  1. 读取文件内容后直接转换为整数类型,可添加容错逻辑避免文件内容为空/非合法数字时崩溃
  2. 累加后如果需要持久化存储金币数据,记得将最新数值写回对应文件,避免重启游戏后数据丢失
  3. 补全pygame常量的前缀,修正事件判断逻辑
修正后的参考代码
import pygame
pygame.init()
clock = pygame.time.Clock()
# 读取点击单次增加金币数,默认值1
with open("clickpersecond.txt", "r+") as cpsecond:
    cps_content = cpsecond.read().strip()
    cps = int(cps_content) if cps_content.isdigit() else 1
# 读取总金币数,默认值0
with open("totalcoin.txt", "r+") as cointotal:
    coin_content = cointotal.read().strip()
    totalcoin = int(coin_content) if coin_content.isdigit() else 0

# 这里补全你创建窗口等初始化逻辑
screen = pygame.display.set_mode((400, 300))

while True: # main game loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            # 退出前将最新金币数写回文件
            with open("totalcoin.txt", "w") as f:
                f.write(str(totalcoin))
            pygame.quit()
            exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            # 整数累加
            totalcoin += cps
            print(f"Your current coin is {totalcoin}", end="\r")

    pygame.display.flip()
    clock.tick(30)

如果你的游戏不需要在重启后保留金币数据,也可以不用读取/写入文件,直接初始化totalcoin = 0、cps = 1即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 06:45:04