Bagels系列|python小程序随手记

来自《The Big Book of Small Python Projects》

python 复制代码
import random

NUM_DIGITS = 3  
MAX_GUESSES = 10  

def main():
    print('''Bagels, a deductive logic game.
I am thinking of a {}-digit number with no repeated digits.
Try to guess what it is. Here are some clues:
When I say:    That means:
  Pico         One digit is correct but in the wrong position.
  Fermi        One digit is correct and in the right position.
  Bagels       No digit is correct.

For example, if the secret number was 248 and your guess was 843, the
clues would be Fermi Pico.'''.format(NUM_DIGITS))

    while True:  # Main 主游戏循环.
        # 存储玩家需要猜测的秘密数字
        secretNum = getSecretNum()
        print('I have thought up a number.')
        print(' You have {} guesses to get it.'.format(MAX_GUESSES))

        numGuesses = 1
        while numGuesses <= MAX_GUESSES:
            guess = ''
            # 继续循环,直到用户输入一个有效的猜测
            while len(guess) != NUM_DIGITS or not guess.isdecimal():
                print('Guess #{}: '.format(numGuesses))
                guess = input('> ')

            clues = getClues(guess, secretNum)
            print(clues)
            numGuesses += 1

            if guess == secretNum:
                break  # 猜对跳出循环
            if numGuesses > MAX_GUESSES:
                print('You ran out of guesses.') 
                print('The answer was {}.'.format(secretNum))

        # 询问玩家是否想再玩一次。
        print('Do you want to play again? (yes or no)')
        if not input('> ').lower().startswith('y'):
            break
    print('Thanks for playing!')


def getSecretNum():
    """返回一个由NUM_DIGITS唯一随机数字组成的字符串。"""
    numbers = list('0123456789')  
    random.shuffle(numbers)  # 将它们随机排列

    # 获取秘密号码列表中的第一个NUM_DIGITS数字
    secretNum = ''
    for i in range(NUM_DIGITS):
        secretNum += str(numbers[i])
    return secretNum


def getClues(guess, secretNum):
    """返回带有pico, fermi, bagels线索的字符串。"""
    if guess == secretNum:
        return 'You got it!'

    clues = []

    for i in range(len(guess)):
        if guess[i] == secretNum[i]:
            # 正确的数字在正确的位置,提示Fermi。
            clues.append('Fermi')
        elif guess[i] in secretNum:
            # 正确的数字在错误的位置,提示Pico。
            clues.append('Pico')
    if len(clues) == 0:
        return 'Bagels'  # 没有正确的数字
    else:
        # 将线索按字母顺序排列,这样它们原来的顺序就不会泄露信息。
        clues.sort()
        # 从字符串线索列表中制作一个字符串。
        return ' '.join(clues)

if __name__ == '__main__':
    main()

运行效果:

Bagels系列|python小程序随手记

相关推荐
像风一样的男人@6 分钟前
python --fastapi推流AI推理
人工智能·python·fastapi
2601_9563198822 分钟前
最新量化开发卡住,先查规则和流程是否完整
人工智能·python
小小代码狗1 小时前
SQLi-Labs 基础注入实战教程(Less-1 ~ Less-5and Less-9)
服务器·python·php
nanawinona1 小时前
2026年下半年量化学习,不同基础要查不同缺口
人工智能·python
CTA量化套保2 小时前
最新量化表达入门,从概念规则到简单实现
人工智能·python
小码哥0682 小时前
从三甲综合医院到连锁诊所:医院管理小程序的场景化突围逻辑(陪诊系统-陪诊APP-陪诊小程序)
小程序·医院管理系统·陪诊小程序·陪诊系统·陪诊app
吃饱了得干活2 小时前
别再手动解析 LLM 输出了!LangChain 四种结构化输出方案对比
后端·python·langchain
ikun_文2 小时前
Python进阶—函数编程
python·pycharm
MC皮蛋侠客2 小时前
uv 系列(三):依赖、锁文件与环境同步——可重复构建的核心
python·uv
量化吞吐机2 小时前
2026年交易想法转Python,中间先补规则转译
人工智能·python