一口气用Python写了13个小游戏
这些小游戏的源代码可能包含在《Python编程:从入门到实践》一书中,这本书详细介绍了如何使用Python来创建各种有趣的小游戏。以下是这本书中的一些游戏的简要代码示例:
- 猜数字游戏:
answer = 42
guess = None
while guess != answer:
guess = int(input("请输入你猜测的数字:"))
if guess == answer:
print("恭喜你,猜对了!")
else:
if guess > answer:
print("猜的数字大了!")
else:
print("猜的数字小了!")
- 猜词游戏:
import random
WORDS = ["python", "jumble", "easy", "difficult", "spinner", "rhyme"]
word = random.choice(WORDS)
correct = word
jumble = ""
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
print(f"Jumble: {jumble}")
guess = input("What is the correct word?: ")
if guess == correct:
print("That's correct!")
else:
print("Sorry, that's not it.")
print(f"The correct word was {correct}.")
- 游戏:猜测用户名游戏:
usernames = ['admin', 'player', 'guest']
for turn in range(3):
guess = input("请输入你猜测的用户名:")
if guess in usernames:
print("恭喜你,猜对了!")
break
else:
print("抱歉,猜错了。")
else:
print("抱歉,次数用完。正确的用户名是:", usernames)
这些例子只是书中源代码的一部分,完整的源代码和其他游戏可以在书中找到。
评论已关闭