你有没有发现自己在填写随机单词以创造一个搞笑荒诞的故事时无法控制地咯咯笑?如果是这样,您可能已经体验过 Mad Libs 的乐趣,这是一款自 20 世纪 50 年代以来一直为各个年龄段的人们带来乐趣的经典文字游戏。
但是如果我告诉您,这个简单的游戏也可以成为您通往令人兴奋的 Python 编程世界的门户?
Mad Libs 的核心是一款填空讲故事游戏。玩家在不知道故事背景的情况下,会被提示提供特定类型的单词(名词、动词、形容词等)。
在这里了解循环:Python 循环:初学者综合指南
然后将这些单词插入到预先写好的叙述中,通常会产生一个喜剧和无意义的故事,激发笑声和创造力。
但 Mad Libs 不仅仅是一种娱乐。当转化为编程项目时,它成为一种强大的教学工具,为有抱负的程序员提供一种有趣且引人入胜的方式来学习基本编程概念。
首先,请确保您的计算机上安装了 Python。您可以从Python官方网站下载它。对于这个项目,我们将使用 Python 3.12.7。
安装 Python 后,打开您最喜欢的文本编辑器或集成开发环境 (IDE)。初学者的热门选择包括 IDLE(Python 附带)、Visual Studio Code 或 PyCharm。
对于这个项目,我将使用 Pycharm。
让我们将 Mad Libs 游戏分解为可管理的步骤。我们将从基本版本开始,逐步添加更多功能,使其更具互动性和吸引力。
您可以在这里找到完整的代码。
要运行这个游戏,您需要安装一些依赖项,其中之一是 colorama 库。您可以通过运行以下命令来做到这一点:
pip install colorama
导入该项目所需的一些库,其中包括 ramdom、os colorama
import random import os from colorama import init, Fore, Style
接下来我们将使用 init(),它允许我们使用彩色输出来增强用户界面,例如以青色显示欢迎消息,以红色显示错误,以及以明亮风格的白色显示已完成的故事。
首先,我们将定义故事模板。这将是一个带有占位符的字符串,其中包含我们希望玩家填写的单词。下面是一个示例:
story_template = """ Once upon a time, in a {adjective} {noun}, there lived a {adjective} {noun}. Every day, they would {verb} to the {noun} and {verb} with their {adjective} {noun}. One day, something {adjective} happened! They found a {adjective} {noun} that could {verb}! From that day on, their life became even more {adjective} and full of {noun}. """
接下来,我们将创建故事所需的单词类型列表:
word_types = ["adjective", "noun", "adjective", "noun", "verb", "noun", "verb", "adjective", "noun", "adjective", "adjective", "noun", "verb", "adjective", "noun"]
现在,让我们创建一个函数来提示玩家输入单词:
def get_word(word_type): return input(f"Enter a(n) {word_type}: ") def collect_words(word_types): return [get_word(word_type) for word_type in word_types]
收集到的单词,我们可以填写我们的故事模板:
def fill_story(template, words): for word in words: template = template.replace("{" + word_types[words.index(word)] + "}", word, 1) return template
让我们创建一个主函数来运行我们的游戏:
def play_mad_libs(): print("Welcome to Mad Libs!") print("I'll ask you for some words to fill in the blanks of our story.") words = collect_words(word_types) completed_story = fill_story(story_template, words) print("\nHere's your Mad Libs story:\n") print(completed_story) if __name__ == "__main__": play_mad_libs()
现在我们有了 Mad Libs 游戏的基本工作版本!但我们不要就此止步。我们可以让它变得更具吸引力和用户友好性。
添加多个故事模板
为了保持游戏的趣味性,我们添加多个故事模板:
import random story_templates = [ # ... (add your original story template here) """ In a {adjective} galaxy far, far away, a {adjective} {noun} embarked on a {adjective} quest. Armed with a {adjective} {noun}, they set out to {verb} the evil {noun} and save the {noun}. Along the way, they encountered a {adjective} {noun} who taught them to {verb} with great skill. In the end, they emerged {adjective} and ready to face any {noun} that came their way. """, # ... (add more story templates as desired) ] def choose_random_template(): return random.choice(story_templates)
实现重玩功能
让我们添加玩家玩多轮的选项:
def play_again(): return input("Would you like to play again? (yes/no): ").lower().startswith('y') def mad_libs_game(): while True: template = choose_random_template() word_types = extract_word_types(template) play_mad_libs(template, word_types) if not play_again(): print("Thanks for playing Mad Libs!") break def extract_word_types(template): return [word.split('}')[0] for word in template.split('{')[1:]]
添加错误处理
为了使我们的游戏更加健壮,让我们添加一些错误处理:
def get_word(word_type): while True: word = input(f"Enter a(n) {word_type}: ").strip() if word: return word print("Oops! You didn't enter anything. Please try again.")
改善用户体验
让我们添加一些颜色和格式以使我们的游戏更具视觉吸引力:
from colorama import init, Fore, Style init() # Initialize colorama def print_colored(text, color=Fore.WHITE, style=Style.NORMAL): print(f"{style}{color}{text}{Style.RESET_ALL}") def play_mad_libs(template, word_types): print_colored("Welcome to Mad Libs!", Fore.CYAN, Style.BRIGHT) print_colored("I'll ask you for some words to fill in the blanks of our story.", Fore.YELLOW) words = collect_words(word_types) completed_story = fill_story(template, words) print_colored("\nHere's your Mad Libs story:\n", Fore.GREEN, Style.BRIGHT) print_colored(completed_story, Fore.WHITE, Style.BRIGHT) **Saving Stories** Let's give players the option to save their stories: import os def save_story(story): if not os.path.exists("mad_libs_stories"): os.makedirs("mad_libs_stories") filename = f"mad_libs_stories/story_{len(os.listdir('mad_libs_stories')) + 1}.txt" with open(filename, "w") as file: file.write(story) print_colored(f"Your story has been saved as {filename}", Fore.GREEN) def play_mad_libs(template, word_types): # ... (previous code) if input("Would you like to save this story? (yes/no): ").lower().startswith('y'): save_story(completed_story)
首先,确保您的系统上安装了 Python。您可以通过打开终端并输入来检查这一点。
python --version
或
python3 --version
这应该返回您系统上安装的 Python 版本。
如果安装了 Python,则应使用 Python 解释器运行该脚本。而不是跑步。
./first_test.py
你应该运行:
python first_test.py
或者如果您专门使用 Python 3:
python3 first_test.py
此外,请确保该文件具有正确的执行权限。您可以通过以下方式设置:
chmod +x first_test.py<br>
恭喜!您现在已经用 Python 创建了一个交互式、色彩丰富且功能丰富的 Mad Libs 游戏。该项目向您介绍了几个重要的编程概念:
By building this game, you've not only created something fun but also laid a solid foundation for more advanced Python projects. Remember, the key to becoming a proficient programmer is practice and experimentation. Don't be afraid to modify this game, add new features, or use these concepts to create entirely new projects!
As you continue your Python journey, consider exploring more advanced topics like object-oriented programming, graphical user interfaces (GUIs), or web development with frameworks like Django or Flask.
The skills you've learned here will serve as an excellent springboard for these more complex areas of software development.
Happy coding, and may your Mad Libs adventures be filled with laughter and learning!
The above is the detailed content of Building an Interactive Mad Libs Game in Python: A Beginners Guide. For more information, please follow other related articles on the PHP Chinese website!