使用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
广告