Mad Libs:趣味故事创作游戏

通过创意填词打造独一无二的趣味故事

一、Mad Libs 游戏简介

Mad Libs 是一种经典的文字游戏,它通过让玩家在不知道完整故事的情况下,根据提示填入不同词性的单词(如名词、动词、形容词等),最终组合成一个充满趣味和惊喜的故事。

游戏特色

二、Mad Libs 游戏实现与解析

(一)基础代码实现

"""Mad Libs: Funny Story Creation Game

Exercises:
1. How to replace the story?
2. How load the story and from a file?
3. How to add additional parts of speech?
"""

# 故事模板,其中|1|、|2|等为需要用户输入的位置标记
template = 'The |1| |2| |3| |4| over the |5| |6|.'
# 定义每个标记对应的词性描述
parts = {
    '1': 'adjective',
    '2': 'adjective',
    '3': 'noun',
    '4': 'verb',
    '5': 'adjective',
    '6': 'noun',
}

chunks = []

# 分割模板并处理每个部分
for chunk in template.split('|'):
    if chunk in parts:
        # 如果是需要用户输入的部分,获取对应的词性描述并提示用户输入
        description = parts[chunk]
        prompt = 'Enter [{}]: '.format(description)
        word = input(prompt)
        chunks.append(word)
    else:
        # 如果是普通文本,直接添加到结果中
        chunks.append(chunk)

print('=' * 80)
# 组合所有部分形成完整故事并输出
story = ''.join(chunks)
print(story)

(二)代码功能解析

1. 故事模板设计

代码中的 template 变量定义了故事的基本框架,使用 |1||2| 等标记表示需要用户输入单词的位置。

2. 词性定义与映射

parts 字典将每个标记映射到对应的词性描述,例如:

(三)游戏运行示例

示例输入
生成的故事
================================================================================
The purple fluffy unicorn skipped over the sleepy dragon.

三、功能扩展与优化

(一)替换故事模板

可以通过修改 templateparts 变量来更换故事模板:

# 新的故事模板
template = 'On a |1| day, |2| decided to go to the |3|. There, |2| met a |4| |5| that could |6|! What an adventure!'
parts = {
    '1': 'adjective',
    '2': 'name',
    '3': 'place',
    '4': 'adjective',
    '5': 'animal',
    '6': 'verb'
}

(二)从文件加载故事模板

实现文件加载功能,使游戏更加灵活:

import os

def load_story_from_file(file_path):
    """从文件加载故事模板"""
    if not os.path.exists(file_path):
        print(f"文件 {file_path} 不存在!")
        return None, None
    
    try:
        with open(file_path, 'r') as f:
            # 读取模板字符串
            template = f.readline().strip()
            # 读取词性描述
            parts = {}
            for line in f:
                line = line.strip()
                if line:
                    chunk, description = line.split(':', 1)
                    parts[chunk.strip()] = description.strip()
        return template, parts
    except Exception as e:
        print(f"加载故事文件时出错:{e}")
        return None, None

(三)添加额外的词性

扩展 parts 字典以支持更多词性:

parts = {
    '1': 'adjective',
    '2': 'adjective',
    '3': 'noun',
    '4': 'verb',
    '5': 'adjective',
    '6': 'noun',
    '7': 'adverb',  # 新增副词
    '8': 'pronoun'   # 新增代词
}

四、进一步拓展思路

创意扩展方向

五、结语

Mad Libs 游戏不仅是一种有趣的娱乐方式,还能在轻松愉快的氛围中锻炼语言能力和创造力。通过本文介绍的代码实现和扩展思路,我们可以打造出更加丰富多样的 Mad Libs 游戏体验。

无论是作为教育工具帮助孩子学习词性和词汇,还是作为聚会游戏带来欢乐,Mad Libs 都有着广泛的应用场景。希望本文能为你提供一个良好的起点,让你可以根据自己的想法进一步拓展和优化这个有趣的故事创作游戏。