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

如何实现猜对不增猜测计数器、猜错生成新随机选项?

解决猫咪喂食猜选程序的两个核心问题

先明确需求的核心逻辑:

  • 完全猜对时,计入完成的喂食次数(不消耗猜测机会,完成一次喂食任务)
  • 猜错时,错误次数累加,同时生成新的随机喂食组合,直到错误次数达到上限(4-5次随机)或完成所有喂食次数(4-6次)

以下是修改后的完整代码:

import random

collection = {
    "Wet": [1, 2, 3, 4],
    "Dry": [1, 2, 3, 4]
}

def userGuess(target_collection, target_brand):
    while True:
        collectionGuess = input('Wet or Dry? Make your guess: ')
        foodGuess = input('Guess the food brand: ')
        if (collectionGuess == 'Wet' or collectionGuess == 'Dry') and foodGuess.isdigit():
            break
        else:
            print("Enter valid guesses! ")
    
    # 返回是否完全猜对的结果
    if collectionGuess == target_collection and int(foodGuess) == target_brand:
        print('Your guess is correct')
        return True
    elif collectionGuess == target_collection:
        print('Need a bit more luck')
        return False
    else:
        print('Oops! Guess Mr.Poppins is not eating :(')
        return False

def foodSelect(collection):
    feedings_needed = random.choice([4, 5, 6]) 
    completed_feedings = 0
    max_wrong_guesses = random.choice([4, 5])
    wrong_guesses = 0

    while completed_feedings < feedings_needed and wrong_guesses < max_wrong_guesses:
        # 生成当前需要猜测的喂食组合
        current_collection = random.choice(['Wet', 'Dry'])
        current_brand = random.choice(collection[current_collection])
        
        # 调用猜测函数,获取结果
        guess_success = userGuess(current_collection, current_brand)
        if guess_success:
            # 猜对则完成一次喂食,计数累加
            completed_feedings += 1
            print(f"Completed {completed_feedings}/{feedings_needed} feedings!")
        else:
            # 猜错则错误次数累加,准备生成新组合
            wrong_guesses += 1
            print(f"Wrong guess! {wrong_guesses}/{max_wrong_guesses} remaining chances.")
    
    # 游戏结束提示
    if completed_feedings == feedings_needed:
        print("Great! All feedings are completed successfully!")
    else:
        print("Oh no! You've used all your wrong guesses. Game over.")

foodSelect(collection)

关键改动说明:

  1. userGuess返回猜测结果:将原函数的分数计算逻辑替换为布尔值返回,让调用方明确知道用户是否完全猜对,以此决定后续逻辑。
  2. 错误次数管控:新增max_wrong_guesses(随机4/5次)和wrong_guesses计数器,每次猜错就累加,达到上限直接结束游戏。
  3. 喂食计数逻辑修正:只有当用户完全猜对时,才增加completed_feedings,严格符合「猜对不消耗次数,完成一次喂食」的需求。
  4. 猜错自动生成新组合:每次猜错后,循环会重新进入下一轮,自动生成新的随机喂食组合,无需额外操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 17:12:43