Python游戏编程(六)Bagels

Bagels是可以和朋友一起玩的一个推理游戏。你的朋友想到一个随机的、没有重复的3位数字,你尝试去猜测它是什么。每次猜测之后,朋友就会给出3中类型的线索:

  • Bagels——你猜测的3个数都不在神秘数字中;
  • Pico——你猜测的是神秘数字中的一个数,但是位置不对;
  • Fermi——你猜测的是正确位置上的一个正确的数字;

计算机可以返回多条线索,这些线索按照字母顺序排序。如果神秘数字是456,而玩家猜测的是546,那么线索就是“fermi pico pico”。6提供的线索是“fermi”,5和4提供的线索是“pico pico”。

主要内容:

  • random.shuffl()函数;
  • 复合赋值操作符+=、-=、*=、/=;
  • 列表方法sort()和join();
  • 字符串插值;
  • 转换说明符%s;
  • 嵌套循环;

流程图

在这里插入图片描述

用random.shuffle()函数改变列表项的顺序

random.shuffle()函数并不返回一个值,而是把传递给它的列表”就地“修改。

>>> import random
>>> spam = list(range(10))
>>> print(spam)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> random.shuffle(spam)
>>> print(spam)
[0, 6, 7, 5, 8, 1, 4, 2, 3, 9]
>>> random.shuffle(spam)
>>> print(spam)
[2, 7, 0, 5, 9, 6, 4, 3, 1, 8]

复合赋值操作符

如果想要把一个值增加或者连接到一个变量中,应该使用如下代码:

>>> spam = 42
>>> spam = spam + 10
>>> spam
52
>>> eggs = 'Hello'
>>> eggs = eggs + 'world'
>>> eggs
'Helloworld'

复合赋值操作符是一种快捷方式,它使得我们不必再重复地输入了变量名称。

>>> spam = 42
>>> spam += 10
>>> spam
52
>>> eggs = 'Hello'
>>> eggs += ' World'
>>> eggs
'Hello World'

还可以

>>> spam = 40
>>> spam *= 3
>>> spam
120
>>> spam /= 10
>>> spam
12.0

变量命名

这里使用变量NUM_DIGITS来表示答案中的数字位数,而不是直接使用整数3。对于玩家所能够猜测的次数,也是使用变量MAX_GUESS而不是整数10,这样便于修改。

import random

NUM_DIGITS = 3  #答案中的数字位数
MAX_GUESS = 10  #玩家所能够猜测的次数

源代码

import random

NUM_DIGITS = 3  #答案中的数字位数
MAX_GUESS = 10  #玩家所能够猜测的次数

#生成神秘数字
def getSecretNum():
    #Return a string of unique random digits that is NUM_DIGITS long.
    numbers = list(range(10))
    random.shuffle(numbers)
    secretNum = ' '
    for i in range(NUM_DIGITS):
        secretNum += str(numbers[i])
    return secretNum

#计算要给出的结果 
def getClues(guess, secretNum):
    #Returns a string with the Pico, Fermi, & Bagels clues to the user.
    if guess == secretNum:
        return 'You got it!'                          
    
    clues = [ ]
    for i in range(len(guess)):
        if guess[i] == secretNum[i]:
            clues.append('Fermi')
        elif guess[i] in secretNum:
            clues.append('Pico')
    if len(clues) == 0:
        return 'Bagels'
    
    clues.sort()
    return ' '.join(clues)


#检查字符串中是否只包含数字 
def isOnlyDigits(num):
    #Return True if num is a string of only digits. Otherwise, returns False
    if num == ' ':
        return False
    
    for i in num:
        if i not in '0 1 2 3 4 5 6 7 8 9'.split():
            return False
        
    return True


print('I an thinking of a %s-digits number. Try to guess what it is,'%(NUM_DIGITS))
print('The clues I give are...')
print('When I say:        That meas:')
print('  Bagels           None of the digit is correct.')
print('  Pico             One digit is correct but in the wrong position.')
print('  Fermi            One digit is correct and in the right position.')

while True:
    secretNum = getSecretNum()
    print('I have thought up a number, You have %s guesses to get it.'%(MAX_GUESS))
    
    guessesTaken = 1
    while guessesTaken <= MAX_GUESS:
        guess = ' '
        while len(guess) != NUM_DIGITS or not isOnlyDigits(guess):
            
            print('Guess #%s:    '% (guessesTaken))
            guess = input()
            
        print(getClues(guess, secretNum))
        guessesTaken += 1
        
        if guess == secretNum:
            break
        if guessesTaken > MAX_GUESS:
            print('You ran out of guesses. The answer was %s.' %(secretNum))
            
            
    print('Do you want to play again ?(yes or no)')
    if not input().lower().startswith('y'):
        break
               
发布了9 篇原创文章 · 获赞 1 · 访问量 414

猜你喜欢

转载自blog.csdn.net/weixin_45755966/article/details/104065044