- Python編程快速上手2
- (美)阿爾·斯維加特
- 951字
- 2022-10-26 17:00:13
工作原理
切記,這個程序使用的不是整數值,而是包含數字的字符串值。例如,'426'與426是不同的值。之所以這么做,是因為我們需要與秘密數字進行字符串比較,而不是進行數學運算。記住,0可以作為前導數字,在這種情況下,字符串'026'與'26'不同,但整數026與26相同。
1. """
2. Pico Fermi Bagels猜數字游戲,作者:Al Sweigart al@inventwithpython.com
3. 一個邏輯推理游戲,你必須根據線索猜數字
4. 本游戲的一個版本在《Python游戲編程快速上手》中有相應介紹
5. 標簽:簡短,游戲,謎題
6. """
7.
8. import random
9.
10. NUM_DIGITS = 3 # (!) 請試著將3設置為1或10
11. MAX_GUESSES = 10 # (!) 請試著將10設置為1或100
12.
13.
14. def main():
15. print('''Bagels, a deductive logic game.
16. By Al Sweigart al@inventwithpython.com
17.
18. I am thinking of a {}-digit number with no repeated digits.
19. Try to guess what it is. Here are some clues:
20. When I say: That means:
21. Pico One digit is correct but in the wrong position.
22. Fermi One digit is correct and in the right position.
23. Bagels No digit is correct.
24.
25. For example, if the secret number was 248 and your guess was 843, the
26. clues would be Fermi Pico.'''.format(NUM_DIGITS))
27.
28. while True: # 主循環
29. # secretNum存儲了玩家所要猜測的秘密數字
30. secretNum = getSecretNum()
31. print('I have thought up a number.')
32. print(' You have {} guesses to get it.'.format(MAX_GUESSES))
33.
34. numGuesses = 1
35. while numGuesses <= MAX_GUESSES:
36. guess = ''
37. # 保持循環,直到玩家輸入正確的猜測數字
38. while len(guess) != NUM_DIGITS or not guess.isdecimal():
39. print('Guess #{}: '.format(numGuesses))
40. guess = input('> ')
41.
42. clues = getClues(guess, secretNum)
43. print(clues)
44. numGuesses += 1
45.
46. if guess == secretNum:
47. break # 玩家猜對了數字,結束當前循環
48. if numGuesses > MAX_GUESSES:
49. print('You ran out of guesses.')
50. print('The answer was {}.'.format(secretNum))
51.
52. # 詢問玩家是否想再玩一次
53. print('Do you want to play again? (yes or no)')
54. if not input('> ').lower().startswith('y'):
55. break
56. print('Thanks for playing!')
57.
58.
59. def getSecretNum():
60. """返回唯一一個長度為NUM_DIGITS且由隨機數字組成的字符串"""
61. numbers = list('0123456789') # 創建數字0~9的列表
62. random.shuffle(numbers) # 將它們隨機排列
63.
64. # 獲取秘密數字列表中的前NUM_DIGITS位數字
65. secretNum = ''
66. for i in range(NUM_DIGITS):
67. secretNum += str(numbers[i])
68. return secretNum
69.
70.
71. def getClues(guess, secretNum):
72. """返回一個由Pico、Fermi、Bagels組成的字符串,用于猜測一個三位數"""
73. if guess == secretNum:
74. return 'You got it!'
75.
76. clues = []
77.
78. for i in range(len(guess)):
79. if guess[i] == secretNum[i]:
80. # 正確的數字位于正確的位置
81. clues.append('Fermi')
82. elif guess[i] in secretNum:
83. # 正確的數字不在正確的位置
84. clues.append('Pico')
85. if len(clues) == 0:
86. return 'Bagels' # 沒有正確的數字
87. else:
88. # 將clues列表按字母順序排序,使其不會泄露數字的信息
89. clues.sort()
90. # 返回一個由clues列表中所有元素組成的字符串
91. return ' '.join(clues)
92.
93.
94. # 程序運行入口(如果不是作為模塊導入的話)
95. if __name__ == '__main__':
96. main()
輸入源代碼并運行幾次后,請試著對其進行更改。標有!的注釋給你提供了更改建議。你也可以自己嘗試執行以下操作。
● 通過更改NUM_DIGITS
修改秘密數字的位數。
● 通過更改MAX_GUESSES
修改玩家的最大猜測次數。
● 嘗試創建秘密數字中包含字母和數字的程序版本。
推薦閱讀
- TypeScript Essentials
- MySQL數據庫管理實戰
- 復雜軟件設計之道:領域驅動設計全面解析與實戰
- OpenShift開發指南(原書第2版)
- Hands-On JavaScript High Performance
- Go語言精進之路:從新手到高手的編程思想、方法和技巧(2)
- Kotlin開發教程(全2冊)
- Mastering ArcGIS Enterprise Administration
- FPGA嵌入式項目開發實戰
- TypeScript 2.x By Example
- Mastering Adobe Captivate 7
- Building Business Websites with Squarespace 7(Second Edition)
- Python預測分析與機器學習
- Python 快速入門(第3版)
- 基于MATLAB的控制系統仿真及應用