首页 后端开发 Python教程 用 Python 构建交互式 Mad Libs 游戏:初学者指南

用 Python 构建交互式 Mad Libs 游戏:初学者指南

Oct 06, 2024 pm 06:15 PM

你有没有发现自己在填写随机单词以创造一个搞笑荒诞的故事时无法控制地咯咯笑?如果是这样,您可能已经体验过 Mad Libs 的乐趣,这是一款自 20 世纪 50 年代以来一直为各个年龄段的人们带来乐趣的经典文字游戏。

但是如果我告诉您,这个简单的游戏也可以成为您通往令人兴奋的 Python 编程世界的门户?

什么是疯狂自由?

Building an Interactive Mad Libs Game in Python: A Beginner

Mad Libs 的核心是一款填空讲故事游戏。玩家在不知道故事背景的情况下,会被提示提供特定类型的单词(名词、动词、形容词等)。

Building an Interactive Mad Libs Game in Python: A Beginner

在这里了解循环:Python 循环:初学者综合指南

然后将这些单词插入到预先写好的叙述中,通常会产生一个喜剧和无意义的故事,激发笑声和创造力。

但是 Mad Libs 不仅仅是一种娱乐。当转化为编程项目时,它成为一种强大的教学工具,为有抱负的程序员提供一种有趣且引人入胜的方式来学习基本编程概念。

设置 Python 环境

首先,请确保您的计算机上安装了 Python。您可以从Python官方网站下载它。对于这个项目,我们将使用 Python 3.12.7。

安装 Python 后,打开您最喜欢的文本编辑器或集成开发环境 (IDE)。初学者的热门选择包括 IDLE(Python 附带)、Visual Studio Code 或 PyCharm。

对于这个项目,我将使用 Pycharm。

构建 Mad Libs 游戏:一步一步

让我们将 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 游戏。该项目向您介绍了几个重要的编程概念:

  1. 字符串操作
  2. 用户输入和输出
  3. 函数和模块化编程
  4. 列表和列表推导式
  5. 文件 I/O 操作
  6. 错误处理
  7. 第三方库(colorama)
  8. 随机选择
  9. While 循环和控制流

通过构建这个游戏,您不仅创造了一些有趣的东西,而且还为更高级的 Python 项目奠定了坚实的基础。请记住,成为熟练程序员的关键是练习和实验。不要害怕修改这个游戏,添加新功能,或使用这些概念创建全新的项目!

当您继续 Python 之旅时,请考虑探索更高级的主题,例如面向对象编程、图形用户界面 (GUI) 或使用 Django 或 Flask 等框架进行 Web 开发。

您在这里学到的技能将成为这些更复杂的软件开发领域的绝佳跳板。

快乐编码,愿你的 Mad Libs 冒险充满欢笑和学习!

资源

  • 开始使用 Folium
  • Visual Studio Code 的 20 个基本 Python 扩展
  • 使用 Python 进行网页抓取和数据提取
  • Python 入门
  • 使用 Folium 和 Python 创建交互式地图

以上是用 Python 构建交互式 Mad Libs 游戏:初学者指南的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

如何解决Linux终端中查看Python版本时遇到的权限问题? 如何解决Linux终端中查看Python版本时遇到的权限问题? Apr 01, 2025 pm 05:09 PM

Linux终端中查看Python版本时遇到权限问题的解决方法当你在Linux终端中尝试查看Python的版本时,输入python...

如何在使用 Fiddler Everywhere 进行中间人读取时避免被浏览器检测到? 如何在使用 Fiddler Everywhere 进行中间人读取时避免被浏览器检测到? Apr 02, 2025 am 07:15 AM

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

在Python中如何高效地将一个DataFrame的整列复制到另一个结构不同的DataFrame中? 在Python中如何高效地将一个DataFrame的整列复制到另一个结构不同的DataFrame中? Apr 01, 2025 pm 11:15 PM

在使用Python的pandas库时,如何在两个结构不同的DataFrame之间进行整列复制是一个常见的问题。假设我们有两个Dat...

Uvicorn是如何在没有serve_forever()的情况下持续监听HTTP请求的? Uvicorn是如何在没有serve_forever()的情况下持续监听HTTP请求的? Apr 01, 2025 pm 10:51 PM

Uvicorn是如何持续监听HTTP请求的?Uvicorn是一个基于ASGI的轻量级Web服务器,其核心功能之一便是监听HTTP请求并进�...

在Linux终端中使用python --version命令时如何解决权限问题? 在Linux终端中使用python --version命令时如何解决权限问题? Apr 02, 2025 am 06:36 AM

Linux终端中使用python...

如何在10小时内通过项目和问题驱动的方式教计算机小白编程基础? 如何在10小时内通过项目和问题驱动的方式教计算机小白编程基础? Apr 02, 2025 am 07:18 AM

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

如何绕过Investing.com的反爬虫机制获取新闻数据? 如何绕过Investing.com的反爬虫机制获取新闻数据? Apr 02, 2025 am 07:03 AM

攻克Investing.com的反爬虫策略许多人尝试爬取Investing.com(https://cn.investing.com/news/latest-news)的新闻数据时,常常�...

See all articles