如何用 Python 编写一个简单的猜数字游戏
我上个周末整理了一份可以用 Python 编写的游戏清单。但为什么呢?
如果你是 Python 的初学者,编写有趣的游戏可以帮助你更快更好地学习这门语言,避免陷入语法之类的困境。我在学习 Python 的时候编写了一些这样的游戏;我非常享受这个过程!
你能编写的第一个游戏,也是所有游戏里最简单的,就是猜数字游戏(或者叫“猜数字”)!所以我想写一个循序渐进的教程来教你如何编写这个游戏,并帮助初学者学习一些基础知识。
让我们开始吧!
猜数字游戏是如何进行的?
在猜数字游戏中,用户在给定的尝试次数内猜出一个随机生成的秘密数字。
每次猜测后,用户都会收到提示,告知他们猜测的数字是过高、过低还是正确。所以,当用户猜中秘密数字或尝试次数用尽时,游戏就会结束。
编写猜数字游戏代码
开始编码吧!创建一个新的 Python 脚本并开始编码。
步骤 1 - 导入random
模块
我们先导入内置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 guess
else:
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 = 0
won = False
while attempts < max_attempts:
attempts += 1
guess = 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 = True
break
else:
print(f"{result}. Try again!")
if not won:
print(f"Sorry, you ran out of attempts! The secret number is {secret_number}.")
第 7 步 - 玩游戏!
最后,您可以play_game()
在每次运行 Python 脚本时调用该函数:
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 guess
else:
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 = 0
won = False
while attempts < max_attempts:
attempts += 1
guess = 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 = True
break
else:
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 构建了一个猜数字游戏。我很快会在另一篇教程中与大家见面。不过,别等我了。快来看看其他您可以构建的游戏——您可以编写的功能——然后开始编写代码吧!
文章来源:https://dev.to/balapriya/how-to-code-a-simple-number-guessing-game-in-python-4jai