]> jfr.im git - erebus.git/commitdiff
trivia v1 done
authorzonidjan <redacted>
Fri, 14 Aug 2015 22:13:35 +0000 (17:13 -0500)
committerzonidjan <redacted>
Fri, 14 Aug 2015 22:13:35 +0000 (17:13 -0500)
modules/trivia.py

index e0bc0dfa994a4e95504953d2ad6bc974e3a24f99..bd0889a13512b96a8d732e25ac7137653d7dc269 100644 (file)
@@ -5,13 +5,11 @@
 #TODO:
 #      stop game after X unanswered questions
 #      bonus points
-#      ability to REDUCE users points
-#      dynamic questions
 #      v2
 #              team play
 #              statistics
 
-HINTTIMER = 2.0
+HINTTIMER = 15.0
 HINTNUM = 3
 
 # module info
@@ -30,6 +28,7 @@ def modstart(parent, *args, **kwargs):
        return lib.modstart(parent, *args, **kwargs)
 def modstop(*args, **kwargs):
        stop()
+       state.closeshop()
        global state
        del state
        return lib.modstop(*args, **kwargs)
@@ -44,7 +43,8 @@ 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):
+       def __init__(self, questionfile, parent=None):
+               self.parent = parent
                self.questionfile = questionfile
                self.db = json.load(open(questionfile, "r"))
                self.chan = self.db['chan']
@@ -53,9 +53,13 @@ class TriviaState(object):
                self.steptimer = None
                self.hintstr = None
                self.hintanswer = None
+               self.hintsgiven = 0
                self.revealpossibilities = None
+               self.gameover = False
 
        def __del__(self):
+               self.closeshop()
+       def closeshop(self):
                if threading is not None and threading._Timer is not None and isinstance(self.steptimer, threading._Timer):
                        self.steptimer.cancel()
                if json is not None and json.dump is not None:
@@ -84,6 +88,8 @@ class TriviaState(object):
                        self.hintstr[revealloc] = answer[revealloc]
                self.parent.channel(self.chan).bot.msg(self.chan, "Here's a hint: %s" % (''.join(self.hintstr)))
 
+               self.hintsgiven += 1
+
                if hintnum < HINTNUM:
                        self.steptimer = threading.Timer(HINTTIMER, self.nexthint, args=[hintnum+1])
                        self.steptimer.start()
@@ -91,7 +97,28 @@ class TriviaState(object):
                        self.steptimer = threading.Timer(HINTTIMER, self.nextquestion, args=[True])
                        self.steptimer.start()
 
+       def doGameOver(self):
+               def msg(line): self.getbot().msg(self.getchan(), line)
+               def person(num): return self.db['users'][self.db['ranks'][num]]['realnick']
+               def pts(num): return self.db['users'][self.db['ranks'][num]]['points']
+               try:
+                       msg("\00312THE GAME IS OVER!!!")
+                       msg("THE WINNER IS: %s (%s)" % (person(0), pts(0)))
+                       msg("2ND PLACE: %s (%s)" % (person(1), pts(1)))
+                       msg("3RD PLACE: %s (%s)" % (person(2), pts(2)))
+                       [msg("%dth place: %s (%s)" % (i+1, person(i), pts(i))) for i in range(3,10)]
+               except IndexError: pass
+               except Exception as e:
+                       msg("DERP! %r" % (e))
+               self.db['users'] = {}
+               self.db['ranks'] = []
+               stop()
+               self.closeshop()
+               self.__init__(self.questionfile, self.parent)
+
        def nextquestion(self, qskipped=False):
+               if self.gameover == True:
+                       return self.doGameOver()
                if qskipped:
                        self.getbot().msg(self.getchan(), "Fail! The correct answer was: %s" % (self.hintanswer))
 
@@ -99,6 +126,7 @@ class TriviaState(object):
                        self.steptimer.cancel()
                self.hintstr = None
                self.hintanswer = None
+               self.hintsgiven = 0
                self.revealpossibilities = None
 
 
@@ -126,7 +154,7 @@ class TriviaState(object):
                        return answer.lower() == self.curq['answer']
                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()
@@ -136,17 +164,11 @@ class TriviaState(object):
                        self.db['users'][user] = {'points': count, 'realnick': _user, 'rank': len(self.db['ranks'])}
                        self.db['ranks'].append(user)
 
-               oldrank = self.db['users'][user]['rank']
-               while oldrank != 0:
-                       nextperson = self.db['ranks'][oldrank-1]
-                       if self.db['users'][user]['points'] > self.db['users'][nextperson]['points']:
-                               self.db['ranks'][oldrank-1] = user
-                               self.db['users'][user]['rank'] = oldrank-1
-                               self.db['ranks'][oldrank] = nextperson
-                               self.db['users'][nextperson]['rank'] = oldrank
-                               oldrank = oldrank-1
-                       else:
-                               break
+               state.db['ranks'].sort(key=lambda nick: state.db['users'][nick]['points'], reverse=True)
+
+               if self.db['users'][user]['points'] >= state.db['target']:
+                       self.gameover = True
+
                return self.db['users'][user]['points']
 
        def points(self, user):
