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

如何在Python猜动物游戏中固定随机选中的动物以生成提示?

Python猜动物游戏提示异常问题修复

问题根源

  1. 初始hint仅在游戏启动时生成一次,后续请求提示时没有从当前选中的目标动物中重新提取未使用的字符
  2. 生命值扣除逻辑错误:lives = -1会直接把生命值设为-1,而非正确扣除1点
  3. 提示生成逻辑冗余:循环遍历单个hint字符完全没必要,且未处理当前提示已被使用时的重新获取逻辑

修改后的完整代码

import random

print("Do you think you know all the animals😺😼?! if yes then this game is for \033[1myou!\033[0m")
print("\033[7mLet the game begin! \033[0m")
animals = ("ant baboon badger bat bear beaver camel cat clam cobra cougar").split()
you_chose = []
# 选中目标动物,整局游戏固定不变
animal = random.choice(animals)
used_hints = []
lives = 6
hint_count = 6

while True:
    print()
    letter = input("please type a letter to begin:  ").lower()
    
    if letter in you_chose:
        print("\033[31m Error duplicate letter\033[0m")
        continue
    you_chose.append(letter)
    
    if letter in animal:
        print("Congrats, you found a letter! keep going.")
    else:
        print("Not in there keep trying")
        # 修复生命值扣除逻辑
        lives -= 1
        want_hint = input("Would you like a hint?(yes / No)\n: ").lower()
        if want_hint == "yes":
            # 筛选当前动物中未被猜过、未被用作提示的字符
            available_hints = [char for char in animal if char not in you_chose and char not in used_hints]
            if available_hints:
                hint = random.choice(available_hints)
                used_hints.append(hint)
                print(f"Hint: {hint}")
            else:
                print("No more hints available!")
    
    # 打印当前猜测进度
    print("\nCurrent progress:")
    for char in animal:
        if char in you_chose:
            print(char, end="")
        else:
            print("*", end="")
    print()
    
    # 补充游戏结束判断逻辑
    if all(char in you_chose for char in animal):
        print("\n🎉 You win!")
        break
    if lives <= 0:
        print(f"\n💀 Game over! The animal was: {animal}")
        break

关键修改点说明

  • 固定目标动物:animal = random.choice(animals)放在循环外,确保整局游戏只选中一个动物,不会中途切换
  • 动态生成提示:每次用户请求提示时,从当前动物的剩余未猜字符中随机选一个,保证提示始终对应目标动物
  • 修复生命值逻辑:将lives = -1改为lives -= 1,正确实现生命值递减
  • 完善游戏流程:补充胜利、失败的终止条件,避免无限循环
  • 优化提示反馈:当没有可用提示时,明确告知用户

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 14:35:19