使用Python的猜數字遊戲



猜數字是一款經典的破譯密碼遊戲,玩家需要在一定次數的嘗試內猜出秘密程式碼。在本文中,我們將探討如何使用不同的方法(從基本到高階)在Python中實現猜數字遊戲。我們將介紹每種方法中使用的邏輯、程式碼和概念解釋。

方法1:基本實現

在猜數字遊戲的基本實現中,計算機隨機生成一個秘密程式碼,玩家必須猜出該程式碼。計算機在每次猜測後提供反饋,指示有多少位數字正確且位置正確(表示為“bulls”),以及有多少位數字正確但位置錯誤(表示為“cows”)。

示例

以下是基本實現程式碼:

import random

# Function to generate a random 4-digit code
def generate_code():
   return [random.randint(0, 9) for _ in range(4)]

# Function to compare the guess with the code
def check_guess(code, guess):
   bulls = sum([1 for i in range(4) if code[i] == guess[i]])
   cows = sum([1 for i in range(4) if guess[i] in code and code[i] != guess[i]])
   return bulls, cows

# Main game loop
def mastermind_basic():
   code = generate_code()
   attempts = 10
   print("Welcome to Mastermind!")
   print("Guess the 4-digit code. You have 10 attempts.")

   while attempts > 0:
      guess = list(map(int, input("Enter your guess: ").strip()))
      bulls, cows = check_guess(code, guess)
      print(f"Bulls: {bulls}, Cows: {cows}")

      if bulls == 4:
         print("Congratulations! You've cracked the code!")
         break
      attempts -= 1

      if attempts == 0:
         print(f"Game Over! The code was: {''.join(map(str, code))}")

# Run the basic game
mastermind_basic()

輸出

Welcome to Mastermind!
Guess the 4-digit code. You have 10 attempts.
Enter your guess: 1234
Bulls: 1, Cows: 2
Enter your guess: 5678
Bulls: 0, Cows: 1
Enter your guess: 9101
Bulls: 2, Cows: 0
...
Congratulations! You've cracked the code!

解釋

  • “generate_code”函式使用random模組生成一個隨機的4位數字程式碼。
  • “check_guess”函式比較玩家的猜測與秘密程式碼,並返回bulls和cows的數量。
  • 主遊戲迴圈執行10次嘗試,玩家輸入他們的猜測,程式提供反饋。

方法2:帶有輸入驗證的高階實現

在這個高階版本中,我們新增輸入驗證以確保玩家輸入有效的4位數字。我們還將引入一個函式來檢查程式碼中是否包含唯一數字,使遊戲更具挑戰性。

示例

以下是高階實現程式碼:

import random

# Function to generate a random 4-digit code with unique digits
def generate_unique_code():
   digits = list(range(10))
   random.shuffle(digits)
   return digits[:4]

# Function to validate user input
def validate_input(user_input):
   return user_input.isdigit() and len(user_input) == 4

# Function to compare the guess with the code
def check_guess(code, guess):
   bulls = sum([1 for i in range(4) if code[i] == guess[i]])
   cows = sum([1 for i in range(4) if guess[i] in code and code[i] != guess[i]])
   return bulls, cows

# Main game loop
def mastermind_advanced():
   code = generate_unique_code()
   attempts = 10
   print("Welcome to Mastermind!")
   print("Guess the 4-digit code with unique digits. You have 10 attempts.")

   while attempts > 0:
      guess = input("Enter your guess: ").strip()
      if not validate_input(guess):
         print("Invalid input! Please enter a 4-digit number.")
         continue

      guess = list(map(int, guess))
      bulls, cows = check_guess(code, guess)
      print(f"Bulls: {bulls}, Cows: {cows}")

      if bulls == 4:
         print("Congratulations! You've cracked the code!")
         break
      attempts -= 1

   if attempts == 0:
      print(f"Game Over! The code was: {''.join(map(str, code))}")

# Run the advanced game
mastermind_advanced()

輸出

Welcome to Mastermind!
Guess the 4-digit code with unique digits. You have 10 attempts.
Enter your guess: 1123
Invalid input! Please enter a 4-digit number.
Enter your guess: 3456
Bulls: 0, Cows: 2
Enter your guess: 7890
Bulls: 1, Cows: 1
...
Congratulations! You've cracked the code!

解釋

  • “generate_unique_code”函式透過對數字列表進行洗牌並選擇前四個數字來生成一個包含唯一數字的4位數字程式碼。
  • “validate_input”函式檢查玩家的輸入是否為4位數字。
  • 遊戲迴圈現在包括輸入驗證,如果輸入無效,則提示玩家重新輸入猜測。

結論

猜數字遊戲是練習Python程式設計的一種有趣且具有挑戰性的方式。在本文中,我們探討了兩種不同的遊戲實現方法,從基本版本到具有輸入驗證和唯一數字的更高階版本。這些示例為進一步增強提供了堅實的基礎,例如新增圖形使用者介面(GUI)或實現AI來玩遊戲。

python_projects_from_basic_to_advanced.htm
廣告