-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmad-libs.py
More file actions
313 lines (289 loc) Β· 10.9 KB
/
mad-libs.py
File metadata and controls
313 lines (289 loc) Β· 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
#!/usr/bin/env python3
"""
Mad Libs Flask Web Application
A fun word game where random words are inserted into story templates
"""
from flask import Flask, render_template_string, request, jsonify
import random
app = Flask(__name__)
# Word lists for different categories
WORD_LISTS = {
'nouns': [
'elephant', 'bicycle', 'hamburger', 'computer', 'rainbow', 'dinosaur',
'pizza', 'rocket', 'telephone', 'sandwich', 'butterfly', 'volcano',
'penguin', 'spaceship', 'cookie', 'dragon', 'unicorn', 'robot'
],
'verbs': [
'dancing', 'singing', 'jumping', 'flying', 'swimming', 'cooking',
'laughing', 'running', 'climbing', 'painting', 'reading', 'writing',
'skateboarding', 'juggling', 'sneezing', 'tickling', 'wiggling', 'bouncing'
],
'adjectives': [
'silly', 'enormous', 'tiny', 'sparkly', 'squishy', 'fuzzy',
'gigantic', 'invisible', 'magical', 'stinky', 'colorful', 'bouncy',
'slippery', 'mysterious', 'fantastic', 'ridiculous', 'amazing', 'peculiar'
],
'colors': [
'purple', 'orange', 'turquoise', 'magenta', 'lime green', 'hot pink',
'golden', 'silver', 'rainbow-colored', 'polka-dotted', 'striped', 'glittery'
],
'animals': [
'llama', 'platypus', 'octopus', 'kangaroo', 'flamingo', 'hedgehog',
'pangolin', 'narwhal', 'sloth', 'armadillo', 'peacock', 'chameleon'
],
'foods': [
'spaghetti', 'marshmallow', 'pickle', 'donut', 'taco', 'pancake',
'bubble gum', 'cotton candy', 'cheese', 'banana', 'popcorn', 'pretzel'
],
'places': [
'the moon', 'a treehouse', 'underwater', 'in a cloud', 'inside a volcano',
'on Mars', 'in a candy store', 'at the circus', 'in a jungle', 'on a pirate ship'
]
}
# Story templates with placeholders
STORY_TEMPLATES = [
{
'title': 'The Amazing Adventure',
'template': """Once upon a time, there was a {adjectives} {animals} named Bob who lived in {places}.
Every morning, Bob would wake up and eat a {foods} for breakfast. Then Bob would spend the day {verbs}
with a {colors} {nouns}. One day, Bob discovered a {adjectives} {nouns} that could {verbs}!
Bob was so {adjectives} that he decided to {verbs} all the way to {places} and share the
{colors} {foods} with all the {adjectives} {animals}s there. The end!"""
},
{
'title': 'The Silly School Day',
'template': """At {places}, there was a {adjectives} teacher who loved to {verbs}. The students
would always bring {colors} {foods} for lunch and play with {adjectives} {nouns}s during recess.
One day, a {animals} came to school and started {verbs} in the classroom! The teacher was so
{adjectives} that they gave the {animals} a {colors} {nouns} as a reward. Now the {animals}
comes to school every day and helps teach the students how to {verbs}!"""
},
{
'title': 'The Magical Kitchen',
'template': """In a {adjectives} kitchen {places}, there lived a {colors} {animals} who was an
amazing chef. Every day, the {animals} would {verbs} while cooking {adjectives} {foods}.
The secret ingredient was always a {colors} {nouns} that made everything taste {adjectives}!
People would travel from {places} just to watch the {animals} {verbs} and eat the {adjectives} {foods}.
The kitchen became so famous that even {adjectives} {animals}s started {verbs} there!"""
}
]
def get_random_words():
"""Generate a dictionary of random words for each category"""
return {
category: random.choice(words)
for category, words in WORD_LISTS.items()
}
def generate_story():
"""Generate a complete Mad Libs story with random words"""
# Choose a random story template
story_data = random.choice(STORY_TEMPLATES)
# Get random words
words = get_random_words()
# Create the story by formatting the template with random words
story = story_data['template'].format(**words)
return {
'title': story_data['title'],
'story': story,
'words_used': words
}
# HTML template for the web interface
HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mad Libs Generator</title>
<style>
body {
font-family: 'Comic Sans MS', cursive, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
margin: 0;
padding: 20px;
min-height: 100vh;
}
.container {
max-width: 800px;
margin: 0 auto;
background: white;
padding: 30px;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0,0,0,0.3);
}
h1 {
color: #4a4a4a;
text-align: center;
margin-bottom: 30px;
font-size: 2.5em;
text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
}
.story-container {
background: #f8f9fa;
padding: 25px;
border-radius: 10px;
margin: 20px 0;
border-left: 5px solid #667eea;
}
.story-title {
color: #667eea;
font-size: 1.5em;
margin-bottom: 15px;
font-weight: bold;
}
.story-text {
font-size: 1.1em;
line-height: 1.6;
color: #333;
}
.button {
background: linear-gradient(45deg, #667eea, #764ba2);
color: white;
border: none;
padding: 15px 30px;
font-size: 1.1em;
border-radius: 25px;
cursor: pointer;
display: block;
margin: 20px auto;
transition: transform 0.2s;
}
.button:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}
.words-used {
background: #e9ecef;
padding: 15px;
border-radius: 8px;
margin-top: 20px;
font-size: 0.9em;
}
.word-category {
margin: 5px 0;
}
.word-category strong {
color: #667eea;
}
.api-info {
background: #d4edda;
border: 1px solid #c3e6cb;
padding: 15px;
border-radius: 8px;
margin-top: 20px;
}
.loading {
text-align: center;
color: #667eea;
font-style: italic;
}
</style>
</head>
<body>
<div class="container">
<h1>π Mad Libs Generator π</h1>
<div id="story-display">
{% if story_data %}
<div class="story-container">
<div class="story-title">{{ story_data.title }}</div>
<div class="story-text">{{ story_data.story }}</div>
</div>
<div class="words-used">
<strong>Words used in this story:</strong>
{% for category, word in story_data.words_used.items() %}
<div class="word-category">
<strong>{{ category.title() }}:</strong> {{ word }}
</div>
{% endfor %}
</div>
{% else %}
<div class="story-container">
<div class="story-title">Welcome to Mad Libs!</div>
<div class="story-text">
Click the button below to generate a hilarious story with random words!
</div>
</div>
{% endif %}
</div>
<button class="button" onclick="generateNewStory()">
π² Generate New Mad Libs Story
</button>
<div class="api-info">
<strong>π§ API Endpoints:</strong><br>
β’ <code>GET /</code> - This web interface<br>
β’ <code>GET /api/story</code> - Get random story as JSON<br>
β’ <code>GET /api/words</code> - Get random words as JSON
</div>
</div>
<script>
function generateNewStory() {
// Show loading message
document.getElementById('story-display').innerHTML =
'<div class="story-container"><div class="loading">π Generating your hilarious story...</div></div>';
// Fetch new story from API
fetch('/api/story')
.then(response => response.json())
.then(data => {
displayStory(data);
})
.catch(error => {
console.error('Error:', error);
document.getElementById('story-display').innerHTML =
'<div class="story-container"><div class="story-text">Oops! Something went wrong. Please try again.</div></div>';
});
}
function displayStory(storyData) {
let wordsHtml = '';
for (const [category, word] of Object.entries(storyData.words_used)) {
wordsHtml += `<div class="word-category"><strong>${category.charAt(0).toUpperCase() + category.slice(1)}:</strong> ${word}</div>`;
}
document.getElementById('story-display').innerHTML = `
<div class="story-container">
<div class="story-title">${storyData.title}</div>
<div class="story-text">${storyData.story}</div>
</div>
<div class="words-used">
<strong>Words used in this story:</strong>
${wordsHtml}
</div>
`;
}
</script>
</body>
</html>
"""
# Flask routes
@app.route('/')
def home():
"""Main page - show the Mad Libs interface"""
return render_template_string(HTML_TEMPLATE, story_data=None)
@app.route('/api/story')
def get_story():
"""API endpoint to get a random Mad Libs story as JSON"""
story_data = generate_story()
return jsonify(story_data)
@app.route('/api/words')
def get_words():
"""API endpoint to get random words as JSON"""
words = get_random_words()
return jsonify(words)
@app.route('/health')
def health_check():
"""Health check endpoint"""
return jsonify({
'status': 'healthy',
'message': 'Mad Libs Generator is running!',
'available_endpoints': ['/api/story', '/api/words', '/health']
})
if __name__ == '__main__':
print("π Starting Mad Libs Generator...")
print("π‘ Server will be available at:")
print(" β’ http://localhost:8000")
print(" β’ http://0.0.0.0:8000")
print("π API endpoints:")
print(" β’ GET / - Web interface")
print(" β’ GET /api/story - Random story JSON")
print(" β’ GET /api/words - Random words JSON")
print(" β’ GET /health - Health check")
print("\nπ Starting server...")
# Run Flask on port 8000, listening on all interfaces
app.run(host='0.0.0.0', port=8000, debug=True)