]> jfr.im git - irc/evilnet/x3.git/commitdiff
New hangman plugin, and commented some debug code out
authorrubin <redacted>
Wed, 28 Jan 2009 06:51:27 +0000 (06:51 +0000)
committerrubin <redacted>
Wed, 28 Jan 2009 06:51:27 +0000 (06:51 +0000)
ChangeLog
src/modpython.py
src/plugins/hangman/__init__.py [new file with mode: 0644]
src/plugins/hangman/plugin.py [new file with mode: 0644]

index ff950751af657f17ec7de47bde369a84318ef8a3..ef62f95ff15c602e04405c338df7de8e261f0eee 100644 (file)
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,6 +1,12 @@
 /***********************************************************************
 X3 ChangeLog
 
+2009-01-27  Alex Schumann  <rubin@afternet.org>
+
+       * src/modpython.py: Comment out debug printing
+
+       * src/plugins/hangman: New example plugin: Hangman game
+
 2009-01-27  Alex Schumann  <rubin@afternet.org>
 
        * src/opserv.c: Fix a hole Sindacious found, where alerts on account
index 75e0a58d46725e348a7951fe24cd0fcd452141fd..c0fc06cd45a916f351db9025a55dc55fc5b68976 100644 (file)
@@ -37,7 +37,7 @@ class irc:
 
     def reply(self, message):
         """ Send a private reply to the user using convenience values"""
-        print "DEBUG: sending a message from %s to %s: %s"%(self.service, self.caller, message)
+        #print "DEBUG: sending a message from %s to %s: %s"%(self.service, self.caller, message)
         if(len(self.target)):
             self.send_target_privmsg(self.service, self.target, "%s: %s"%(self.caller, message))
         else:
@@ -47,7 +47,7 @@ class handler:
     """ Main hub of python system. Handle callbacks from c. """
 
     def __init__(self):
-        print "DEBUG: constructor for handler initing"
+        #print "DEBUG: constructor for handler initing"
         self.plugins = plugins(self)
         if(not self.plugins):
             print "DEBUG: unable to make self.plugins!?!"
@@ -55,18 +55,18 @@ class handler:
     def init(self, irc): # not to be confused with __init__!
         """ This gets called once all the objects are up and running. Otherwise,
         were not done initing this own instance to be able to start calling it """
-        print "DEBUG: in handler.init()"
+        #print "DEBUG: in handler.init()"
         self.plugins.init()
         return 0
 
     def join(self, irc, channel, nick):
         user = svc.get_user(nick)
-        print "DEBUG: handler.join()"
+        #print "DEBUG: handler.join()"
         self.plugins.callhandler("join", irc, [channel, nick], [channel, nick])
         return 0
         
     def cmd_run(self, irc, cmd):
-        print "DEBUG: handler.cmd_run: %s"%cmd
+        #print "DEBUG: handler.cmd_run: %s"%cmd
         eval(cmd)
         return 0
 
@@ -78,10 +78,13 @@ class handler:
         self.addhook("command", method, [plugin, command])
 
     def cmd_command(self, irc, plugin, cmd, args):
-        print "DEBUG: handlec.cmd_command; %s %s; args= %s"%(plugin, cmd, args)
+        #print "DEBUG: handel.cmd_command; %s %s; args= %s"%(plugin, cmd, args)
         self.plugins.callhandler("command", irc, [plugin, cmd], [args])
         return 0
 
+    def load(self, irc, plugin):
+        return self.plugins.load(plugin)
+
 class plugins:
     """Class to handle loading/unloading of plugins"""
     loaded_plugins = {}
@@ -105,34 +108,35 @@ class plugins:
                 for i in range(len(self.filter)):
                     if( self.filter[i] != None 
                       and self.filter[i] != evdata[i]): # should be case insensitive? or how to compare?
-                        print "DEBUG: rejecting event, %s is not %s"%(self.filter[i], evdata[i])
+                        #print "DEBUG: rejecting event, %s is not %s"%(self.filter[i], evdata[i])
                         return False
                 return True
             else:
                 return False
 
         def trigger(self, irc, args):
-            print "DEBUG: Triggering %s event. with '%s' arguments."%(self.event, args)
+            #print "DEBUG: Triggering %s event. with '%s' arguments."%(self.event, args)
             self.method(irc, *args)
 
     def __init__(self, handler):
         """ Constructor """
-        print "DEBUG: constructor for plugins initing"
+        #print "DEBUG: constructor for plugins initing"
         self.handler = handler
 
     def init(self):
-        print "DEBUG: in plugins.init()"
+        #print "DEBUG: in plugins.init()"
         self.load("annoy")
+        self.load("hangman")
 
     def addhook(self, event, method, filter=[None], data=None):
-        print "DEBUG: Adding hook for %s."%event
+        #print "DEBUG: Adding hook for %s."%event
         self.hooks.append(self.hook(event, method, filter, data))
 
     def findhooksforevent(self, event, data):
         ret = []
-        print "DEBUG: findhooksforevent() looking..."
+        #print "DEBUG: findhooksforevent() looking..."
         for hook in self.hooks:
-            print "DEBUG: looking at a %s hook..."%hook.event
+            #print "DEBUG: looking at a %s hook..."%hook.event
             if(hook.event_is(event, data)):
                 ret.append(hook)
         return ret
@@ -157,4 +161,5 @@ class plugins:
         Class = module.Class
         pluginObj = Class(self.handler, irc())
         self.loaded_plugins[mod_name] = pluginObj
+        return True
 
diff --git a/src/plugins/hangman/__init__.py b/src/plugins/hangman/__init__.py
new file mode 100644 (file)
index 0000000..daad326
--- /dev/null
@@ -0,0 +1,6 @@
+
+import plugin
+reload(plugin)
+
+Class = plugin.Class
+
diff --git a/src/plugins/hangman/plugin.py b/src/plugins/hangman/plugin.py
new file mode 100644 (file)
index 0000000..82bd5d4
--- /dev/null
@@ -0,0 +1,225 @@
+# anoy module
+
+import svc
+import re
+import fileinput
+import random
+
+# HANGMAN !!!!
+# /---
+# |  o
+# | /|\
+# | / \
+# =======
+
+class Game:
+    target = '' #channel or user's nick who we are playing with
+    word = ''
+    maskchar = '*'
+    man = 0
+    dictionary = "/usr/share/dict/words"
+
+    def __init__(self, irc, target, length=0):
+        self.irc = irc
+        self.target = target
+        length = int(length)
+        if(length > 3 and length < 100):
+            self.length = length
+        else:
+            self.length = random.randrange(5, 9)
+        # What constitutes a valid word?
+        self.valid = re.compile(r"^[a-zA-Z]+$")
+        self.guesses = {}
+
+        if(self.length < 3):
+            self.reply("You can only play with 3 or more letters")
+            self.man = 9999
+            return
+
+        if(self.newword(self.length)):
+            self.reply("HANGMAN is starting!")
+            self.printstatus()
+        else:
+            self.reply("Aborting game")
+            self.man = 9999
+            return 
+
+    def validword(self):
+        if(len(self.word) == self.length and self.valid.search(self.word)):
+                return True
+        return False
+
+    def newword(self, length):
+        numlines = 0
+        for line in open(self.dictionary, "r"):
+          numlines += 1
+        tries = 0
+
+        if(numlines < 100):
+            raise Exception("Dictionary has too few words")
+
+        while((not self.validword())): #failsafe dont loop forever...
+            tries += 1
+            if(tries > 10):
+                self.reply("Error finding a %s letter word"%length)
+                return False
+                #raise(Exception("DictError", "Unable to find %s letter word"%length))
+            i = 0
+            randline = random.randrange(1, numlines-1)
+            for line in open(self.dictionary, 'r'):
+                if(i >= randline):
+                    self.word = line.rstrip()
+                    if(not self.validword() and i < randline + 50):
+                        continue
+                    else:
+                        break # give up on this block and try again
+                i += 1
+        if(len(self.word) < 3):
+            self.reply("Unable to find a word in the dictionary!")
+            return False
+
+        return True
+
+
+    def maskedword(self):
+        mask = []
+        for i in self.word:
+            if(i in self.guesses or not i.isalpha()):
+                mask.append(i)
+            else:
+                mask.append(self.maskchar)
+        return(''.join(mask))
+
+    def manpart(self, part, num):
+        if(self.man >= num):
+            return part
+        else:
+            return " "
+
+    def printstatus(self):
+        print("DEBUG: the word is '%s'"%self.word)
+        self.reply(" /---%s       "%( self.manpart(",", 1 )) )
+        self.reply(" |   %s       Make "%( self.manpart("o",2)) )
+        self.reply(" |  %s%s%s      your "%( self.manpart("/",4), self.manpart("|",3), self.manpart("\\", 5) ) )
+        self.reply(" |  %s %s      guess! "%( self.manpart("/",6), self.manpart("\\",7) ))
+        self.reply(" ====")
+        self.reply(self.maskedword())
+
+        if(self.won() == True):
+            self.reply("YOU WON! FOR NOW!!")
+        elif(self.won() == False):
+            self.reply("Your DEAD! DEAAAAAAAD!")
+
+
+    def won(self):
+        if(self.man >= 7):
+            return False
+
+        for i in self.word:
+            if(not i in self.guesses.keys()):
+                return None
+        return True
+
+    def guess(self, irc, letter):
+        self.irc = irc
+
+        if(self.won() != None):
+            self.reply("This game is over. Start another!")
+            return
+        if(len(letter) > 1):
+            self.reply("Guess a single letter only, please.")
+            return
+        if(not letter.isalpha()):
+            self.reply("Letters only. Punctuation will be filled in for you.")
+            return
+        if(letter in self.guesses):
+            self.reply("Pay attention! %s has already been guessed! I'm hanging you anyway!"%letter)
+            self.man += 1
+            self.printstatus()
+            return
+        
+        self.guesses[letter] = True
+
+        if(self.won() != None):
+            pass
+        elif(self.word.find(letter) >= 0):
+            self.reply("YOU GOT ONE! But I'll hang you yet!!")
+        else:
+            self.reply("NO! MuaHaHaHaHa!")
+            self.man += 1
+
+        self.printstatus()
+
+    def reply(self, msg):
+            self.irc.send_target_privmsg(self.irc.service, self.target, msg)
+
+class Hangman:
+    config = {}
+
+    def __init__(self, handler, irc):
+        self.handler = handler
+        self.name = "hangman"
+
+        handler.addcommand(self.name, "start", self.start)
+        handler.addcommand(self.name, "end", self.end)
+        handler.addcommand(self.name, "guess", self.guess)
+
+        self.games = {} # list of game objects
+
+    def target(self, irc):
+        if(len(irc.target)):
+            return irc.target
+        else:
+            return irc.caller 
+
+    def start(self, irc, arg):
+        playwith = self.target(irc)
+        if(playwith in self.games.keys() and self.games[playwith].won() == None):
+            irc.reply("There is a game is in progress here, End it before you start another.")
+            return
+            
+        if(arg.isdigit()):
+            self.games[playwith] = Game(irc, playwith, arg)
+        else:
+            self.games[playwith] = Game(irc, playwith)
+
+    def end(self, irc, unused):
+        playwith = self.target(irc)
+        if(self.target(irc) in self.games.keys()):
+            self.games[playwith].reply("Game ended by %s"%irc.caller)
+            del(self.games[playwith])
+        else:
+            irc.reply("No game here to end")
+
+    def guess(self, irc, arg):
+        playwith = self.target(irc)
+        if(self.target(irc) in self.games.keys()):
+            self.games[playwith].guess(irc, arg)
+        else:
+            irc.reply("No game here in progress. Start one!")
+
+    def dance(self, irc, args):
+        nick = irc.caller
+        user = svc.get_user(nick)
+
+        reply = "Ok,"
+        if(user and "account" in user):
+           reply +=  " Mr. %s"%user["account"]
+
+        reply += " we can dance"
+        if(len(args)):
+            reply += " "
+            reply += args
+        reply += "."
+
+        irc.reply(reply)
+
+    def nickof(self, irc, bot):
+        info = svc.get_info()
+
+        if(bot and bot in info.keys()):
+            irc.reply("%s has nick %s"%(bot, info[bot]))
+        else:
+            irc.reply("I dunno. Try %s"%str(info.keys()))
+
+Class = Hangman