]> jfr.im git - erebus.git/blame - modules/trivia.py
added ability for bot to update a trivia hall-of-fame
[erebus.git] / modules / trivia.py
CommitLineData
80d02bd8 1# Erebus IRC bot - Author: Erebus Team
c695f740 2# trivia module
80d02bd8 3# This file is released into the public domain; see http://unlicense.org/
4
5# module info
6modinfo = {
7 'author': 'Erebus Team',
8 'license': 'public domain',
9 'compatible': [1], # compatible module API versions
10 'depends': [], # other modules required to work properly?
11}
12
13# preamble
14import modlib
15lib = modlib.modlib(__name__)
16def modstart(parent, *args, **kwargs):
9557ee54 17 state.parent = parent
80d02bd8 18 return lib.modstart(parent, *args, **kwargs)
19def modstop(*args, **kwargs):
c0eee1b4 20 global state
fadbf980 21 stop()
77c61775 22 state.closeshop()
80d02bd8 23 del state
24 return lib.modstop(*args, **kwargs)
25
26# module code
7bd5e7d5 27import json, random, threading, re, time, datetime
b16b8c05 28
c0eee1b4 29try:
c53f6514 30 import twitter
31except: pass # doesn't matter if we don't have twitter, updating the status just will fall through the try-except if so...
c0eee1b4 32
b16b8c05 33def findnth(haystack, needle, n): #http://stackoverflow.com/a/1884151
34 parts = haystack.split(needle, n+1)
35 if len(parts)<=n+1:
36 return -1
37 return len(haystack)-len(parts[-1])-len(needle)
80d02bd8 38
39class TriviaState(object):
c53f6514 40 def __init__(self, questionfile, parent=None, pointvote=False):
77c61775 41 self.parent = parent
80d02bd8 42 self.questionfile = questionfile
43 self.db = json.load(open(questionfile, "r"))
9557ee54 44 self.chan = self.db['chan']
45 self.curq = None
c695f740 46 self.nextq = None
b16b8c05 47 self.steptimer = None
48 self.hintstr = None
49 self.hintanswer = None
77c61775 50 self.hintsgiven = 0
b16b8c05 51 self.revealpossibilities = None
77c61775 52 self.gameover = False
c0eee1b4 53 self.missedquestions = 0
80d02bd8 54
7bd5e7d5 55 if 'starttime' not in self.db or self.db['starttime'] is None:
56 self.db['starttime'] = time.time()
57
c53f6514 58 if pointvote:
59 self.getchan().msg("Vote for the next round target points! Options: %s. Vote using !vote <choice>" % (', '.join([str(x) for x in self.db['targetoptions']])))
60 self.getchan().msg("You have %s seconds." % (self.db['votetimer']))
61 self.voteamounts = dict([(x, 0) for x in self.db['targetoptions']]) # make a dict {pointsoptionA: 0, pointsoptionB: 0, ...}
62 self.pointvote = threading.Timer(self.db['votetimer'], self.endPointVote)
63 self.pointvote.start()
64 else:
65 self.pointvote = None
66
80d02bd8 67 def __del__(self):
77c61775 68 self.closeshop()
69 def closeshop(self):
b16b8c05 70 if threading is not None and threading._Timer is not None and isinstance(self.steptimer, threading._Timer):
71 self.steptimer.cancel()
c695f740 72 if json is not None and json.dump is not None:
6374d61f 73 json.dump(self.db, open(self.questionfile, "w"))#, indent=4, separators=(',', ': '))
80d02bd8 74
fadbf980 75 def getchan(self):
76 return self.parent.channel(self.chan)
77 def getbot(self):
78 return self.getchan().bot
79
b16b8c05 80 def nexthint(self, hintnum):
b16b8c05 81 answer = self.hintanswer
82
b5c89dfb 83 if self.hintstr is None or self.revealpossibilities is None or self.reveal is None:
b16b8c05 84 self.hintstr = list(re.sub(r'[a-zA-Z0-9]', '*', answer))
85 self.revealpossibilities = range(''.join(self.hintstr).count('*'))
b5c89dfb 86 self.reveal = int(''.join(self.hintstr).count('*') * (7/24.0))
b16b8c05 87
b5c89dfb 88 for i in range(self.reveal):
b16b8c05 89 revealcount = random.choice(self.revealpossibilities)
90 revealloc = findnth(''.join(self.hintstr), '*', revealcount)
91 self.revealpossibilities.remove(revealcount)
92 self.hintstr[revealloc] = answer[revealloc]
6374d61f 93 self.parent.channel(self.chan).bot.msg(self.chan, "\00304,01Here's a hint: %s" % (''.join(self.hintstr)))
b16b8c05 94
77c61775 95 self.hintsgiven += 1
96
c4763e66 97 if hintnum < self.db['hintnum']:
98 self.steptimer = threading.Timer(self.db['hinttimer'], self.nexthint, args=[hintnum+1])
b16b8c05 99 self.steptimer.start()
100 else:
c4763e66 101 self.steptimer = threading.Timer(self.db['hinttimer'], self.nextquestion, args=[True])
b16b8c05 102 self.steptimer.start()
103
77c61775 104 def doGameOver(self):
7bd5e7d5 105 msg = self.getchan().msg
77c61775 106 def person(num): return self.db['users'][self.db['ranks'][num]]['realnick']
7bd5e7d5 107 def pts(num): return str(self.db['users'][self.db['ranks'][num]]['points'])
c0eee1b4 108 winner = person(0)
77c61775 109 try:
110 msg("\00312THE GAME IS OVER!!!")
111 msg("THE WINNER IS: %s (%s)" % (person(0), pts(0)))
112 msg("2ND PLACE: %s (%s)" % (person(1), pts(1)))
113 msg("3RD PLACE: %s (%s)" % (person(2), pts(2)))
114 [msg("%dth place: %s (%s)" % (i+1, person(i), pts(i))) for i in range(3,10)]
115 except IndexError: pass
c0eee1b4 116 except Exception as e: msg("DERP! %r" % (e))
117
7bd5e7d5 118 if self.db['hofpath'] is not None and self.db['hofpath'] != '':
119 self.writeHof()
120
77c61775 121 self.db['users'] = {}
122 self.db['ranks'] = []
123 stop()
124 self.closeshop()
c0eee1b4 125
c53f6514 126 try:
c0eee1b4 127 t = twitter.Twitter(auth=twitter.OAuth(self.getbot().parent.cfg.get('trivia', 'token'),
128 self.getbot().parent.cfg.get('trivia', 'token_sec'),
129 self.getbot().parent.cfg.get('trivia', 'con'),
130 self.getbot().parent.cfg.get('trivia', 'con_sec')))
131 t.statuses.update(status="Round is over! The winner was %s" % (winner))
c53f6514 132 except: pass #don't care if errors happen updating twitter.
133
134 self.__init__(self.questionfile, self.parent, True)
135
7bd5e7d5 136 def writeHof(self):
137 def person(num):
138 try: return self.db['users'][self.db['ranks'][num]]['realnick']
139 except: return "none"
140 def pts(num):
141 try: return str(self.db['users'][self.db['ranks'][num]]['points'])
142 except: return 0
143
144 try:
145 f = open(self.db['hofpath'], 'rb+')
146 for i in range(self.db['hoflines']): #skip this many lines
147 f.readline()
148 insertpos = f.tell()
149 fcontents = f.read()
150 f.seek(insertpos)
151 f.write((self.db['hofformat']+"\n") % {
152 'date': time.strftime("%F", time.gmtime()),
153 'duration': str(datetime.timedelta(seconds=time.time()-self.db['starttime'])),
154 'targetscore': self.db['target'],
155 'firstperson': person(0),
156 'firstscore': pts(0),
157 'secondperson': person(1),
158 'secondscore': pts(1),
159 'thirdperson': person(2),
160 'thirdscore': pts(2),
161 })
162 f.write(fcontents)
163 return True
164 except Exception as e:
165 raise e
166 return False
167 finally:
168 f.close()
169
c53f6514 170 def endPointVote(self):
171 self.getchan().msg("Voting has ended!")
172 votelist = sorted(self.voteamounts.items(), key=lambda item: item[1]) #sort into list of tuples: [(option, number_of_votes), ...]
173 for i in range(len(votelist)-1):
174 item = votelist[i]
175 self.getchan().msg("%s place: %s (%s votes)" % (len(votelist)-i, item[0], item[1]))
176 self.getchan().msg("Aaaaand! The next round will be to \002%s\002 points! (%s votes)" % (votelist[-1][0], votelist[-1][1]))
c0eee1b4 177
c53f6514 178 self.db['target'] = votelist[-1][0]
179 self.pointvote = None
77c61775 180
38b29993 181 self.nextquestion() #start the game!
182
b5c89dfb 183 def nextquestion(self, qskipped=False, iteration=0):
77c61775 184 if self.gameover == True:
185 return self.doGameOver()
fadbf980 186 if qskipped:
c53f6514 187 self.getchan().msg("\00304Fail! The correct answer was: %s" % (self.hintanswer))
c0eee1b4 188 self.missedquestions += 1
189 else:
190 self.missedquestions = 0
fadbf980 191
b16b8c05 192 if isinstance(self.steptimer, threading._Timer):
193 self.steptimer.cancel()
c0eee1b4 194
b16b8c05 195 self.hintstr = None
77c61775 196 self.hintsgiven = 0
b16b8c05 197 self.revealpossibilities = None
b5c89dfb 198 self.reveal = None
b16b8c05 199
c4763e66 200 if self.missedquestions > self.db['maxmissedquestions']:
c0eee1b4 201 stop()
202 self.getbot().msg(self.getchan(), "%d questions unanswered! Stopping the game.")
b16b8c05 203
c695f740 204 if state.nextq is not None:
205 nextq = state.nextq
c695f740 206 state.nextq = None
207 else:
208 nextq = random.choice(self.db['questions'])
b5c89dfb 209
210 if nextq['question'][0] == "!":
211 nextq = specialQuestion(nextq)
212
213 if iteration < 10 and 'lastasked' in nextq and nextq['lastasked'] - time.time() < 24*60*60:
214 return self.nextquestion(iteration=iteration+1) #short-circuit to pick another question
215 nextq['lastasked'] = time.time()
216
217 nextq['answer'] = nextq['answer'].lower()
c695f740 218
6374d61f 219 qtext = "\00304,01Next up: "
c695f740 220 qary = nextq['question'].split(None)
221 for qword in qary:
6374d61f 222 qtext += "\00304,01"+qword+"\00301,01"+chr(random.randrange(0x61,0x7A)) #a-z
fadbf980 223 self.getbot().msg(self.chan, qtext)
80d02bd8 224
b5c89dfb 225 self.curq = nextq
226
c0eee1b4 227 if isinstance(self.curq['answer'], basestring): self.hintanswer = self.curq['answer']
228 else: self.hintanswer = random.choice(self.curq['answer'])
229
c4763e66 230 self.steptimer = threading.Timer(self.db['hinttimer'], self.nexthint, args=[1])
b16b8c05 231 self.steptimer.start()
232
80d02bd8 233 def checkanswer(self, answer):
9557ee54 234 if self.curq is None:
235 return False
236 elif isinstance(self.curq['answer'], basestring):
80d02bd8 237 return answer.lower() == self.curq['answer']
238 else: # assume it's a list or something.
239 return answer.lower() in self.curq['answer']
77c61775 240
c53f6514 241 def addpoint(self, user_obj, count=1):
242 user_nick = str(user_obj)
243 user = user_nick.lower() # save this separately as we use both
80d02bd8 244 if user in self.db['users']:
245 self.db['users'][user]['points'] += count
246 else:
c53f6514 247 self.db['users'][user] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])}
9557ee54 248 self.db['ranks'].append(user)
80d02bd8 249
c53f6514 250 self.db['ranks'].sort(key=lambda nick: state.db['users'][nick]['points'], reverse=True) #re-sort ranks, rather than dealing with anything more efficient
6374d61f 251 for i in range(0, len(self.db['ranks'])):
252 nick = self.db['ranks'][i]
253 self.db['users'][nick]['rank'] = i
77c61775 254
255 if self.db['users'][user]['points'] >= state.db['target']:
256 self.gameover = True
257
80d02bd8 258 return self.db['users'][user]['points']
259
260 def points(self, user):
9557ee54 261 user = str(user).lower()
80d02bd8 262 if user in self.db['users']:
263 return self.db['users'][user]['points']
264 else:
265 return 0
266
267 def rank(self, user):
c695f740 268 user = str(user).lower()
fadbf980 269 if user in self.db['users']:
270 return self.db['users'][user]['rank']+1
271 else:
272 return len(self.db['users'])+1
77c61775 273
c695f740 274 def targetuser(self, user):
77c61775 275 if len(self.db['ranks']) == 0: return "no one is ranked!"
276
c695f740 277 user = str(user).lower()
fadbf980 278 if user in self.db['users']:
279 rank = self.db['users'][user]['rank']
280 if rank == 0:
281 return "you're in the lead!"
282 else:
283 return self.db['ranks'][rank-1]
c695f740 284 else:
fadbf980 285 return self.db['ranks'][-1]
c695f740 286 def targetpoints(self, user):
77c61775 287 if len(self.db['ranks']) == 0: return 0
288
c695f740 289 user = str(user).lower()
fadbf980 290 if user in self.db['users']:
291 rank = self.db['users'][user]['rank']
292 if rank == 0:
293 return "N/A"
294 else:
295 return self.db['users'][self.db['ranks'][rank-1]]['points']
c695f740 296 else:
fadbf980 297 return self.db['users'][self.db['ranks'][-1]]['points']
80d02bd8 298
c695f740 299state = TriviaState("/home/jrunyon/erebus/modules/trivia.json") #TODO get path from config
9557ee54 300
80d02bd8 301@lib.hookchan(state.db['chan'])
302def trivia_checkanswer(bot, user, chan, *args):
80d02bd8 303 line = ' '.join([str(arg) for arg in args])
304 if state.checkanswer(line):
6374d61f 305 bot.msg(chan, "\00312%s\003 has it! The answer was \00312%s\003. New score: %d. Rank: %d. Target: %s (%s)." % (user, line, state.addpoint(user), state.rank(user), state.targetuser(user), state.targetpoints(user)))
77c61775 306 if state.hintsgiven == 0:
6374d61f 307 bot.msg(chan, "\00312%s\003 got an extra point for getting it before the hints! New score: %d." % (user, state.addpoint(user)))
9557ee54 308 state.nextquestion()
80d02bd8 309
f6252f1c 310@lib.hook('points', needchan=False)
80d02bd8 311def cmd_points(bot, user, chan, realtarget, *args):
c695f740 312 if chan == realtarget: replyto = chan
80d02bd8 313 else: replyto = user
314
315 if len(args) != 0: who = args[0]
316 else: who = user
317
318 bot.msg(replyto, "%s has %d points." % (who, state.points(who)))
319
f6252f1c 320@lib.hook('give', clevel=lib.OP, needchan=False)
80d02bd8 321@lib.argsGE(1)
322def cmd_give(bot, user, chan, realtarget, *args):
80d02bd8 323 whoto = args[0]
c695f740 324 if len(args) > 1:
325 numpoints = int(args[1])
326 else:
327 numpoints = 1
328 balance = state.addpoint(whoto, numpoints)
fadbf980 329
c695f740 330 bot.msg(chan, "%s gave %s %d points. New balance: %d" % (user, whoto, numpoints, balance))
331
f6252f1c 332@lib.hook('setnext', clevel=lib.OP, needchan=False)
c695f740 333@lib.argsGE(1)
334def cmd_setnext(bot, user, chan, realtarget, *args):
335 line = ' '.join([str(arg) for arg in args])
336 linepieces = line.split('*')
b5c89dfb 337 if len(linepieces) < 2:
338 bot.msg(user, "Error: need <question>*<answer>")
339 return
c695f740 340 question = linepieces[0].strip()
341 answer = linepieces[1].strip()
342 state.nextq = {'question':question,'answer':answer}
343 bot.msg(user, "Done.")
344
f6252f1c 345@lib.hook('skip', clevel=lib.KNOWN, needchan=False)
c695f740 346def cmd_skip(bot, user, chan, realtarget, *args):
c0eee1b4 347 state.nextquestion(True)
c695f740 348
f6252f1c 349@lib.hook('start', needchan=False)
c695f740 350def cmd_start(bot, user, chan, realtarget, *args):
351 if chan == realtarget: replyto = chan
352 else: replyto = user
353
c53f6514 354 if state.curq is None and state.pointvote is None:
c695f740 355 state.nextquestion()
c53f6514 356 elif state.pointvote is not None:
357 bot.msg(replyto, "There's a vote in progress!")
c695f740 358 else:
359 bot.msg(replyto, "Game is already started!")
360
6374d61f 361#FIXME @lib.hook('stop', clevel=lib.KNOWN, needchan=False)
362@lib.hook('stop', needchan=False) #FIXME
c695f740 363def cmd_stop(bot, user, chan, realtarget, *args):
fadbf980 364 if stop():
365 bot.msg(state.chan, "Game stopped by %s" % (user))
366 else:
367 bot.msg(user, "Game isn't running.")
c695f740 368
fadbf980 369def stop():
c695f740 370 if state.curq is not None:
371 state.curq = None
c0eee1b4 372 try:
b16b8c05 373 state.steptimer.cancel()
c0eee1b4 374 except Exception as e:
375 print "!!! steptimer.cancel(): e"
fadbf980 376 return True
c695f740 377 else:
fadbf980 378 return False
80d02bd8 379
f6252f1c 380@lib.hook('rank', needchan=False)
80d02bd8 381def cmd_rank(bot, user, chan, realtarget, *args):
c695f740 382 if chan == realtarget: replyto = chan
80d02bd8 383 else: replyto = user
384
c695f740 385 if len(args) != 0: who = args[0]
386 else: who = user
387
77c61775 388 bot.msg(replyto, "%s is in %d place (%s points). Target is: %s (%s points)." % (who, state.rank(who), state.points(who), state.targetuser(who), state.targetpoints(who)))
fadbf980 389
f6252f1c 390@lib.hook('top10', needchan=False)
fadbf980 391def cmd_top10(bot, user, chan, realtarget, *args):
77c61775 392 if len(state.db['ranks']) == 0:
393 return bot.msg(state.db['chan'], "No one is ranked!")
fadbf980 394
395 replylist = []
396 for nick in state.db['ranks'][0:10]:
397 user = state.db['users'][nick]
77c61775 398 replylist.append("%s (%s)" % (user['realnick'], user['points']))
399 bot.msg(state.db['chan'], ', '.join(replylist))
400
f6252f1c 401@lib.hook('settarget', clevel=lib.MASTER, needchan=False)
77c61775 402def cmd_settarget(bot, user, chan, realtarget, *args):
403 try:
404 state.db['target'] = int(args[0])
405 bot.msg(state.db['chan'], "Target has been changed to %s points!" % (state.db['target']))
38b29993 406
7bd5e7d5 407 if state.pointvote is not None:
408 state.pointvote.cancel()
409 state.pointvote = None
38b29993 410 bot.msg(state.db['chan'], "Vote has been cancelled!")
7bd5e7d5 411 except Exception as e:
412 print e
77c61775 413 bot.msg(user, "Failed to set target.")
414
38b29993 415@lib.hook('vote', needchan=False)
416def cmd_vote(bot, user, chan, realtarget, *args):
7bd5e7d5 417 if state.pointvote is not None:
38b29993 418 if int(args[0]) in state.voteamounts:
419 state.voteamounts[int(args[0])] += 1
420 bot.msg(user, "Your vote has been recorded.")
421 else:
422 bot.msg(user, "Sorry - that's not an option!")
423 else:
424 bot.msg(user, "There's no vote in progress.")
425
c4763e66 426@lib.hook('maxmissed', clevel=lib.MASTER, needchan=False)
427def cmd_maxmissed(bot, user, chan, realtarget, *args):
428 try:
429 state.db['maxmissedquestions'] = int(args[0])
430 bot.msg(state.db['chan'], "Max missed questions before round ends has been changed to %s." % (state.db['maxmissedquestions']))
431 except:
432 bot.msg(user, "Failed to set maxmissed.")
433
434@lib.hook('hinttimer', clevel=lib.MASTER, needchan=False)
435def cmd_hinttimer(bot, user, chan, realtarget, *args):
436 try:
437 state.db['hinttimer'] = float(args[0])
438 bot.msg(state.db['chan'], "Time between hints has been changed to %s." % (state.db['hinttimer']))
439 except:
440 bot.msg(user, "Failed to set hint timer.")
441
442@lib.hook('hintnum', clevel=lib.MASTER, needchan=False)
443def cmd_hintnum(bot, user, chan, realtarget, *args):
444 try:
445 state.db['hintnum'] = int(args[0])
446 bot.msg(state.db['chan'], "Max number of hints has been changed to %s." % (state.db['hintnum']))
447 except:
448 bot.msg(user, "Failed to set hintnum.")
449
450@lib.hook('findq', clevel=lib.KNOWN, needchan=False)
451def cmd_findquestion(bot, user, chan, realtarget, *args):
452 matches = [str(i) for i in range(len(state.db['questions'])) if state.db['questions'][i]['question'] == ' '.join(args)] #FIXME: looser equality check
453 if len(matches) > 1:
454 bot.msg(user, "Multiple matches: %s" % (', '.join(matches)))
455 elif len(matches) == 1:
456 bot.msg(user, "One match: %s" % (matches[0]))
457 else:
458 bot.msg(user, "No match.")
459
460@lib.hook('delq', clevel=lib.OP, needchan=False)
461@lib.hook('deleteq', clevel=lib.OP, needchan=False)
462def cmd_deletequestion(bot, user, chan, realtarget, *args):
463 try:
464 backup = state.db['questions'][int(args[0])]
465 del state.db['questions'][int(args[0])]
466 bot.msg(user, "Deleted %s*%s" % (backup['question'], backup['answer']))
467 except:
468 bot.msg(user, "Couldn't delete that question.")
469
470@lib.hook('addq', clevel=lib.OP, needchan=False)
471def cmd_addquestion(bot, user, chan, realtarget, *args):
472 line = ' '.join([str(arg) for arg in args])
473 linepieces = line.split('*')
474 if len(linepieces) < 2:
475 bot.msg(user, "Error: need <question>*<answer>")
476 return
477 question = linepieces[0].strip()
478 answer = linepieces[1].strip()
479 state.db['questions'].append({'question':question,'answer':answer})
480 bot.msg(user, "Done. Question is #%s" % (len(state.db['questions'])-1))
481
482
f6252f1c 483@lib.hook('triviahelp', needchan=False)
77c61775 484def cmd_triviahelp(bot, user, chan, realtarget, *args):
c4763e66 485 bot.msg(user, "START")
486 bot.msg(user, "TOP10")
487 bot.msg(user, "POINTS [<user>]")
488 bot.msg(user, "RANK [<user>]")
77c61775 489 if bot.parent.channel(state.db['chan']).levelof(user.auth) >= lib.KNOWN:
c4763e66 490 bot.msg(user, "SKIP (>=KNOWN )")
491 bot.msg(user, "STOP (>=KNOWN )")
492 bot.msg(user, "FINDQ <question> (>=KNOWN )")
77c61775 493 if bot.parent.channel(state.db['chan']).levelof(user.auth) >= lib.OP:
c4763e66 494 bot.msg(user, "GIVE <user> [<points>] (>=OP )")
495 bot.msg(user, "SETNEXT <q>*<a> (>=OP )")
496 bot.msg(user, "ADDQ <q>*<a> (>=OP )")
497 bot.msg(user, "DELETEQ <q>*<a> (>=OP ) [aka DELQ]")
77c61775 498 if bot.parent.channel(state.db['chan']).levelof(user.auth) >= lib.MASTER:
c4763e66 499 bot.msg(user, "SETTARGET <points> (>=MASTER)")
500 bot.msg(user, "MAXMISSED <questions> (>=MASTER)")
501 bot.msg(user, "HINTTIMER <float seconds> (>=MASTER)")
502 bot.msg(user, "HINTNUM <hints> (>=MASTER)")
b5c89dfb 503
6374d61f 504@lib.hooknum(417)
505def num_417(bot, textline):
506 bot.msg(state.db['chan'], "Whoops, it looks like that question didn't quite go through! (E:417). Let's try another...")
507 state.nextquestion(False)
508
b5c89dfb 509
510def specialQuestion(oldq):
511 newq = {'question': oldq['question'], 'answer': oldq['answer']}
512 qtype = oldq['question'].upper()
513
514 if qtype == "!MONTH":
515 newq['question'] = "What month is it currently (in UTC)?"
7bd5e7d5 516 newq['answer'] = time.strftime("%B", time.gmtime()).lower()
b5c89dfb 517 elif qtype == "!MATH+":
518 randnum1 = random.randrange(0, 11)
519 randnum2 = random.randrange(0, 11)
520 newq['question'] = "What is %d + %d?" % (randnum1, randnum2)
521 newq['answer'] = spellout(randnum1+randnum2)
522 return newq
523
524def spellout(num):
525 return [
526 "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
527 "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
528 "sixteen", "seventeen", "eighteen", "nineteen", "twenty"
529 ][num]