Bagels系列|python小程序随手记

来自《The Big Book of Small Python Projects》

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Turbo正则

如果对您有用请我喝杯咖啡吧~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值