X-Git-Url: https://jfr.im/git/erebus.git/blobdiff_plain/6374d61fdeb48b31c0b8316bfbb10adc17e48276..c53f65143e93f9c41bb5041b2658dc26df69e0f8:/modules/trivia.py diff --git a/modules/trivia.py b/modules/trivia.py index fbd5abb..b4c0785 100644 --- a/modules/trivia.py +++ b/modules/trivia.py @@ -2,10 +2,6 @@ # trivia module # This file is released into the public domain; see http://unlicense.org/ -HINTTIMER = 10.0 # how long between hints -HINTNUM = 3 # how many hints to give -MAXMISSEDQUESTIONS = 25 # how many missed questions before game stops - # module info modinfo = { 'author': 'Erebus Team', @@ -31,10 +27,8 @@ def modstop(*args, **kwargs): import json, random, threading, re, time try: - import twitter - hastwitter = True -except ImportError: - hastwitter = False + import twitter +except: pass # doesn't matter if we don't have twitter, updating the status just will fall through the try-except if so... def findnth(haystack, needle, n): #http://stackoverflow.com/a/1884151 parts = haystack.split(needle, n+1) @@ -43,7 +37,7 @@ def findnth(haystack, needle, n): #http://stackoverflow.com/a/1884151 return len(haystack)-len(parts[-1])-len(needle) class TriviaState(object): - def __init__(self, questionfile, parent=None): + def __init__(self, questionfile, parent=None, pointvote=False): self.parent = parent self.questionfile = questionfile self.db = json.load(open(questionfile, "r")) @@ -58,6 +52,15 @@ class TriviaState(object): self.gameover = False self.missedquestions = 0 + if pointvote: + self.getchan().msg("Vote for the next round target points! Options: %s. Vote using !vote " % (', '.join([str(x) for x in self.db['targetoptions']]))) + self.getchan().msg("You have %s seconds." % (self.db['votetimer'])) + self.voteamounts = dict([(x, 0) for x in self.db['targetoptions']]) # make a dict {pointsoptionA: 0, pointsoptionB: 0, ...} + self.pointvote = threading.Timer(self.db['votetimer'], self.endPointVote) + self.pointvote.start() + else: + self.pointvote = None + def __del__(self): self.closeshop() def closeshop(self): @@ -88,11 +91,11 @@ class TriviaState(object): self.hintsgiven += 1 - if hintnum < HINTNUM: - self.steptimer = threading.Timer(HINTTIMER, self.nexthint, args=[hintnum+1]) + if hintnum < self.db['hintnum']: + self.steptimer = threading.Timer(self.db['hinttimer'], self.nexthint, args=[hintnum+1]) self.steptimer.start() else: - self.steptimer = threading.Timer(HINTTIMER, self.nextquestion, args=[True]) + self.steptimer = threading.Timer(self.db['hinttimer'], self.nextquestion, args=[True]) self.steptimer.start() def doGameOver(self): @@ -114,20 +117,32 @@ class TriviaState(object): stop() self.closeshop() - if hastwitter: + try: t = twitter.Twitter(auth=twitter.OAuth(self.getbot().parent.cfg.get('trivia', 'token'), self.getbot().parent.cfg.get('trivia', 'token_sec'), self.getbot().parent.cfg.get('trivia', 'con'), self.getbot().parent.cfg.get('trivia', 'con_sec'))) t.statuses.update(status="Round is over! The winner was %s" % (winner)) + except: pass #don't care if errors happen updating twitter. - self.__init__(self.questionfile, self.parent) + self.__init__(self.questionfile, self.parent, True) + + def endPointVote(self): + self.getchan().msg("Voting has ended!") + votelist = sorted(self.voteamounts.items(), key=lambda item: item[1]) #sort into list of tuples: [(option, number_of_votes), ...] + for i in range(len(votelist)-1): + item = votelist[i] + self.getchan().msg("%s place: %s (%s votes)" % (len(votelist)-i, item[0], item[1])) + self.getchan().msg("Aaaaand! The next round will be to \002%s\002 points! (%s votes)" % (votelist[-1][0], votelist[-1][1])) + + self.db['target'] = votelist[-1][0] + self.pointvote = None def nextquestion(self, qskipped=False, iteration=0): if self.gameover == True: return self.doGameOver() if qskipped: - self.getbot().msg(self.getchan(), "\00304Fail! The correct answer was: %s" % (self.hintanswer)) + self.getchan().msg("\00304Fail! The correct answer was: %s" % (self.hintanswer)) self.missedquestions += 1 else: self.missedquestions = 0 @@ -140,7 +155,7 @@ class TriviaState(object): self.revealpossibilities = None self.reveal = None - if self.missedquestions > MAXMISSEDQUESTIONS: + if self.missedquestions > self.db['maxmissedquestions']: stop() self.getbot().msg(self.getchan(), "%d questions unanswered! Stopping the game.") @@ -170,7 +185,7 @@ class TriviaState(object): if isinstance(self.curq['answer'], basestring): self.hintanswer = self.curq['answer'] else: self.hintanswer = random.choice(self.curq['answer']) - self.steptimer = threading.Timer(HINTTIMER, self.nexthint, args=[1]) + self.steptimer = threading.Timer(self.db['hinttimer'], self.nexthint, args=[1]) self.steptimer.start() def checkanswer(self, answer): @@ -181,16 +196,16 @@ class TriviaState(object): else: # assume it's a list or something. return answer.lower() in self.curq['answer'] - def addpoint(self, _user, count=1): - _user = str(_user) - user = _user.lower() + def addpoint(self, user_obj, count=1): + user_nick = str(user_obj) + user = user_nick.lower() # save this separately as we use both if user in self.db['users']: self.db['users'][user]['points'] += count else: - self.db['users'][user] = {'points': count, 'realnick': _user, 'rank': len(self.db['ranks'])} + self.db['users'][user] = {'points': count, 'realnick': user_nick, 'rank': len(self.db['ranks'])} self.db['ranks'].append(user) - self.db['ranks'].sort(key=lambda nick: state.db['users'][nick]['points'], reverse=True) + self.db['ranks'].sort(key=lambda nick: state.db['users'][nick]['points'], reverse=True) #re-sort ranks, rather than dealing with anything more efficient for i in range(0, len(self.db['ranks'])): nick = self.db['ranks'][i] self.db['users'][nick]['rank'] = i @@ -294,8 +309,10 @@ def cmd_start(bot, user, chan, realtarget, *args): if chan == realtarget: replyto = chan else: replyto = user - if state.curq is None: + if state.curq is None and state.pointvote is None: state.nextquestion() + elif state.pointvote is not None: + bot.msg(replyto, "There's a vote in progress!") else: bot.msg(replyto, "Game is already started!") @@ -347,21 +364,83 @@ def cmd_settarget(bot, user, chan, realtarget, *args): except: bot.msg(user, "Failed to set target.") +@lib.hook('maxmissed', clevel=lib.MASTER, needchan=False) +def cmd_maxmissed(bot, user, chan, realtarget, *args): + try: + state.db['maxmissedquestions'] = int(args[0]) + bot.msg(state.db['chan'], "Max missed questions before round ends has been changed to %s." % (state.db['maxmissedquestions'])) + except: + bot.msg(user, "Failed to set maxmissed.") + +@lib.hook('hinttimer', clevel=lib.MASTER, needchan=False) +def cmd_hinttimer(bot, user, chan, realtarget, *args): + try: + state.db['hinttimer'] = float(args[0]) + bot.msg(state.db['chan'], "Time between hints has been changed to %s." % (state.db['hinttimer'])) + except: + bot.msg(user, "Failed to set hint timer.") + +@lib.hook('hintnum', clevel=lib.MASTER, needchan=False) +def cmd_hintnum(bot, user, chan, realtarget, *args): + try: + state.db['hintnum'] = int(args[0]) + bot.msg(state.db['chan'], "Max number of hints has been changed to %s." % (state.db['hintnum'])) + except: + bot.msg(user, "Failed to set hintnum.") + +@lib.hook('findq', clevel=lib.KNOWN, needchan=False) +def cmd_findquestion(bot, user, chan, realtarget, *args): + matches = [str(i) for i in range(len(state.db['questions'])) if state.db['questions'][i]['question'] == ' '.join(args)] #FIXME: looser equality check + if len(matches) > 1: + bot.msg(user, "Multiple matches: %s" % (', '.join(matches))) + elif len(matches) == 1: + bot.msg(user, "One match: %s" % (matches[0])) + else: + bot.msg(user, "No match.") + +@lib.hook('delq', clevel=lib.OP, needchan=False) +@lib.hook('deleteq', clevel=lib.OP, needchan=False) +def cmd_deletequestion(bot, user, chan, realtarget, *args): + try: + backup = state.db['questions'][int(args[0])] + del state.db['questions'][int(args[0])] + bot.msg(user, "Deleted %s*%s" % (backup['question'], backup['answer'])) + except: + bot.msg(user, "Couldn't delete that question.") + +@lib.hook('addq', clevel=lib.OP, needchan=False) +def cmd_addquestion(bot, user, chan, realtarget, *args): + line = ' '.join([str(arg) for arg in args]) + linepieces = line.split('*') + if len(linepieces) < 2: + bot.msg(user, "Error: need *") + return + question = linepieces[0].strip() + answer = linepieces[1].strip() + state.db['questions'].append({'question':question,'answer':answer}) + bot.msg(user, "Done. Question is #%s" % (len(state.db['questions'])-1)) + + @lib.hook('triviahelp', needchan=False) def cmd_triviahelp(bot, user, chan, realtarget, *args): - bot.msg(user, "POINTS []") - bot.msg(user, "START") - bot.msg(user, "RANK []") - bot.msg(user, "TOP10") - + bot.msg(user, "START") + bot.msg(user, "TOP10") + bot.msg(user, "POINTS []") + bot.msg(user, "RANK []") if bot.parent.channel(state.db['chan']).levelof(user.auth) >= lib.KNOWN: - bot.msg(user, "SKIP (>=KNOWN )") - bot.msg(user, "STOP (>=KNOWN )") + bot.msg(user, "SKIP (>=KNOWN )") + bot.msg(user, "STOP (>=KNOWN )") + bot.msg(user, "FINDQ (>=KNOWN )") if bot.parent.channel(state.db['chan']).levelof(user.auth) >= lib.OP: - bot.msg(user, "GIVE [] (>=OP )") - bot.msg(user, "SETNEXT * (>=OP )") + bot.msg(user, "GIVE [] (>=OP )") + bot.msg(user, "SETNEXT * (>=OP )") + bot.msg(user, "ADDQ * (>=OP )") + bot.msg(user, "DELETEQ * (>=OP ) [aka DELQ]") if bot.parent.channel(state.db['chan']).levelof(user.auth) >= lib.MASTER: - bot.msg(user, "SETTARGET (>=MASTER)") + bot.msg(user, "SETTARGET (>=MASTER)") + bot.msg(user, "MAXMISSED (>=MASTER)") + bot.msg(user, "HINTTIMER (>=MASTER)") + bot.msg(user, "HINTNUM (>=MASTER)") @lib.hooknum(417) def num_417(bot, textline):