通过Game()函数打造一个交互式Python游戏应用
发布时间:2023-12-26 05:30:53
下面是一个交互式的Python游戏应用的示例代码,名为"Guess the Number"。在这个游戏中,玩家需要猜测一个随机生成的数字,直到猜中为止。游戏会根据猜测的次数给出提示,直到玩家猜中为止。
import random
def game():
print("Welcome to Guess the Number Game!")
print("I'm thinking of a number between 1 and 100.")
target_number = random.randint(1, 100)
guess = None
num_guesses = 0
while guess != target_number:
guess = int(input("Take a guess: "))
num_guesses += 1
if guess < target_number:
print("Too low! Try again.")
elif guess > target_number:
print("Too high! Try again.")
else:
print(f"Congratulations! You guessed the number in {num_guesses} guesses.")
game()
运行以上代码后,游戏会显示欢迎消息和游戏规则。然后,它会生成一个1到100之间的随机数字,玩家需要通过输入猜测的数字来猜出正确的数字。游戏会根据玩家的每次输入给出相应的提示,直到猜中为止。最后,游戏会告诉玩家猜了多少次才猜中。
以下是一个游戏的运行示例:
Welcome to Guess the Number Game! I'm thinking of a number between 1 and 100. Take a guess: 50 Too low! Try again. Take a guess: 75 Too high! Try again. Take a guess: 63 Too high! Try again. Take a guess: 57 Too high! Try again. Take a guess: 53 Congratulations! You guessed the number in 5 guesses.
通过以上示例代码,您可以使用Game()函数轻松创建一个交互式的Python游戏应用,并根据需要进行相应的修改和扩展。