@@ -162,8 +184,10 @@ class TriviaState(object):
                        return self.db['users'][user]['rank']+1
                else:
                        return len(self.db['users'])+1
-       
+
        def targetuser(self, user):
+               if len(self.db['ranks']) == 0: return "no one is ranked!"
+
                user = str(user).lower()
                if user in self.db['users']:
                        rank = self.db['users'][user]['rank']
@@ -174,6 +198,8 @@ class TriviaState(object):
                else:
                        return self.db['ranks'][-1]
        def targetpoints(self, user):
+               if len(self.db['ranks']) == 0: return 0
+
                user = str(user).lower()
                if user in self.db['users']:
                        rank = self.db['users'][user]['rank']
@@ -190,7 +216,9 @@ state = TriviaState("/home/jrunyon/erebus/modules/trivia.json") #TODO get path f
 def trivia_checkanswer(bot, user, chan, *args):
        line = ' '.join([str(arg) for arg in args])
        if state.checkanswer(line):
-               bot.msg(chan, "\00308%s\003 has it! The answer was \00308%s\003. Current points: %d. Rank: %d. Target: %s (%s)." % (user, line, state.addpoint(user), state.rank(user), state.targetuser(user), state.targetpoints(user)))
+               bot.msg(chan, "\00308%s\003 has it! The answer was \00308%s\003. New score: %d. Rank: %d. Target: %s (%s)." % (user, line, state.addpoint(user), state.rank(user), state.targetuser(user), state.targetpoints(user)))
+               if state.hintsgiven == 0:
+                       bot.msg(chan, "\00308%s\003 got an extra point for getting it before the hints! New score: %d." % (user, state.addpoint(user)))
                state.nextquestion()
 
 @lib.hook('points')
@@ -213,8 +241,6 @@ def cmd_give(bot, user, chan, realtarget, *args):
                numpoints = 1
        balance = state.addpoint(whoto, numpoints)
 
-       if numpoints < 0:
-               state.db['ranks'].sort(key=lambda nick: state.db['users'][nick]['points'], reverse=True)
        bot.msg(chan, "%s gave %s %d points. New balance: %d" % (user, whoto, numpoints, balance))
 
 @lib.hook('setnext', clevel=lib.OP)
@@ -265,15 +291,39 @@ def cmd_rank(bot, user, chan, realtarget, *args):
        if len(args) != 0: who = args[0]
        else: who = user
 
-       bot.msg(replyto, "%s is in %d place. Target is: %s (%d points)." % (who, state.rank(who), state.targetuser(who), state.targetpoints(who)))
+       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)))
 
 @lib.hook('top10')
 def cmd_top10(bot, user, chan, realtarget, *args):
-       if chan == realtarget: replyto = chan
-       else: replyto = user
+       if len(state.db['ranks']) == 0:
+               return bot.msg(state.db['chan'], "No one is ranked!")
 
        replylist = []
        for nick in state.db['ranks'][0:10]:
                user = state.db['users'][nick]
-               replylist.append("%s (%d)" % (user['realnick'], user['points']))
-       bot.msg(replyto, ', '.join(replylist))
+               replylist.append("%s (%s)" % (user['realnick'], user['points']))
+       bot.msg(state.db['chan'], ', '.join(replylist))
+
+@lib.hook('settarget', clevel=lib.MASTER)
+def cmd_settarget(bot, user, chan, realtarget, *args):
+       try:
+               state.db['target'] = int(args[0])
+               bot.msg(state.db['chan'], "Target has been changed to %s points!" % (state.db['target']))
+       except:
+               bot.msg(user, "Failed to set target.")
+
+@lib.hook('triviahelp')
+def cmd_triviahelp(bot, user, chan, realtarget, *args):
+       bot.msg(user, "POINTS [<user>]")
+       bot.msg(user, "START")
+       bot.msg(user, "RANK [<user>]")
+       bot.msg(user, "TOP10")
+
+       if bot.parent.channel(state.db['chan']).levelof(user.auth) >= lib.KNOWN:
+               bot.msg(user, "SKIP                      (>=KNOWN )")
+               bot.msg(user, "STOP                      (>=KNOWN )")
+               if bot.parent.channel(state.db['chan']).levelof(user.auth) >= lib.OP:
+                       bot.msg(user, "GIVE <user> [<points>]    (>=OP    )")
+                       bot.msg(user, "SETNEXT <q>*<a>           (>=OP    )")
+                       if bot.parent.channel(state.db['chan']).levelof(user.auth) >= lib.MASTER:
+                               bot.msg(user, "SETTARGET <points>        (>=MASTER)")