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小程序随手记

相关推荐
祝余Eleanor7 小时前
Day 41 训练和测试的规范写法
python·深度学习·机器学习
百锦再7 小时前
与AI沟通的正确方式——AI提示词:原理、策略与精通之道
android·java·开发语言·人工智能·python·ui·uni-app
2501_915909067 小时前
iOS 项目中常被忽略的 Bundle ID 管理问题
android·ios·小程序·https·uni-app·iphone·webview
电化学仪器白超7 小时前
《可编程固定阻值电子负载的制作与自动化标定技术》
python·单片机·嵌入式硬件·自动化
free-elcmacom7 小时前
机器学习高阶教程<2>优化理论实战:BERT用AdamW、强化学习爱SGD
人工智能·python·机器学习·bert·强化学习·大模型训练的优化器选择逻辑
2501_915921437 小时前
iOS App 测试的工程化实践,多工具协同的一些尝试
android·ios·小程序·https·uni-app·iphone·webview
IT三重门7 小时前
Scikit-Learn进行数据预处理,从基础到实战全解析
python
ULTRA??7 小时前
Informed RRT*算法,并包含圆形障碍物环境
人工智能·python·算法
黑客思维者7 小时前
XGW-9000 网关 DDR4/LPDDR4 内存子系统信号完整性仿真细化设计
开发语言·python·嵌入式硬件·ddr4·信号仿真
Felven7 小时前
华为昇腾310P模型转换失败问题解决
linux·python·模型训练·昇腾·310p