首頁 >後端開發 >Python教學 >如何為初學者使用 Python 創建「猜數字」遊戲

如何為初學者使用 Python 創建「猜數字」遊戲

WBOY
WBOY原創
2024-08-12 18:39:39384瀏覽

How to Create a

什麼是「猜數字」遊戲?

在這個遊戲中,電腦隨機選擇一個數字,你必須猜測它是什麼。每次猜測後,計算機都會告訴您您的猜測是否太高、太低或恰到好處。當您猜對數字時遊戲結束,並且它還會告訴您嘗試了多少次。

讓我們開始吧!

第 1 步:導入隨機模組
首先,我們需要導入隨機模組。這個模組幫助我們產生一個隨機數,您將嘗試猜測。

import random

第 2 步:產生隨機數
現在,我們需要產生一個 1 到 100 之間的隨機數。這個數字將是您必須猜測的秘密數字。

# Generate a random number between 1 and 100
secret_number = random.randint(1, 100)

第三步:開始遊戲並解釋規則
接下來,讓我們向玩家顯示歡迎訊息並解釋規則。

# Start the game
print("Welcome to 'Guess the Number' game!")
print("I'm thinking of a number between 1 and 100.")

第 4 步:建立猜測循環
我們將創建一個循環,不斷要求玩家猜測數字,直到他們猜對為止。我們也會記錄玩家的猜測次數。

# Variable to store the user's guess
guess = None

# Variable to count the number of attempts
attempts = 0

第 5 步:詢問玩家的猜測
在此步驟中,我們將要求玩家輸入他們的猜測。他們猜測後,我們將檢查猜測是否過高、過低或正確。

# Loop until the user guesses the correct number
while guess != secret_number:
    # Ask the user to enter a number
    guess = int(input("Enter your guess: "))

    # Increment the attempts counter
    attempts += 1

    # Check if the guess is too low, too high, or correct
    if guess < secret_number:
        print("Too low! Try guessing a higher number.")
    elif guess > secret_number:
        print("Too high! Try guessing a lower number.")
    else:
        print("Congratulations! You guessed the correct number!")

第 6 步:顯示嘗試次數

最後,在玩家猜出數字後,我們會讓他們知道需要嘗試多少次才能找到正確答案。

# Tell the user how many attempts it took
print(f"It took you {attempts} attempts to guess the correct number.")
print("Thank you for playing!")

完整程式碼
這是遊戲的完整程式碼:

import random

# Generate a random number between 1 and 100
secret_number = random.randint(1, 100)

# Start the game
print("Welcome to 'Guess the Number' game!")
print("I'm thinking of a number between 1 and 100.")

# Variable to store the user's guess
guess = None

# Variable to count the number of attempts
attempts = 0

# Loop until the user guesses the correct number
while guess != secret_number:
    # Ask the user to enter a number
    guess = int(input("Enter your guess: "))

    # Increment the attempts counter
    attempts += 1

    # Check if the guess is too low, too high, or correct
    if guess < secret_number:
        print("Too low! Try guessing a higher number.")
    elif guess > secret_number:
        print("Too high! Try guessing a lower number.")
    else:
        print("Congratulations! You guessed the correct number!")

# Tell the user how many attempts it took
print(f"It took you {attempts} attempts to guess the correct number.")
print("Thank you for playing!")

就是這樣!您剛剛用 Python 創建了一個簡單的「猜數字」遊戲。此專案非常適合初學者,可以幫助您了解 Python 中循環、條件和使用者輸入的基礎知識。繼續練習,很快您就可以創建更複雜的項目了!

編碼愉快! !

想成為Python大師請點這裡。

以上是如何為初學者使用 Python 創建「猜數字」遊戲的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn