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

Python投资游戏开发问题:cash变量未更新及连续游玩需求实现

搞定你的投资游戏问题:Cash不更新 + 连续游玩功能

嘿,我来帮你解决这两个问题!先拆解cash始终停在1000的bug,再给你搞定连续游玩的功能。

1. Cash为啥一直是1000?

从你贴的代码片段来看,核心问题有两个:

  • 你根本没把投资操作和cash变量关联起来:你定义了涨跌比例,但既没让用户输入投资金额,也没根据涨跌结果去更新cash的值——cash初始是1000,之后没被重新赋值,当然一直不变啦!
  • 你的涨跌比例计算逻辑错误:percentdown = percentrand/100 -1 会得到负数(比如percentrand是50的话,就是0.5-1=-0.9),就算你后来想更新cash,结果也会完全不对。

修复cash更新的核心步骤:

首先修正涨跌比例的计算:

percentrand = random.randint(1,99)
percentup = 1 + (percentrand / 100)  # 涨percentrand%,比如涨10%就是1.1倍
percentdown = 1 - (percentrand / 100)  # 跌percentrand%,比如跌10%就是0.9倍

然后添加用户投资输入和cash更新逻辑:

# 先让用户输入投资金额,还要做合法性检查(不能超当前现金,不能是负数/非数字)
while True:
    try:
        investment = int(input("How much do you want to invest? "))
        if 0 < investment <= cash:
            break
        else:
            print(f"Invalid amount! It has to be between 1 and {cash}$")
    except ValueError:
        print("Please enter a valid number!")

# 根据随机涨跌结果更新cash
if randomhighlow == "h":
    cash = cash - investment + (investment * percentup)
    print(f"Nice! Your cash is now {cash:.2f}$")
else:
    cash = cash - investment + (investment * percentdown)
    print(f"Oops! Your cash is now {cash:.2f}$")

2. 实现连续游玩功能

要让玩家持续操作,用while循环把整个游戏流程包起来就行,每次循环结束后问玩家要不要继续,再加个“破产即结束”的规则更合理。

完整的可运行代码示例:

import random

print("=== INVEST GAME ===")
cash = 1000
play_again = "y"

while play_again.lower() == "y":
    print(f"\nYou have {cash:.2f}$ on you now.")
    
    # 获取合法的投资金额
    while True:
        try:
            investment = int(input("How much do you want to invest? "))
            if 0 < investment <= cash:
                break
            else:
                print(f"Please enter an amount between 1 and {cash:.2f}$")
        except ValueError:
            print("Please enter a valid number!")
    
    # 生成随机涨跌结果和比例
    highlow = ["h", "l"]
    percentrand = random.randint(1, 99)
    percentup = 1 + (percentrand / 100)
    percentdown = 1 - (percentrand / 100)
    randomhighlow = random.choice(highlow)
    
    # 更新现金
    if randomhighlow == "h":
        cash = cash - investment + (investment * percentup)
        print(f"🎉 Your investment went up by {percentrand}%!")
    else:
        cash = cash - investment + (investment * percentdown)
        print(f"😢 Your investment went down by {percentrand}%!")
    
    # 检查是否破产
    if cash <= 0:
        print("\nYou're broke! Game over.")
        break
    
    # 询问是否继续
    play_again = input("\nDo you want to play again? (y/n): ")

print(f"\nThanks for playing! You ended with {cash:.2f}$")

最后划个重点

  • Cash更新的关键:必须对cash变量重新赋值,不能只计算不赋值,同时要修正涨跌比例的计算逻辑。
  • 连续游玩的核心:用while循环包裹游戏流程,每次循环后询问玩家意愿,再加个破产终止的规则更完善。
  • 输入检查很重要:避免玩家输入非数字或者超出范围的金额,防止游戏崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:11:28