上個周末,我整理了一份可以用 Python 編寫的游戲列表。但為什么呢?
如果您是 Python 程序員初學者,編寫有趣的游戲可以幫助您更快更好地學習 Python 語言,而不會被語法之類的東西所困擾。我在學習 Python 的時候曾制作過一些這樣的游戲;我非常享受這個過程!
你可以編寫的第一個游戲,也是最簡單的一個游戲,就是猜數字游戲(或者叫 “猜數字”!)。因此,我想寫一篇循序漸進的教程來編寫這個游戲的代碼,并幫助初學者學習一些基礎知識。
Let’s begin!
數字競猜游戲是如何進行的?
在數字競猜游戲中,用戶要在給定的嘗試次數內猜出一個隨機生成的秘密數字。
每次猜測之后,用戶都會得到提示,告訴他們猜測的數字是過高、過低還是正確。是的,當用戶猜中秘密數字或嘗試次數用完時,游戲就結束了。
數字猜謎游戲編碼
讓我們開始編碼吧!創建一個新的 Python 腳本并開始編碼。
第 1 步 - 導入隨機模塊
讓我們從導入內置 random
模塊開始。random
模塊中的函數可以用來生成指定范圍內的隨機秘密數字:
import random
注意:random
模塊給出的是偽隨機數,而不是真正的隨機數。因此,請勿將其用于密碼生成等敏感應用。
第 2 步 - 設置范圍和最大嘗試次數
接下來,我們需要確定秘密號碼的范圍和允許玩家嘗試的最大次數。在本教程中,我們把 lower_bound
和 upper_bound
分別設為 1 和 1000。另外,將允許的最大嘗試次數 max_attempts
設為 10:
lower_bound = 1
upper_bound = 1000
max_attempts = 10
第 3 步 - 生成隨機數
現在,讓我們使用 random.randint()
函數在指定范圍內生成一個隨機數。這就是用戶需要猜測的秘密數字:
secret_number = random.randint(lower_bound, upper_bound)
第 4 步 - 讀取用戶輸入信息
為了獲取用戶的輸入,讓我們創建一個名為 get_guess()
的函數。記住,用戶可以輸入無效輸入:超出 [lower_bound, upper_bound]
范圍的數字、字符串或浮點數等。
我們將在 get_guess()
函數中處理這種情況,該函數會不斷提示用戶輸入一個數字–在指定范圍內–直到他們提供一個有效的輸入。
在這里,我們使用 while
循環來提示用戶輸入有效輸入,直到他們輸入一個介于 lower_bound
和 upper_bound
之間的整數:
def get_guess():while True:try:guess = int(input(f"Guess a number between {lower_bound} and {upper_bound}: "))if lower_bound <= guess <= upper_bound:return guesselse:print("Invalid input. Please enter a number within the specified range.")except ValueError:print("Invalid input. Please enter a valid number.")
第 5 步 - 驗證用戶的猜測
接下來,讓我們定義一個 check_guess()
函數,它將用戶的猜測和秘密數字作為輸入,并就猜測是否正確、過高或過低提供反饋。
該函數將玩家的猜測與秘密數字進行比較,并返回相應的信息:
def check_guess(guess, secret_number):if guess == secret_number:return "Correct"elif guess < secret_number:return "Too low"else:return "Too high"
第 6 步 - 跟蹤嘗試次數并檢測游戲結束條件
現在我們將創建函數 play_game()
,該函數負責處理游戲邏輯并將所有內容整合在一起。該函數使用 attempts
變量來跟蹤用戶的嘗試次數。在一個 while
循環中,用戶會被提示輸入一個猜測,并由 get_guess()
函數進行處理。
調用 check_guess()
函數可以獲得用戶猜測的反饋信息:
- 如果猜測正確,用戶獲勝,游戲結束。
- 否則,用戶將獲得另一次猜測機會。
- 這個過程一直持續到玩家猜中秘密數字或猜完為止。
下面是play_game()
函數:
def play_game():attempts = 0won = Falsewhile attempts < max_attempts:attempts += 1guess = get_guess()result = check_guess(guess, secret_number)if result == "Correct":print(f"Congratulations! You guessed the secret number {secret_number} in {attempts} attempts.")won = Truebreakelse:print(f"{result}. Try again!")if not won:print(f"Sorry, you ran out of attempts! The secret number is {secret_number}.")
第 7 步 - 玩游戲!
最后,每次運行 Python 腳本時,都可以調用 play_game() 函數:
if __name__ == "__main__":print("Welcome to the Number Guessing Game!")play_game()
將所有內容整合在一起
現在我們的 Python 腳本是這樣的
# main.py
import random# define range and max_attempts
lower_bound = 1
upper_bound = 1000
max_attempts = 10# generate the secret number
secret_number = random.randint(lower_bound, upper_bound)# Get the user's guess
def get_guess():while True:try:guess = int(input(f"Guess a number between {lower_bound} and {upper_bound}: "))if lower_bound <= guess <= upper_bound:return guesselse:print("Invalid input. Please enter a number within the specified range.")except ValueError:print("Invalid input. Please enter a valid number.")# Validate guess
def check_guess(guess, secret_number):if guess == secret_number:return "Correct"elif guess < secret_number:return "Too low"else:return "Too high"# track the number of attempts, detect if the game is over
def play_game():attempts = 0won = Falsewhile attempts < max_attempts:attempts += 1guess = get_guess()result = check_guess(guess, secret_number)if result == "Correct":print(f"Congratulations! You guessed the secret number {secret_number} in {attempts} attempts.")won = Truebreakelse:print(f"{result}. Try again!")if not won:print(f"Sorry, you ran out of attempts! The secret number is {secret_number}.")if __name__ == "__main__":print("Welcome to the Number Guessing Game!")play_game()
下面是腳本運行樣本的輸出結果:
Welcome to the Number Guessing Game!
Guess a number between 1 and 1000: 500
Too low. Try again!
Guess a number between 1 and 1000: 750
Too high. Try again!
Guess a number between 1 and 1000: 625
Too low. Try again!
Guess a number between 1 and 1000: 685
Too low. Try again!
Guess a number between 1 and 1000: 710
Too low. Try again!
Guess a number between 1 and 1000: 730
Congratulations! You guessed the secret number 730 in 6 attempts.
結束
恭喜你您已經成功地用 Python 構建了一個數字競猜游戲。我們很快會在另一個教程中再見。不過,別等我了。Python很有趣的,你也可以在互聯網上找到更多有意思的代碼和程序哦!
感謝大家花時間閱讀我的文章,你們的支持是我不斷前進的動力。期望未來能為大家帶來更多有價值的內容,請多多關注我的動態!