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

Python中修改猜数字游戏随机数的技术实现问询

完整实现:优化随机数生成逻辑的猜数字游戏

Got it, let's fix up this number guessing game code and tweak the random number generation logic as you need. Here's a complete, polished version with explanations of the changes:

import random

def guess_number_game():
    # 可自定义的随机数范围,默认设置为1-100
    min_num = 1
    max_num = 100
    
    play_again = True
    while play_again:
        # 核心修改:每次新局都生成全新的随机数
        number = random.randint(min_num, max_num)
        points = 0
        print(f'Welcome to the game! You start with {points} point(s)')
        
        playing = True
        while playing:
            try:
                guess = int(input(f'Guess the number between {min_num} and {max_num}: '))
                # 验证输入是否在有效范围内
                if guess < min_num or guess > max_num:
                    print(f'Oops! Please enter a number between {min_num} and {max_num}.')
                    continue
                    
                points += 1  # 每猜一次加1分
                if guess > number:
                    print('Lower!')
                elif guess < number:
                    print('Higher!')
                else:
                    print(f'You got it, Good job!! You took {points} guesses and earned {points} points!')
                    playing = False
            except ValueError:
                print('Please enter a valid whole number!')
        
        # 处理重新游玩的逻辑,支持大小写输入
        while True:
            again_input = input('Do you want to play again? Type yes/no: ').strip().lower()
            if again_input == 'yes':
                play_again = True
                print('\n--- Starting a new game! ---')
                break
            elif again_input == 'no':
                play_again = False
                print('Thanks for playing! See you next time!')
                break
            else:
                print('Invalid input, please type "yes" or "no".')

# 启动游戏
guess_number_game()

关键修改:随机数生成逻辑优化

  • 每局刷新随机数:原代码只在游戏初始化时生成一次随机数,重新游玩会重复使用同一个数字。现在把随机数生成代码放到play_again循环内部,确保每局都有全新的目标数字。
  • 可配置范围:用min_num和max_num变量定义范围,你可以轻松修改(比如改成1-200),甚至可以扩展成让用户输入自定义范围。
  • 修正范围准确性:原代码使用random.randint(1, 101),会生成1到101的数字(包含101),但提示是"1到100",现在修正为符合提示的1-100区间。

其他补全与体验优化

  • 修正分数计算:原代码的分数累加位置错误,现在调整为每次猜测后都加1分,最后展示用户的猜测次数和得分。
  • 输入合法性校验:添加了非整数输入的异常处理,以及输入范围验证,避免无效输入导致游戏崩溃。
  • 健壮的重玩逻辑:支持大小写输入(比如"YES"或"Yes"都会被识别),对无效输入进行循环提示,直到用户输入正确选项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:38:51