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
               
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章