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

如何实现猜数字游戏的重新游玩功能并避免代码重复?

猜数字游戏代码复用解决方案

核心思路

把单局游戏的逻辑封装成函数,每次重玩直接调用函数即可,无需重复编写代码。同时用外层循环处理「是否重新游玩」的判断,实现持续游玩的功能。

优化后的完整代码

import random

score = 0  
games = 0 

def play_round():
    """执行单局猜数字游戏的函数"""
    global score, games
    games += 1
    # 获取有效猜测数字
    while True:
        try:
            guess = int(input("Pick a number from 1-10: "))
            if 1 <= guess <= 10:
                break
            else:
                print("Sorry that input was not valid")
        except ValueError:
            print("Please enter an integer between 1 and 10")
    
    rnum = random.randint(1, 10)
    # 判断结果并更新分数
    if guess == rnum:
        score += 1
        print(f"The number was {rnum}! You got a point!")
    else:
        print(f"The number was {rnum}. Sorry you didn't get a point.")
    print(f"Current Score: {score}")

# 初始化游戏
print("Welcome to pick a number!")
play_round()

# 处理重新游玩逻辑
while True:
    again = input("Would you like to play again?(Enter yes or no): ").lower().strip()
    if again == "yes":
        play_round()
    elif again == "no":
        print(f"You got {score} out of {games} games correct.")
        break
    else:
        print("Please enter 'yes' or 'no'")

关键改进点

  • 封装play_round()函数:将单局游戏的所有逻辑(有效输入获取、随机数生成、结果判断、分数更新)整合到函数中,调用一次即完成一局游戏,彻底实现代码复用。
  • 修复输入验证逻辑:原代码10 > guess < 1的判断逻辑错误,改为1 <= guess <=10,同时新增try-except处理非整数输入,确保输入有效性。
  • 外层循环控制重玩:用while True循环处理重玩请求,仅当用户输入no时退出游戏,输入无效时提示重新输入。
  • 使用f-string简化输出:让字符串拼接更简洁易读。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 08:47:26