Mercurial > traipse_dev
changeset 71:449a8900f9ac ornery-dev
Code refining almost completed, for this round. Some included files are still in need of some clean up, but this is test worthy.
line wrap: on
line diff
--- a/orpg/chat/chat_msg.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/chat/chat_msg.py Thu Aug 20 03:00:39 2009 -0500 @@ -29,9 +29,10 @@ __version__ = "$Id: chat_msg.py,v 1.15 2006/11/04 21:24:19 digitalxero Exp $" -#import orpg.orpg_xml from orpg.orpgCore import * -from chat_version import CHAT_VERSION +from chat_version import CHAT_VERSION +from orpg.tools.orpg_log import logger +from orpg.tools.decorators import debugging CHAT_MESSAGE = 1 WHISPER_MESSAGE = 2 @@ -40,22 +41,24 @@ SYSTEM_MESSAGE = 5 WHISPER_EMOTE_MESSAGE = 6 -class chat_msg: +class chat_msg: + @debugging def __init__(self,xml_text="<chat type=\"1\" version=\""+CHAT_VERSION+"\" alias=\"\" ></chat>"): - self.xml = component.get('xml') self.chat_dom = None self.takexml(xml_text) - + + @debugging def __del__(self): if self.chat_dom: self.chat_dom.unlink() - + + @debugging def toxml(self): - return self.xml.toxml(self.chat_dom) - + return component.get('xml').toxml(self.chat_dom) + + @debugging def takexml(self,xml_text): - #self.xml = component.get('xml') - xml_dom = self.xml.parseXml(xml_text) + xml_dom = component.get('xml').parseXml(xml_text) node_list = xml_dom.getElementsByTagName("chat") if len(node_list) < 1: print "Warning: no <chat/> elements found in DOM." @@ -63,32 +66,40 @@ if len(node_list) > 1: print "Found more than one instance of <" + self.tagname + "/>. Taking first one" self.takedom(node_list[0]) - + + @debugging def takedom(self,xml_dom): if self.chat_dom: self.text_node = None self.chat_dom.unlink() self.chat_dom = xml_dom - self.text_node = self.xml.safe_get_text_node(self.chat_dom) - + self.text_node = component.get('xml').safe_get_text_node(self.chat_dom) + + @debugging def set_text(self,text): - text = self.xml.strip_text(text) + text = component.get('xml').strip_text(text) self.text_node._set_nodeValue(text) - + + @debugging def set_type(self,type): self.chat_dom.setAttribute("type",str(type)) - + + @debugging def get_type(self): return int(self.chat_dom.getAttribute("type")) - + + @debugging def set_alias(self,alias): self.chat_dom.setAttribute("alias",alias) - + + @debugging def get_alias(self): return self.chat_dom.getAttribute("alias") - + + @debugging def get_text(self): return self.text_node._get_nodeValue() - + + @debugging def get_version(self): return self.chat_dom.getAttribute("version")
--- a/orpg/chat/chat_util.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/chat/chat_util.py Thu Aug 20 03:00:39 2009 -0500 @@ -1,7 +1,10 @@ # utility function; see Post() in chatwnd.py import re -import string +import string +from orpg.orpgCore import * +from orpg.tools.orpg_log import logger +from orpg.tools.decorators import debugging #============================================ # simple_html_repair(string) @@ -15,8 +18,9 @@ # to cause issues with the chat display # # Created 04-25-2005 by Snowdog -#============================================= -def simple_html_repair(string): +#============================================= +@debugging +def simple_html_repair(string): "Returns string with extra > symbols to isolate badly formated HTML" #walk though string checking positions of < and > tags. first_instance = string.find('<') @@ -67,24 +71,26 @@ if diff > 0: for d in range(1,diff): string = string+">" + return string - return string - -def strip_unicode(txt): +""" Depricated! Might as well use the already made component.get('xml') +def strip_unicode(txt): for i in xrange(len(txt)): if txt[i] not in string.printable: try: txt = txt.replace(txt[i], '&#' + str(ord(txt[i])) + ';') except: txt = txt.replace(txt[i], '{?}') - return txt + return txt +""" #================================================ # strip_script_tags(string) # # removes all script tags (start and end) # 04-26-2005 Snowdog -#================================================ +#================================================ +@debugging def strip_script_tags(string): #kill the <script> issue p = re.compile( '<(\s*)(/*)[Ss][Cc][Rr][Ii][Pp][Tt](.*?)>') @@ -97,6 +103,7 @@ # removes all li tags (start and end) # 05-13-2005 #================================================ +@debugging def strip_li_tags(string): #kill the <li> issue string = re.sub( r'<(\s*)[Ll][Ii](.*?)>', r'<b><font color="#000000" size=+1>*</font></b> ', string) @@ -111,6 +118,7 @@ # through legitimate means such as the OpenRPG settings. # 07-27-2005 by mDuo13 #================================================ +@debugging def strip_body_tags(string): bodytag_regex = re.compile(r"""<\/?body.*?>""", re.I) string = re.sub(bodytag_regex, "", string) @@ -128,7 +136,8 @@ # algorithm simply closes them, allowing them to be # used legitimately without causing much annoyance. # 07-27-2005 mDuo13 -#================================================ +#================================================ +@debugging def strip_misalignment_tags(string): alignment_regex = re.compile(r"""<p([^>]*?)align\s*=\s*('.*?'|".*?"|[^\s>]*)(.*?)>""", re.I) string = re.sub(alignment_regex, "<p\\1\\3>", string) @@ -148,7 +157,8 @@ # removes all img tags (start and end) # 05-13-2005 # redone 07-11-2005 by mDuo13 -#================================================ +#================================================ +@debugging def strip_img_tags(string): #This is a Settings definable feature, Allowing users to enable or disable image display to fix the client crash due to large img posted to chat. #p = re.sub( r'<(\s*)(/*)[Ii][Mm][Gg][ ][Ss][Rr][Cc][=](.*?)>', r'<!-- img tag removed //--> <a href=\3>\3</a>', string)
--- a/orpg/chat/chatwnd.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/chat/chatwnd.py Thu Aug 20 03:00:39 2009 -0500 @@ -49,7 +49,7 @@ import orpg.tools.rgbhex import orpg.tools.inputValidator #from orpg.tools.metamenus import MenuEx #Needed? -from orpg.orpgCore import component + import webbrowser from string import * from orpg.orpg_version import VERSION @@ -66,6 +66,10 @@ from HTMLParser import HTMLParser import chat_util import traceback + +from orpg.tools.validate import validate +from orpg.tools.orpg_settings import settings +from orpg.orpgCore import component from orpg.tools.orpg_log import logger from orpg.tools.decorators import debugging NEWCHAT = False @@ -78,32 +82,39 @@ # Global parser for stripping HTML tags: # The 'tag stripping' is implicit, because this parser echoes every # type of html data *except* the tags. -class HTMLStripper(HTMLParser): +class HTMLStripper(HTMLParser): + @debugging def __init__(self): self.accum = "" - self.special_tags = ['hr', 'br', 'img'] + self.special_tags = ['hr', 'br', 'img'] + @debugging def handle_data(self, data): # quote cdata literally - self.accum += data + self.accum += data + @debugging def handle_entityref(self, name): # entities must be preserved exactly - self.accum += "&" + name + ";" + self.accum += "&" + name + ";" + @debugging def handle_starttag(self, tag, attrs): if tag in self.special_tags: self.accum += '<' + tag for attrib in attrs: self.accum += ' ' + attrib[0] + '="' + attrib[1] + '"' - self.accum += '>' + self.accum += '>' + @debugging def handle_charref(self, name): # charrefs too self.accum += "&#" + name + ";" htmlstripper = HTMLStripper() -# utility function; see Post(). +# utility function; see Post(). +@debugging def strip_html(string): "Return string tripped of html tags." htmlstripper.reset() htmlstripper.accum = "" htmlstripper.feed(string) htmlstripper.close() - return htmlstripper.accum + return htmlstripper.accum +@debugging def log( settings, c, text ): filename = settings.get_setting('GameLogPrefix') if filename > '' and filename[0] != commands.ANTI_LOG_CHAR: @@ -135,6 +146,7 @@ # !self : instance of self # !parent : # !id : + @debugging def __init__(self, parent, id): wx.html.HtmlWindow.__init__(self, parent, id, style=wx.SUNKEN_BORDER | wx.html.HW_SCROLLBAR_AUTO|wx.NO_FULL_REPAINT_ON_RESIZE) self.parent = parent @@ -144,41 +156,50 @@ if "gtk2" in wx.PlatformInfo: self.SetStandardFonts() # def __init__ - end + @debugging def onPopup(self, evt): self.PopupMenu(self.menu) + @debugging def LeftUp(self, event): event.Skip() wx.CallAfter(self.parent.set_chat_text_focus, None) + @debugging def build_menu(self): self.menu = wx.Menu() item = wx.MenuItem(self.menu, wx.ID_ANY, "Copy", "Copy") self.Bind(wx.EVT_MENU, self.OnM_EditCopy, item) self.menu.AppendItem(item) + @debugging def OnM_EditCopy(self, evt): wx.TheClipboard.Open() wx.TheClipboard.Clear() wx.TheClipboard.SetData(wx.TextDataObject(self.SelectionToText())) wx.TheClipboard.Close() + @debugging def scroll_down(self): maxrange = self.GetScrollRange(wx.VERTICAL) pagesize = self.GetScrollPageSize(wx.VERTICAL) self.Scroll(-1, maxrange-pagesize) + @debugging def mouse_wheel(self, event): amt = event.GetWheelRotation() units = amt/(-(event.GetWheelDelta())) self.ScrollLines(units*3) + @debugging def Header(self): return '<html><body bgcolor="' + self.parent.bgcolor + '" text="' + self.parent.textcolor + '">' + @debugging def StripHeader(self): return self.GetPageSource().replace(self.Header(), '') + @debugging def GetPageSource(self): return self.GetParser().GetSource() @@ -186,12 +207,14 @@ # # !self : instance of self # !linkinfo : instance of a class that contains the link information + @debugging def OnLinkClicked(self, linkinfo): href = linkinfo.GetHref() wb = webbrowser.get() wb.open(href) # def OnLinkClicked - end + @debugging def CalculateAllFonts(self, defaultsize): return [int(defaultsize * 0.4), int(defaultsize * 0.7), @@ -201,6 +224,7 @@ int(defaultsize * 2), int(defaultsize * 2.5)] + @debugging def SetDefaultFontAndSize(self, fontname, fontsize): """Set 'fontname' to the default chat font. Returns current font settings in a (fontname, fontsize) tuple.""" @@ -210,6 +234,7 @@ # class chat_html_window - end if NEWCHAT: class ChatHtmlWindow(wx.webview.WebView): + @debugging def __init__(self, parent, id): wx.webview.WebView.__init__(self, parent, id) @@ -222,18 +247,23 @@ self.Bind(wx.webview.EVT_WEBVIEW_BEFORE_LOAD, self.OnLinkClicked) #Wrapers so I dont have to add special Code + @debugging def SetPage(self, htmlstring): self.SetPageSource(htmlstring) + @debugging def AppendToPage(self, htmlstring): self.SetPageSource(self.GetPageSource() + htmlstring) + @debugging def GetFont(self): return self.__font + @debugging def CalculateAllFonts(self, defaultsize): return + @debugging def SetDefaultFontAndSize(self, fontname, fontsize): self.__font = wx.Font(int(fontsize), wx.FONTFAMILY_ROMAN, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, faceName=fontname) try: self.SetPageSource(self.Header() + self.StripHeader()) @@ -241,41 +271,50 @@ return (self.GetFont().GetFaceName(), self.GetFont().GetPointSize()) #Events + @debugging def OnLinkClicked(self, linkinfo): href = linkinfo.GetHref() wb = webbrowser.get() wb.open(href) + @debugging def onPopup(self, evt): self.PopupMenu(self.menu) + @debugging def LeftUp(self, event): event.Skip() wx.CallAfter(self.parent.set_chat_text_focus, None) + @debugging def OnM_EditCopy(self, evt): self.Copy() #Cutom Methods + @debugging def Header(self): return "<html><head><style>body {font-size: " + str(self.GetFont().GetPointSize()) + "px;font-family: " + self.GetFont().GetFaceName() + ";color: " + self.parent.textcolor + ";background-color: " + self.parent.bgcolor + ";margin: 0;padding: 0 0;height: 100%;}</style></head><body>" + @debugging def StripHeader(self): tmp = self.GetPageSource().split('<BODY>') if tmp[-1].find('<body>') > -1: tmp = tmp[-1].split('<body>') return tmp[-1] + @debugging def build_menu(self): self.menu = wx.Menu() item = wx.MenuItem(self.menu, wx.ID_ANY, "Copy", "Copy") self.Bind(wx.EVT_MENU, self.OnM_EditCopy, item) self.menu.AppendItem(item) + @debugging def scroll_down(self): maxrange = self.GetScrollRange(wx.VERTICAL) pagesize = self.GetScrollPageSize(wx.VERTICAL) self.Scroll(-1, maxrange-pagesize) + @debugging def mouse_wheel(self, event): amt = event.GetWheelRotation() units = amt/(-(event.GetWheelDelta())) @@ -493,9 +532,9 @@ # who receives outbound messages, either "all" or "playerid" string self.sendtarget = sendtarget self.type = tab_type - self.sound_player = component.get('sound') + #self.sound_player = component.get('sound') #Removing! # create die roller manager - self.DiceManager = component.get('DiceManager') + #self.DiceManager = component.get('DiceManager') #Removing! # create rpghex tool self.r_h = orpg.tools.rgbhex.RGBHex() self.h = 0 @@ -520,7 +559,7 @@ self.Bind(wx.EVT_SIZE, self.OnSize) self.build_ctrls() #openrpg dir - self.root_dir = dir_struct["home"] + #self.root_dir = dir_struct["home"] #Removing! # html font/fontsize is global to all the notebook tabs. StartupFont = self.settings.get_setting("defaultfont") StartupFontSize = self.settings.get_setting("defaultfontsize") @@ -1162,7 +1201,7 @@ if not len(macroText): self.chattxt.SetValue("") # play sound sound_file = self.settings.get_setting("SendSound") - if sound_file != '': self.sound_player.play(sound_file) + if sound_file != '': component.get('sound').play(sound_file) if s[0] != "/": ## it's not a slash command s = self.ParsePost( s, True, True ) else: self.chat_cmds.docmd(s) # emote is in chatutils.py @@ -1292,7 +1331,7 @@ file.write(self.ResetPage() + "</body></html>") file.close() f.Destroy() - os.chdir(self.root_dir) + os.chdir(dir_struct["home"]) # def on_chat_save - end @debugging @@ -1642,7 +1681,7 @@ # playe sound sound_file = self.settings.get_setting(recvSound) if sound_file != '': - self.sound_player.play(sound_file) + component.get('sound').play(sound_file) #### Posting helpers ##### @debugging @@ -1731,7 +1770,7 @@ newline = "<div class='"+c+"'> " + self.TimeIndexString() + name + s + "</div>" log( self.settings, c, name+s ) else: send = False - newline = chat_util.strip_unicode(newline) + newline = component.get('xml').strip_unicode(newline) if self.lockscroll == 0: self.chatwnd.AppendToPage(newline) self.scroll_down() @@ -1820,7 +1859,7 @@ if newstr[0].lower() == 'q': newstr = newstr[1:] qmode = 1 - try: newstr = self.DiceManager.proccessRoll(newstr) + try: newstr = component.get('DiceManager').proccessRoll(newstr) except: pass if qmode == 1: s = s.replace("[" + matches[i] + "]", "<!-- Official Roll [" + newstr1 + "] => " + newstr + "-->" + newstr, 1)
--- a/orpg/chat/commands.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/chat/commands.py Thu Aug 20 03:00:39 2009 -0500 @@ -12,7 +12,10 @@ import time import orpg.orpg_version import orpg.orpg_windows -import traceback +import traceback + +from orpg.tools.orpg_log import logger +from orpg.tools.decorators import debugging ##-------------------------------------------------------------- ## dynamically loading module for extended developer commands @@ -35,7 +38,8 @@ # Initialization subroutine. # # !self : instance of self - # !chat : instance of the chat window to write to + # !chat : instance of the chat window to write to + @debugging def __init__(self,chat): self.post = chat.Post self.colorize = chat.colorize @@ -55,18 +59,21 @@ # of implemented emotions. # # !self : instance of self - # !text : string of text matching an implemented emotion + # !text : string of text matching an implemented emotion + @debugging def addcommand(self, cmd, function, helpmsg): if not self.cmdlist.has_key(cmd) and not self.shortcmdlist.has_key(cmd): self.cmdlist[cmd] = {} self.cmdlist[cmd]['function'] = function self.cmdlist[cmd]['help'] = helpmsg #print 'Command Added: ' + cmd - + + @debugging def addshortcmd(self, shortcmd, longcmd): if not self.shortcmdlist.has_key(shortcmd) and not self.cmdlist.has_key(shortcmd): self.shortcmdlist[shortcmd] = longcmd - + + @debugging def removecmd(self, cmd): if self.cmdlist.has_key(cmd): del self.cmdlist[cmd] @@ -75,7 +82,8 @@ #print 'Command Removed: ' + cmd - + + @debugging def defaultcmds(self): self.addcommand('/help', self.on_help, '- Displays this help message') self.addcommand('/version', self.on_version, ' - Displays current version of OpenRPG.') @@ -104,7 +112,8 @@ self.addcommand('/sound', self.on_sound, 'Sound_URL - Plays a sound for all clients in the room.') self.addcommand('/purge', self.on_purge, 'This will clear the entire chat window') self.addcommand('/advfilter', self.on_filter, 'This will toggle the Advanced Filter') - + + @debugging def defaultcmdalias(self): self.addshortcmd('/?', '/help') self.addshortcmd('/he', '/me') @@ -118,8 +127,8 @@ #This is just an example or a differant way the shorcmd can be used self.addshortcmd('/sleep', '/me falls asleep') - - + + @debugging def docmd(self,text): cmdsearch = string.split(text,None,1) cmd = string.lower(cmdsearch[0]) @@ -134,7 +143,8 @@ else: msg = "Sorry I don't know what %s is!" % (cmd) self.chat.InfoPost(msg) - + + @debugging def on_filter(self, cmdargs): #print self.chat.advancedFilter test = not self.chat.advancedFilter @@ -158,11 +168,13 @@ self.chat.InfoPost("Advanced Filtering has been turned On") else: self.chat.InfoPost("Advanced Filtering has been turned Off") - + + @debugging def on_purge(self, cmdargs): self.chat.PurgeChat() self.chat.InfoPost('Chat Buffer has been Purged!') - + + @debugging def on_sound(self, cmdargs): if len(cmdargs) < 8: self.chat.InfoPost("You must provide a URL for the file name, it does not work for just local sound files") @@ -195,10 +207,12 @@ self.chat.InfoPost("You cannot send sound files to the lobby!") else: self.chat.InfoPost("Something dun fuckered up Frank!") - + + @debugging def on_version(self, cmdargs=""): self.chat.InfoPost("Version is OpenRPG " + self.chat.version) - + + @debugging def on_load(self, cmdargs): args = string.split(cmdargs,None,-1) try: @@ -208,13 +222,15 @@ except Exception,e: print e self.chat.InfoPost("ERROR Loading settings") - + + @debugging def on_font(self, cmdargs): try: fontsettings = self.chat.set_default_font(fontname=cmdargs, fontsize=None) except: self.chat.InfoPost("ERROR setting default font") - + + @debugging def on_fontsize(self, cmdargs): args = string.split(cmdargs,None,-1) try: @@ -222,7 +238,8 @@ except Exception, e: print e self.chat.InfoPost("ERROR setting default font size") - + + @debugging def on_close(self, cmdargs): try: chatpanel = self.chat @@ -233,14 +250,16 @@ chatpanel.parent.onCloseTab(0) except: self.chat.InfoPost("Error: cannot close private chat tab.") - + + @debugging def on_time(self, cmdargs): local_time = time.localtime() gmt_time = time.gmtime() format_string = "%A %b %d, %Y %I:%M:%S%p" self.chat.InfoPost("<br />Local: " + time.strftime(format_string)+\ "<br />GMT: "+time.strftime(format_string,gmt_time)) - + + @debugging def on_dieroller(self, cmdargs): args = string.split(cmdargs,None,-1) rm = self.chat.DiceManager @@ -252,12 +271,14 @@ print e self.chat.InfoPost("Available die rollers: " + str(rm.listRollers())) self.chat.InfoPost("You are using the <b>\"" + rm.getRoller() + "\"</b> die roller.") - + + @debugging def on_ping(self, cmdargs): ct = time.clock() msg = "<ping player='"+self.session.id+"' time='"+str(ct)+"' />" self.session.outbox.put(msg) - + + @debugging def on_log(self,cmdargs): args = string.split(cmdargs,None,-1) logfile = self.settings.get_setting( 'GameLogPrefix' ) @@ -288,7 +309,8 @@ self.postLoggingState() else: self.chat.InfoPost("Unknown logging command, use 'on' or 'off'" ) - + + @debugging def postLoggingState( self ): logfile = self.settings.get_setting( 'GameLogPrefix' ) try: @@ -304,7 +326,8 @@ # This subroutine will set the players netork status. # #!self : instance of self - + + @debugging def on_name(self, cmdargs): #only 20 chars no more! :) if cmdargs == "": @@ -318,7 +341,8 @@ # This subroutine will set the players netork status. # - # !self : instance of self + # !self : instance of self + @debugging def on_status(self, cmdargs): if cmdargs == "": self.chat.InfoPost("Incorrect synatx for status.") @@ -327,7 +351,8 @@ txt = cmdargs[:20] self.session.set_text_status(str(txt)) # def on_status - end - + + @debugging def on_set(self, cmdargs): args = string.split(cmdargs,None,-1) keys = self.settings.get_setting_keys() @@ -361,7 +386,8 @@ # This subroutine will display the correct usage of the different emotions. # #!self : instance of self - + + @debugging def on_help(self, cmdargs=""): cmds = self.cmdlist.keys() cmds.sort() @@ -383,7 +409,8 @@ # This subroutine will either show the list of currently ignored users # !self : instance of self # !text : string that is comprised of a list of users to toggle the ignore flag - + + @debugging def on_ignore(self, cmdargs): args = string.split(cmdargs,None,-1) (ignore_list, ignore_name) = self.session.get_ignore_list() @@ -409,7 +436,8 @@ except: self.chat.InfoPost(m + " was ignored because it is an invalid player ID") traceback.print_exc() - + + @debugging def on_role(self, cmdargs): if cmdargs == "": self.session.display_roles() @@ -440,7 +468,8 @@ # !self : instance of self # !text : string that is comprised of a list of users and the message to #whisper. - + + @debugging def on_whisper(self, cmdargs): delim = cmdargs.find("=") @@ -458,7 +487,8 @@ #--------------------------------------------------------- # [START] Digitalxero Multi Whisper Group 1/1/05 -#--------------------------------------------------------- +#--------------------------------------------------------- + @debugging def on_groupwhisper(self, cmdargs): args = string.split(cmdargs,None,-1) delim = cmdargs.find("=") @@ -518,7 +548,8 @@ #--------------------------------------------------------- # [END] Digitalxero Multi Whisper Group 1/1/05 #--------------------------------------------------------- - + + @debugging def on_gmwhisper(self, cmdargs): if cmdargs == "": self.chat.InfoPost("**Incorrect syntax for GM Whisper.") @@ -533,7 +564,8 @@ self.on_whisper(gmstring + "=" + cmdargs) else: self.chat.InfoPost("**No GMs to Whisper to.") - + + @debugging def on_moderate(self, cmdargs): if cmdargs != "": pos = cmdargs.find("=") @@ -570,10 +602,12 @@ msg = "<moderate action='list' from='"+self.session.id+"' />" self.session.outbox.put(msg) self.session.update() - + + @debugging def on_update(self, cmdargs): self.chat.InfoPost("This command is no longer valid") - + + @debugging def on_description(self, cmdargs): if len(cmdargs) <= 0: self.chat.InfoPost("**No description text to display." + str(delim)) @@ -583,7 +617,8 @@ mesg += "</font></td></tr></table>" self.chat.Post(mesg) self.chat.send_chat_message(mesg) - + + @debugging def invoke_tab(self, cmdargs): ######START mDuo13's Tab Initiator######## try: @@ -608,7 +643,8 @@ self.chat.parent.newMsg(nidx) return #######END mDuo13's Tab Initiator######### - + + @debugging def on_remote_admin(self, cmdargs): args = string.split(cmdargs,None,-1) #handles remote administration commands
--- a/orpg/dieroller/d20.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/dieroller/d20.py Thu Aug 20 03:00:39 2009 -0500 @@ -18,34 +18,40 @@ # # Description: d20 die roller # -from die import * +from die import * __version__ = "$Id: d20.py,v 1.9 2006/11/04 21:24:19 digitalxero Exp $" # d20 stands for "d20 system" not 20 sided die :) class d20(std): + def __init__(self,source=[]): std.__init__(self,source) # these methods return new die objects for specific options + def attack(self,AC,mod,critical): return d20attack(self,AC,mod,critical) + def dc(self,DC,mod): return d20dc(self,DC,mod) class d20dc(std): + def __init__(self,source=[],DC=10,mod=0): std.__init__(self,source) self.DC = DC self.mod = mod self.append(static_di(mod)) + def is_success(self): return ((self.sum() >= self.DC or self.data[0] == 20) and self.data[0] != 1) + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]: @@ -64,6 +70,7 @@ class d20attack(std): + def __init__(self,source=[],AC=10,mod=0,critical=20): std.__init__(self,source) self.mod = mod @@ -72,11 +79,13 @@ self.append(static_di(mod)) self.critical_check() + def attack(AC=10,mod=0,critical=20): self.mod = mod self.critical = critical self.AC = AC + def critical_check(self): self.critical_result = 0 self.critical_roll = 0 @@ -85,12 +94,15 @@ if self.critical_roll.sum() >= self.AC: self.critical_result = 1 + def is_critical(self): return self.critical_result + def is_hit(self): return ((self.sum() >= self.AC or self.data[0] == 20) and self.data[0] != 1) + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]:
--- a/orpg/dieroller/die.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/dieroller/die.py Thu Aug 20 03:00:39 2009 -0500 @@ -37,6 +37,7 @@ class die_base(UserList.UserList): + def __init__(self,source = []): if isinstance(source, (int, float, basestring)): s = [] @@ -46,12 +47,14 @@ UserList.UserList.__init__(self,s) + def sum(self): s = 0 for a in self.data: s += int(a) return s + def __lshift__(self,other): if type(other) == type(3) or type(other) == type(3.0): o = other @@ -66,6 +69,7 @@ result.append(die) return self.__class__(result) + def __rshift__(self,other): if type(other) == type(3) or type(other) == type(3.0): @@ -81,13 +85,16 @@ result.append(die) return self.__class__(result) + def __rlshift__(self,other): return self.__rshift__(other) + def __rrshift__(self,other): return self.__lshift__(other) + def __str__(self): if len(self.data) > 0: myStr = "[" + str(self.data[0]) @@ -99,6 +106,7 @@ myStr = "[] = (0)" return myStr + def __lt__(self,other): if type(other) == type(3) or type(other) == type(3.0): return (self.sum() < other) @@ -107,6 +115,7 @@ else: return UserList.UserList.__lt__(self,other) + def __le__(self,other): if type(other) == type(3) or type(other) == type(3.0): return (self.sum() <= other) @@ -115,6 +124,7 @@ else: return UserList.UserList.__le__(self,other) + def __eq__(self,other): if type(other) == type(3) or type(other) == type(3.0): return (self.sum() == other) @@ -123,6 +133,7 @@ else: return UserList.UserList.__eq__(self,other) + def __ne__(self,other): if type(other) == type(3) or type(other) == type(3.0): return (self.sum() != other) @@ -131,6 +142,7 @@ else: return UserList.UserList.__ne__(self,other) + def __gt__(self,other): if type(other) == type(3) or type(other) == type(3.0): return (self.sum() > other) @@ -139,6 +151,7 @@ else: return UserList.UserList.__gt__(self,other) + def __ge__(self,other): if type(other) == type(3) or type(other) == type(3.0): return (self.sum() >= other) @@ -147,6 +160,7 @@ else: return UserList.UserList.__ge__(self,other) + def __cmp__(self,other): # this function included for backwards compatibility # As of 2.1, lists implement the "rich comparison" @@ -159,9 +173,11 @@ return UserList.UserList.__cmp__(self,other) + def __rcmp__(self,other): return self.__cmp__(other) + def __add__(self,other): mycopy = copy.deepcopy(self) if type(other) == type(3) or type(other) == type(3.0): @@ -177,9 +193,11 @@ #result = UserList.UserList.__add__(mycopy,other) return mycopy + def __iadd__(self,other): return self.__add__(other) + def __radd__(self,other): mycopy = copy.deepcopy(self) if type(other) == type(3) or type(other) == type(3.0): @@ -189,9 +207,11 @@ mycopy.insert(0,other) return mycopy + def __int__(self): return self.sum() + def __sub__(self,other): mycopy = copy.deepcopy(self) if type(other) == type(3) or type(other) == type(3.0): @@ -204,6 +224,7 @@ mycopy.extend(other) return mycopy + def __rsub__(self,other): mycopy = -copy.deepcopy(self) #print type(other) @@ -214,9 +235,11 @@ mycopy.insert(0,other) return mycopy + def __isub__(self,other): return self.__sub__(other) + def __mul__(self,other): if type(other) == type(3) or type(other) == type(3.0): return self.sum() * other @@ -225,9 +248,11 @@ else: return UserList.UserList.__mul__(self,other) + def __rmul__(self,other): return self.__mul__(other) + def __div__(self,other): if type(other) == type(3) or type(other) == type(3.0): return float(self.sum()) / other @@ -236,6 +261,7 @@ else: return UserList.UserList.__div__(self,other) + def __rdiv__(self,other): if type(other) == type(3) or type(other) == type(3.0): return other / float(self.sum()) @@ -244,6 +270,7 @@ else: return UserList.UserList.__rdiv__(self,other) + def __mod__(self,other): if type(other) == type(3) or type(other) == type(3.0): return self.sum()%other @@ -252,6 +279,7 @@ else: return UserList.UserList.__mod__(self,other) + def __rmod__(self,other): if type(other) == type(3) or type(other) == type(3.0): return other % self.sum() @@ -260,22 +288,26 @@ else: return UserList.UserList.__rmod__(self,other) + def __neg__(self): for i in range(len(self.data)): self.data[i] = -self.data[i] return self + def __pos__(self): for i in range(len(self.data)): self.data[i] = +self.data[i] return self + def __abs__(self): for i in range(len(self.data)): self.data[i] = abs(self.data[i]) return self #return abs(self.sum()) + def __pow__(self,other): if type(other) == type(3) or type(other) == type(3.0): return self.sum() ** other @@ -285,6 +317,7 @@ return UserList.UserList.__pow__(self,other) + def __rpow__(self,other): # We're overloading exponentiation of ints to create "other" number of dice @@ -300,6 +333,7 @@ ### di class to handle actual dice class di: + def __init__(self,sides,min=1): self.sides = sides self.history = None @@ -307,40 +341,47 @@ self.target = None self.roll(min) + def __str__(self): if len(self.history) > 1: return str(self.history) else: return str(self.value) + def __neg__(self): self.value = -self.value for i in range(len(self.history)): self.history[i] = -self.history[i] return self + def __pos__(self): self.value = +self.value for i in range(len(self.history)): self.history[i] = +self.history[i] return self + def __abs__(self): self.value = abs(self.value) for i in range(len(self.history)): self.history[i] = abs(self.history[i]) return self + def __repr__(self): if len(self.history) > 1: return str(self.history) else: return str(self.value) + def __int__(self): return self.value + def __lt__(self,other): if type(other) == type(3) or type(other) == type(3.0): return self.value < other @@ -349,6 +390,7 @@ else: return self < other + def __le__(self,other): if type(other) == type(3) or type(other) == type(3.0): return self.value <= other @@ -357,6 +399,7 @@ else: return self <= other + def __eq__(self,other): if type(other) == type(3) or type(other) == type(3.0): return self.value == other @@ -365,6 +408,7 @@ else: return self == other + def __ne__(self,other): if type(other) == type(3) or type(other) == type(3.0): return self.value != other @@ -373,6 +417,7 @@ else: return self != other + def __gt__(self,other): if type(other) == type(3) or type(other) == type(3.0): return self.value > other @@ -381,6 +426,7 @@ else: return self > other + def __ge__(self,other): if type(other) == type(3) or type(other) == type(3.0): return self.value >= other @@ -389,10 +435,11 @@ else: return self >= other + def __cmp__(self,other): # this function included for backwards compatibility -# As of 2.1, lists implement the "rich comparison" -# methods overloaded above. + # As of 2.1, lists implement the "rich comparison" + # methods overloaded above. if type(other) == type(3) or type(other) == type(3.0): return cmp(self.value, other) elif hasattr(other,"value"): @@ -400,6 +447,7 @@ else: return cmp(self,other) + def roll(self,min=1): if isinstance(self.sides, basestring) and self.sides.lower() == 'f': self.value = random.randint(-1, 1) @@ -409,6 +457,7 @@ self.history = [] self.history.append(self.value) + def extraroll(self): if isinstance(self.sides, basestring) and self.sides.lower() == 'f': result = random.randint(-1, 1) @@ -419,56 +468,68 @@ self.value += result self.history.append(result) + def lastroll(self): return self.history[len(self.history)-1] + def set_value(self,value): self.value = value self.history = [] self.history.append(self.value) + def modify(self,mod): self.value += mod self.history.append(mod) + def gethistory(self): return self.history[:] class static_di(di): + def __init__(self,value): di.__init__(self,value,value) self.set_value(value) class std(die_base): + def __init__(self,source=[]): die_base.__init__(self,source) # Examples of adding member functions through inheritance. + def ascending(self): result = self[:] result.sort() return result + def descending(self): result = self[:] result.sort() result.reverse() return result + def takeHighest(self,num_dice): return self.descending()[:num_dice] + def takeLowest(self,num_dice): return self.ascending()[:num_dice] + def extra(self,num): for i in range(len(self.data)): if self.data[i].lastroll() >= num: self.data[i].extraroll() return self + def open(self,num): if num <= 1: self @@ -482,12 +543,14 @@ else: return self.open(num) + def minroll(self,min): for i in range(len(self.data)): if self.data[i].lastroll() < min: self.data[i].roll(min) return self + def each(self,mod): mod = int(mod) for i in range(len(self.data)): @@ -495,6 +558,7 @@ return self + def vs(self, target): for dn in self.data: dn.target = target @@ -505,6 +569,7 @@ ## greater than or equal to against the target value and ## we only return the number of successful saves. A negative ## value will never be generated. + def sum(self): retValue = 0 for dn in self.data:
--- a/orpg/dieroller/gurps.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/dieroller/gurps.py Thu Aug 20 03:00:39 2009 -0500 @@ -53,7 +53,6 @@ from time import time, clock import random - __version__ = "$Id: gurps.py,v 1.5 2007/05/06 16:42:55 digitalxero Exp $" # gurps @@ -65,45 +64,58 @@ # these methods return new die objects for specific options # Original msk roll renamed to be easier to understand/remember + def skill(self,skill,mod): return gurpsskill(self,skill,mod) + def defaultskill(self,stat,defaultlevel,mod): return gurpsdefaultskill(self,stat,defaultlevel,mod) + def supernatural(self,skill,resistance,mod): return gurpssupernatural(self,skill,resistance,mod) + def crit_hit(self): return gurpscrit_hit(self) + def crit_headblow(self): return gurpscrit_headblow(self) + def crit_miss(self): return gurpscrit_miss(self) + def crit_unarm(self): return gurpscrit_unarm(self) + def spellfail(self): return gurpsspellfail(self) + def frightcheck(self,level,mod): return gurpsfrightcheck(self,level,mod) + def frightcheckfail(self,mod): return gurpsfrightcheckfail(self,mod) class gurpsskill(std): + def __init__(self,source=[],skill=0,mod=0): std.__init__(self,source) self.skill = skill self.mod = mod + def is_success(self): return (((self.sum()) <= self.skill+self.mod) and (self.sum() < 17)) + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]: @@ -142,12 +154,14 @@ return myStr class gurpsdefaultskill(std): + def __init__(self,source=[],stat=0,defaultlevel=0,mod=0): std.__init__(self,source) self.stat = stat self.defaultlevel = defaultlevel self.mod = mod + def is_success(self): if self.stat < 21: intSkillVal = self.stat + self.defaultlevel + self.mod @@ -155,6 +169,7 @@ intSkillVal = 20 + self.defaultlevel + self.mod return (((self.sum()) <= intSkillVal) and (self.sum() < 17)) + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]: @@ -199,12 +214,14 @@ return myStr class gurpssupernatural(std): + def __init__(self,source=[],skill=0,resistance=0,mod=0): std.__init__(self,source) self.skill = skill self.resistance = resistance self.mod = mod + def is_success(self): if self.skill+self.mod > 16: if self.resistance > 16: @@ -218,6 +235,7 @@ newSkill = self.skill+self.mod return (((self.sum()) <= newSkill) and (self.sum() < 17)) + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]: @@ -269,9 +287,11 @@ return myStr class gurpscrit_hit(std): + def __init__(self,source=[],mod=0): std.__init__(self,source) + def __str__(self): myStr = "[" + str(self.data[0]) #Variable myStr holds text and first we put a [ into it and then adds the first die rolled for a in self.data[1:]: #This is a for loop. It will do the next two lines of code for every die (except the first die which we handled in the line above) in the roll. @@ -300,10 +320,11 @@ return myStr class gurpscrit_headblow(std): - def __init__(self,source=[],mod=0): - std.__init__(self,source) + def __init__(self,source=[],mod=0): + std.__init__(self,source) - def __str__(self): + + def __str__(self): myStr = "[" + str(self.data[0]) #Variable myStr holds text and first we put a [ into it and then adds the first die rolled for a in self.data[1:]: #This is a for loop. It will do the next two lines of code for every die (except the first die which we handled in the line above) in the roll. myStr += "," #Adds a comma after each die @@ -337,9 +358,11 @@ return myStr class gurpscrit_miss(std): + def __init__(self,source=[],mod=0): std.__init__(self,source) + def __str__(self): myStr = "[" + str(self.data[0]) #Variable myStr holds text and first we put a [ into it and then adds the first die rolled for a in self.data[1:]: #This is a for loop. It will do the next two lines of code for every die (except the first die which we handled in the line above) in the roll. @@ -376,9 +399,11 @@ return myStr class gurpscrit_unarm(std): + def __init__(self,source=[],mod=0): std.__init__(self,source) + def __str__(self): myStr = "[" + str(self.data[0]) #Variable myStr holds text and first we put a [ into it and then adds the first die rolled for a in self.data[1:]: #This is a for loop. It will do the next two lines of code for every die (except the first die which we handled in the line above) in the roll. @@ -414,9 +439,11 @@ return myStr class gurpsspellfail(std): + def __init__(self,source=[],mod=0): std.__init__(self,source) + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]: @@ -455,14 +482,17 @@ return myStr class gurpsfrightcheck(std): + def __init__(self,source=[],skill=0,mod=0): std.__init__(self,source) self.skill = skill self.mod = mod + def is_success(self): return (((self.sum()) <= self.skill+self.mod) and (self.sum() < 14)) + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]: @@ -586,10 +616,12 @@ return myStr class gurpsfrightcheckfail(std): + def __init__(self,source=[],mod=0): std.__init__(self,source) self.mod = mod + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]:
--- a/orpg/dieroller/hackmaster.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/dieroller/hackmaster.py Thu Aug 20 03:00:39 2009 -0500 @@ -38,18 +38,23 @@ #hackmaster Class basically passes into functional classes class hackmaster(std): + def __init__(self,source=[]): std.__init__(self,source) + def damage(self, mod, hon): return HMdamage(self, mod, hon) + def attack(self, mod, hon): return HMattack(self, mod, hon) + def help(self): return HMhelp(self) + def severity(self, honor): return HMSeverity(self, honor) @@ -58,6 +63,7 @@ # and this appears to be invisible to the user ( if a 4 on a d4 is rolled a 3 will appear and be followed by another # die. if High honor then a 4 will appear followed by a another die. class HMdamage(std): + def __init__(self,source=[], mod = 0, hon = 0): std.__init__(self,source) self.mod = mod @@ -68,12 +74,14 @@ #here we roll the honor die self.append(static_di(self.hon)) + def damage(mod = 0, hon = 0): self.mod = mod self.hon = hon # This function is called by default to display the die string to the chat window. # Our die string attempts to explain the results + def __str__(self): myStr = "Damage " myStr += "[Damage Roll, Modifiers, Honor]: " + " [" + str(self.data[0]) @@ -85,12 +93,14 @@ return myStr # This function checks to see if we need to reroll for penetration + def check_pen(self): for i in range(len(self.data)): if self.data[i].lastroll() >= self.data[i].sides: self.pen_roll(i) #this function rolls the penetration die, and checks to see if it needs to be re-rolled again. + def pen_roll(self,num): result = int(random.uniform(1,self.data[num].sides+1)) self.data[num].value += (result - 1 + self.hon) @@ -101,6 +111,7 @@ # this function rolls for the HM Attack. the function checks for a 20 and displays critical, and a 1 # and displays fumble class HMattack(std): + def __init__(self, source=[], mod = 0, base_severity = 0, hon = 0, size = 0): std.__init__(self,source) self.size = size @@ -116,6 +127,7 @@ self.append(static_di(self.hon)) + def check_crit(self): if self.data[0] == self.data[0].sides: self.crit = 1 @@ -125,6 +137,7 @@ #this function is the out put to the chat window, it basicaly just displays the roll unless #it's a natural 20, or a natural 1 + def __str__(self): if self.crit > 0: myStr = "Critical Hit!!: " @@ -140,10 +153,12 @@ return myStr class HMhelp(std): + def __init__(self,source=[]): std.__init__(self,source) self.source = source + def __str__(self): myStr = " <br /> .attack(Bonus, Honor): <br />" myStr += " The attack roll rolles the dice and adds your bonus <br />" @@ -171,6 +186,7 @@ # the severity roll is for critical resolution. The die is rerolled and added #on a natural 8 and rerolled and subtracted on a 1 class HMSeverity(std): + def __init__(self, source =[], honor=0): std.__init__(self,source) self.source = source @@ -181,6 +197,7 @@ self.append(static_di(self.hon)) + def __str__(self): myStr = "[Severity Dice, Honor]" + " [" + str(self.data[0]) for a in self.data[1:]: @@ -189,6 +206,7 @@ myStr += "] = (" + str(self.sum()) + ")" return myStr + def CheckReroll(self): if self.data[0] == self.data[0].sides: self.crit_chain(0,1) @@ -196,6 +214,7 @@ self.crit_chain(0,-1) #this function needes moved for severity + def crit_chain(self,num,neg): result = int(random.uniform(1,self.data[num].sides+1)) self.data[num].value += (((result - 1) * neg) + self.hon)
--- a/orpg/dieroller/hero.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/dieroller/hero.py Thu Aug 20 03:00:39 2009 -0500 @@ -33,42 +33,50 @@ from time import time, clock import random - __version__ = "$Id: hero.py,v 1.15 2006/11/04 21:24:19 digitalxero Exp $" # Hero stands for "Hero system" not 20 sided die :) class hero(std): + def __init__(self,source=[]): std.__init__(self,source) # these methods return new die objects for specific options + def k(self,mod): return herok(self,mod) + def hl(self): return herohl(self) + def hk(self): return herohk(self) + def n(self): return heron(self) + def cv(self,cv,mod): return herocv(self,cv,mod) + def sk(self,sk,mod): return herosk(self,sk,mod) class herocv(std): + def __init__(self,source=[],cv=10,mod=0): std.__init__(self,source) self.cv = cv self.mod = mod + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]: @@ -83,14 +91,17 @@ return myStr class herosk(std): + def __init__(self,source=[],sk=11,mod=0): std.__init__(self,source) self.sk = sk self.mod = mod + def is_success(self): return (((self.sum()-self.mod) <= self.sk)) + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]: @@ -117,10 +128,12 @@ return myStr class herok(std): + def __init__(self,source=[],mod=0): std.__init__(self,source) self.mod = mod + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]: @@ -138,10 +151,12 @@ return myStr class herohl(std): + def __init__(self,source=[],mod=0): std.__init__(self,source) self.mod = mod + def __str__(self): myStr = "[" + str(self.data[0]) side = random.randint(1,6) @@ -182,10 +197,12 @@ return myStr class herohk(std): + def __init__(self,source=[],mod=0): std.__init__(self,source) self.mod = mod + def __str__(self): myStr = "[" + str(self.data[0]) for a in self.data[1:]: @@ -200,10 +217,12 @@ return myStr class heron(std): + def __init__(self,source=[],mod=0): std.__init__(self,source) self.bodtot=0 + def __str__(self): myStr = "[" + str(self.data[0]) if self.data[0] == 6:
--- a/orpg/dieroller/runequest.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/dieroller/runequest.py Thu Aug 20 03:00:39 2009 -0500 @@ -61,40 +61,48 @@ import random from math import floor - __version__ = "$Id: runequest.py,v 1.4 2006/11/15 12:11:22 digitalxero Exp $" # rq stands for "Runequest" class runequest(std): - def __init__(self,source=[]): - std.__init__(self,source) + + def __init__(self,source=[]): + std.__init__(self,source) -# these methods return new die objects for specific options + # these methods return new die objects for specific options - def skill(self,sk,mod,ma): - return rqskill(self,sk,mod,ma) + + def skill(self,sk,mod,ma): + return rqskill(self,sk,mod,ma) - def parry(self,sk,mod,ma,AP): - return rqparry(self,sk,mod,ma,AP) + + def parry(self,sk,mod,ma,AP): + return rqparry(self,sk,mod,ma,AP) - def dodge(self,sk,mod,ma): - return rqdodge(self,sk,mod,ma) + + def dodge(self,sk,mod,ma): + return rqdodge(self,sk,mod,ma) - def attack(self,sk,mod,ma,mindam,maxdam,bondam,trueswd): - return rqattack(self,sk,mod,ma,mindam,maxdam,bondam,trueswd) + + def attack(self,sk,mod,ma,mindam,maxdam,bondam,trueswd): + return rqattack(self,sk,mod,ma,mindam,maxdam,bondam,trueswd) - def sorcery(self,sk,mod,pow,cer,int,acc,mlt): - return rqsorcery(self,sk,mod,pow,cer,int,acc,mlt) + + def sorcery(self,sk,mod,pow,cer,int,acc,mlt): + return rqsorcery(self,sk,mod,pow,cer,int,acc,mlt) - def trainskill(self,initial,final): - return rqtrainskill(self,initial,final) + + def trainskill(self,initial,final): + return rqtrainskill(self,initial,final) - def trainskillcost(self,cost,sk): - return rqtrainskillcost(self,cost,sk) + + def trainskillcost(self,cost,sk): + return rqtrainskillcost(self,cost,sk) - def trainskilltime(self,time,sk): - return rqtrainskilltime(self,time,sk) + + def trainskilltime(self,time,sk): + return rqtrainskilltime(self,time,sk) # RQ Skill Training Cost/Time unlimited # @@ -105,32 +113,34 @@ # # class rqtrainskill(std): - def __init__(self,source=[],initial=11,final=0): - std.__init__(self,source) - self.s = initial - self.f = final + + def __init__(self,source=[],initial=11,final=0): + std.__init__(self,source) + self.s = initial + self.f = final - def __str__(self): - myStr = "Unrestricted Training" + + def __str__(self): + myStr = "Unrestricted Training" - if self.s == 0: - myStr = "Initial training completed for Cost(50) Time(20) Skill(1 + modifier)" - else: - cost = 0 - time = 0 - myStr = "Training: " + if self.s == 0: + myStr = "Initial training completed for Cost(50) Time(20) Skill(1 + modifier)" + else: + cost = 0 + time = 0 + myStr = "Training: " - while self.s < self.f and self.s < 75: - cost += self.s * 5 - time += self.s * 1 - self.s += random.uniform(1,4) + 1 + while self.s < self.f and self.s < 75: + cost += self.s * 5 + time += self.s * 1 + self.s += random.uniform(1,4) + 1 - myStr = "Training completed:\n" - myStr += "\tCost(" + str(int(cost)) + ")\n" - myStr += "\tTime(" + str(int(time)) + ")\n" - myStr += "\tSkill(" + str(int(self.s)) + ")" + myStr = "Training completed:\n" + myStr += "\tCost(" + str(int(cost)) + ")\n" + myStr += "\tTime(" + str(int(time)) + ")\n" + myStr += "\tSkill(" + str(int(self.s)) + ")" - return myStr + return myStr # RQ Skill Training Cost Limited @@ -143,38 +153,40 @@ # # class rqtrainskillcost(std): - def __init__(self,source=[],cost=11,sk=0): - std.__init__(self,source) - self.cost = cost - self.sk = sk + + def __init__(self,source=[],cost=11,sk=0): + std.__init__(self,source) + self.cost = cost + self.sk = sk - def __str__(self): - myStr = "" + + def __str__(self): + myStr = "" - if self.sk == 0 and self.cost >= 50: - myStr = "Initial training completed for Cost(50), Time(50), Skill(1 + modifier)" - else: - cost = 0 - time = 0 - icost = self.sk * 5 + if self.sk == 0 and self.cost >= 50: + myStr = "Initial training completed for Cost(50), Time(50), Skill(1 + modifier)" + else: + cost = 0 + time = 0 + icost = self.sk * 5 - myStr = "Training: " + myStr = "Training: " - while (cost + icost) < self.cost: - if self.sk >= 75: - break + while (cost + icost) < self.cost: + if self.sk >= 75: + break - cost += icost - time += self.sk * 1 - self.sk += random.uniform(1,4) + 1 - icost = self.sk * 5 + cost += icost + time += self.sk * 1 + self.sk += random.uniform(1,4) + 1 + icost = self.sk * 5 - myStr = "Training completed: " - myStr += "Cost(" + str(int(cost)) + ") " - myStr += "Time(" + str(int(time)) + ") " - myStr += "Skill(" + str(int(self.sk)) + ")" + myStr = "Training completed: " + myStr += "Cost(" + str(int(cost)) + ") " + myStr += "Time(" + str(int(time)) + ") " + myStr += "Skill(" + str(int(self.sk)) + ")" - return myStr + return myStr # RQ Skill Training Time Limited @@ -187,38 +199,40 @@ # # class rqtrainskilltime(std): - def __init__(self,source=[],time=11,sk=0): - std.__init__(self,source) - self.time = time - self.sk = sk + + def __init__(self,source=[],time=11,sk=0): + std.__init__(self,source) + self.time = time + self.sk = sk - def __str__(self): - myStr = "" + + def __str__(self): + myStr = "" - if self.sk == 0 and self.time >= 20: - myStr = "Initial training completed for Cost(50), Time(50), Skill(1 + modifier)" - else: - cost = 0 - time = 0 - itime = self.sk * 1 + if self.sk == 0 and self.time >= 20: + myStr = "Initial training completed for Cost(50), Time(50), Skill(1 + modifier)" + else: + cost = 0 + time = 0 + itime = self.sk * 1 - myStr = "Trainingsss: " + myStr = "Trainingsss: " - while (time + itime) < self.time: - if self.sk >= 75: - break + while (time + itime) < self.time: + if self.sk >= 75: + break - cost += self.sk * 5 - time += itime - self.sk += random.uniform(1,4) + 1 - itime = self.sk * 5 + cost += self.sk * 5 + time += itime + self.sk += random.uniform(1,4) + 1 + itime = self.sk * 5 - myStr = "Training completed: " - myStr += "Cost(" + str(int(cost)) + ") " - myStr += "Time(" + str(int(time)) + ") " - myStr += "Skill(" + str(int(self.sk)) + ")" + myStr = "Training completed: " + myStr += "Cost(" + str(int(cost)) + ") " + myStr += "Time(" + str(int(time)) + ") " + myStr += "Skill(" + str(int(self.sk)) + ")" - return myStr + return myStr # RQ Skill Roll # @@ -245,60 +259,61 @@ # if ( $fum == 100 ) { $fum = '00'; }; # class rqskill(std): - def __init__(self,source=[],sk=11,mod=0,ma=0): - std.__init__(self,source) - self.sk = sk - self.mod = mod - self.ma = ma + + def __init__(self,source=[],sk=11,mod=0,ma=0): + std.__init__(self,source) + self.sk = sk + self.mod = mod + self.ma = ma - def is_success(self): - return (((self.sum() <= (self.sk + self.mod)) or (self.sum() <= 5)) and (self.sum() <= 95)) - - def is_ma(self): - return (self.sum() <= self.ma) + + def is_success(self): + return (((self.sum() <= (self.sk + self.mod)) or (self.sum() <= 5)) and (self.sum() <= 95)) - def is_special(self): - return (self.sum() <= int(floor((self.sk + self.mod)/5))) - - def is_critical(self): - return (self.sum() <= int(floor((self.sk + self.mod) / 20))) + + def is_ma(self): + return (self.sum() <= self.ma) - def is_fumble(self): - if ( self.sk >= 100 ): - fum = 0 - else: - fum = (100 - self.sk ) - final_fum = ( 100 - int( floor( fum/20 ) ) ) - return ( self.sum() >= final_fum ) + + def is_special(self): + return (self.sum() <= int(floor((self.sk + self.mod)/5))) + + + def is_critical(self): + return (self.sum() <= int(floor((self.sk + self.mod) / 20))) - def __str__(self): - strAdd="+" - swapmod= self.mod - if self.mod < 0: - strAdd= "-" - swapmod= -self.mod - modSum = self.sum() - # build output string - myStr = " (" + str(modSum) + ")" - myStr += " vs [" + str(self.sk) + strAdd + str(swapmod) + "]" + + def is_fumble(self): + if ( self.sk >= 100 ): + fum = 0 + else: + fum = (100 - self.sk ) + final_fum = ( 100 - int( floor( fum/20 ) ) ) + return ( self.sum() >= final_fum ) - if self.is_fumble(): - myStr += " <b><font color=red>Fumble!</font></b>" - elif self.is_critical(): - myStr += " <b><font color=green>Critical!</font></b>" - elif self.is_special(): - myStr += " <i><font color=green>Special!</font></i>" - elif self.is_success() and self.is_ma(): - myStr += " <i><font color=green>Special!</font></i>" - elif self.is_success(): - myStr += " <font color=blue>Success!</font>" - else: - myStr += " <font color=red>Failure!</font>" + + def __str__(self): + strAdd="+" + swapmod= self.mod + if self.mod < 0: + strAdd= "-" + swapmod= -self.mod + modSum = self.sum() + # build output string + myStr = " (" + str(modSum) + ")" + myStr += " vs [" + str(self.sk) + strAdd + str(swapmod) + "]" - Diff = self.sk - modSum - myStr += " </font>" + if self.is_fumble(): myStr += " <b><font color=red>Fumble!</font></b>" + elif self.is_critical(): myStr += " <b><font color=green>Critical!</font></b>" + elif self.is_special(): myStr += " <i><font color=green>Special!</font></i>" + elif self.is_success() and self.is_ma(): myStr += " <i><font color=green>Special!</font></i>" + elif self.is_success(): myStr += " <font color=blue>Success!</font>" + else: myStr += " <font color=red>Failure!</font>" - return myStr + Diff = self.sk - modSum + myStr += " </font>" + + return myStr # # RQ Parry Roll @@ -310,79 +325,87 @@ # class rqparry(std): - def __init__(self,source=[],sk=11,mod=0,ma=0,AP=0): - std.__init__(self,source) - self.sk = sk - self.mod = mod - self.ma = ma - self.AP = AP + + def __init__(self,source=[],sk=11,mod=0,ma=0,AP=0): + std.__init__(self,source) + self.sk = sk + self.mod = mod + self.ma = ma + self.AP = AP - def is_success(self): - return (((self.sum() <= (self.sk + self.mod)) or (self.sum() <= 5)) and (self.sum() <= 95)) + + def is_success(self): + return (((self.sum() <= (self.sk + self.mod)) or (self.sum() <= 5)) and (self.sum() <= 95)) - def is_special(self): - return (self.sum() <= int(floor((self.sk + self.mod) / 5))) + + def is_special(self): + return (self.sum() <= int(floor((self.sk + self.mod) / 5))) - def is_ma(self): - return (self.sum() <= self.ma) + + def is_ma(self): + return (self.sum() <= self.ma) - def is_riposte(self): - return (self.sum() <= (self.ma / 5)) + + def is_riposte(self): + return (self.sum() <= (self.ma / 5)) - def is_critical(self): - return ( ( self.sum() <= int( floor( ( self.sk + self.mod )/20 ) ) ) ) + + def is_critical(self): + return ( ( self.sum() <= int( floor( ( self.sk + self.mod )/20 ) ) ) ) - def is_fumble(self): - if ( self.sk >= 100 ): - fum = 0 - else: - fum = (100 - self.sk ) - final_fum = ( 100 - int( floor( fum/20 ) ) ) - return ( self.sum() >= final_fum ) + + def is_fumble(self): + if ( self.sk >= 100 ): + fum = 0 + else: + fum = (100 - self.sk ) + final_fum = ( 100 - int( floor( fum/20 ) ) ) + return ( self.sum() >= final_fum ) - def __str__(self): - - # get fumble roll result in case needed - fum_roll = random.randint(1,100) + + def __str__(self): - # get special AP - spec_AP = int( floor ( self.AP * 1.5 ) ) + # get fumble roll result in case needed + fum_roll = random.randint(1,100) + + # get special AP + spec_AP = int( floor ( self.AP * 1.5 ) ) - # figure out +/- for modifer - strAdd="+" - swapmod= self.mod - if self.mod < 0: - strAdd= "-" - swapmod= -self.mod - modSum = self.sum() + # figure out +/- for modifer + strAdd="+" + swapmod= self.mod + if self.mod < 0: + strAdd= "-" + swapmod= -self.mod + modSum = self.sum() - # build output string - myStr = " (" + str(modSum) + ")" - myStr += " vs [" + str(self.sk) + strAdd + str(swapmod) + "]" + # build output string + myStr = " (" + str(modSum) + ")" + myStr += " vs [" + str(self.sk) + strAdd + str(swapmod) + "]" - if self.is_fumble(): - myStr += " <b><font color=red>Fumble!</font> See Fumble Chart [" + str(fum_roll) + "]</b>" - elif self.is_critical() and self.is_riposte(): - myStr += " <b><font color=green>Critical!</font> All damage blocked!</b>" - myStr += " Riposte next SR" - elif self.is_critical(): - myStr += " <b><font color=green>Critical!</font> All damage blocked!</b>" - elif self.is_special and self.is_riposte(): - myStr += " <i><font color=green>Special!</font> Weapon/Shield AP [" + str(spec_AP) + "]</i>" - myStr += " Riposte next SR" - elif self.is_special(): - myStr += " <i><font color=green>Special!</font> Weapon/Shield AP [" + str(spec_AP) + "]</i>" - elif self.is_success() and self.is_ma(): - myStr += " <i><font color=green>Special!</font> Weapon/Shield AP [" + str(spec_AP) + "]</i>" - elif self.is_success(): - myStr += " <font color=blue>Success!</font> Weapon/Shield AP [" + str(self.AP) + "]" - else: - myStr += " <font color=red>Failure!</font>" + if self.is_fumble(): + myStr += " <b><font color=red>Fumble!</font> See Fumble Chart [" + str(fum_roll) + "]</b>" + elif self.is_critical() and self.is_riposte(): + myStr += " <b><font color=green>Critical!</font> All damage blocked!</b>" + myStr += " Riposte next SR" + elif self.is_critical(): + myStr += " <b><font color=green>Critical!</font> All damage blocked!</b>" + elif self.is_special and self.is_riposte(): + myStr += " <i><font color=green>Special!</font> Weapon/Shield AP [" + str(spec_AP) + "]</i>" + myStr += " Riposte next SR" + elif self.is_special(): + myStr += " <i><font color=green>Special!</font> Weapon/Shield AP [" + str(spec_AP) + "]</i>" + elif self.is_success() and self.is_ma(): + myStr += " <i><font color=green>Special!</font> Weapon/Shield AP [" + str(spec_AP) + "]</i>" + elif self.is_success(): + myStr += " <font color=blue>Success!</font> Weapon/Shield AP [" + str(self.AP) + "]" + else: + myStr += " <font color=red>Failure!</font>" - Diff = self.sk - modSum - myStr += " </font>" + Diff = self.sk - modSum + myStr += " </font>" - return myStr + return myStr # RQ Dodge Roll # @@ -393,79 +416,87 @@ # class rqdodge(std): - def __init__(self,source=[],sk=11,mod=0,ma=0,AP=0): - std.__init__(self,source) - self.sk = sk - self.mod = mod - self.ma = ma - self.AP = AP + + def __init__(self,source=[],sk=11,mod=0,ma=0,AP=0): + std.__init__(self,source) + self.sk = sk + self.mod = mod + self.ma = ma + self.AP = AP - def is_success(self): - return (((self.sum() <= (self.sk + self.mod)) or (self.sum() <= 5)) and (self.sum() <= 95)) + + def is_success(self): + return (((self.sum() <= (self.sk + self.mod)) or (self.sum() <= 5)) and (self.sum() <= 95)) - def is_special(self): - return (self.sum() <= int(floor((self.sk + self.mod) / 5))) + + def is_special(self): + return (self.sum() <= int(floor((self.sk + self.mod) / 5))) - def is_ma(self): - return (self.sum() <= self.ma) + + def is_ma(self): + return (self.sum() <= self.ma) - def is_riposte(self): - return (self.sum() <= (self.ma / 5)) + + def is_riposte(self): + return (self.sum() <= (self.ma / 5)) - def is_critical(self): - return ( ( self.sum() <= int( floor( ( self.sk + self.mod )/20 ) ) ) ) + + def is_critical(self): + return ( ( self.sum() <= int( floor( ( self.sk + self.mod )/20 ) ) ) ) - def is_fumble(self): - if ( self.sk >= 100 ): - fum = 0 - else: - fum = (100 - self.sk ) - final_fum = ( 100 - int( floor( fum/20 ) ) ) - return ( self.sum() >= final_fum ) + + def is_fumble(self): + if ( self.sk >= 100 ): + fum = 0 + else: + fum = (100 - self.sk ) + final_fum = ( 100 - int( floor( fum/20 ) ) ) + return ( self.sum() >= final_fum ) - def __str__(self): - - # get fumble roll result in case needed - fum_roll = random.randint(1,100) + + def __str__(self): - # get special AP - spec_AP = int( floor ( self.AP * 1.5 ) ) + # get fumble roll result in case needed + fum_roll = random.randint(1,100) + + # get special AP + spec_AP = int( floor ( self.AP * 1.5 ) ) - # figure out +/- for modifer - strAdd="+" - swapmod= self.mod - if self.mod < 0: - strAdd= "-" - swapmod= -self.mod - modSum = self.sum() + # figure out +/- for modifer + strAdd="+" + swapmod= self.mod + if self.mod < 0: + strAdd= "-" + swapmod= -self.mod + modSum = self.sum() - # build output string - myStr = " (" + str(modSum) + ")" - myStr += " vs [" + str(self.sk) + strAdd + str(swapmod) + "]" + # build output string + myStr = " (" + str(modSum) + ")" + myStr += " vs [" + str(self.sk) + strAdd + str(swapmod) + "]" - if self.is_fumble(): - myStr += " <b><font color=red>Fumble!</font> See Fumble Chart [" + str(fum_roll) + "]</b>" - elif self.is_critical() and self.is_riposte(): - myStr += " <b><font color=green>Critical!</font> All damage dodged!</b>" - myStr += " Riposte on next SR" - elif self.is_critical(): - myStr += " <b><font color=green>Critical!</font> All damage dodged!</b>" - elif self.is_special and self.is_riposte(): - myStr += " <i><font color=green>Special!</font> Damage dodged</b>" - myStr += " Riposte on next SR" - elif self.is_special(): - myStr += " <i><font color=green>Special!</font> Damage dodged</b>" - elif self.is_success() and self.is_ma(): - myStr += " <i><font color=green>Special!</font> Damage dodged</b>" - elif self.is_success(): - myStr += " <font color=blue>Success!</font> Damage dodged</b>" - else: - myStr += " <font color=red>Failure!</font>" + if self.is_fumble(): + myStr += " <b><font color=red>Fumble!</font> See Fumble Chart [" + str(fum_roll) + "]</b>" + elif self.is_critical() and self.is_riposte(): + myStr += " <b><font color=green>Critical!</font> All damage dodged!</b>" + myStr += " Riposte on next SR" + elif self.is_critical(): + myStr += " <b><font color=green>Critical!</font> All damage dodged!</b>" + elif self.is_special and self.is_riposte(): + myStr += " <i><font color=green>Special!</font> Damage dodged</b>" + myStr += " Riposte on next SR" + elif self.is_special(): + myStr += " <i><font color=green>Special!</font> Damage dodged</b>" + elif self.is_success() and self.is_ma(): + myStr += " <i><font color=green>Special!</font> Damage dodged</b>" + elif self.is_success(): + myStr += " <font color=blue>Success!</font> Damage dodged</b>" + else: + myStr += " <font color=red>Failure!</font>" - Diff = self.sk - modSum - myStr += " </font>" + Diff = self.sk - modSum + myStr += " </font>" - return myStr + return myStr @@ -478,108 +509,116 @@ # skill%, modifer, ma%, min weap dam, max weap dam, dam bonus, truesword_enabled # class rqattack(std): - def __init__(self,source=[],sk=11,mod=0,ma=0,mindam=0,maxdam=0,bondam=0,trueswd=0): - std.__init__(self,source) - self.sk = sk - self.mod = mod - self.ma = ma - self.mindam = mindam - self.maxdam = maxdam - self.bondam = bondam - self.trueswd = trueswd + + def __init__(self,source=[],sk=11,mod=0,ma=0,mindam=0,maxdam=0,bondam=0,trueswd=0): + std.__init__(self,source) + self.sk = sk + self.mod = mod + self.ma = ma + self.mindam = mindam + self.maxdam = maxdam + self.bondam = bondam + self.trueswd = trueswd + + + def is_success(self): + return (((self.sum() <= (self.sk + self.mod)) or (self.sum() <= 5)) and (self.sum() <= 95)) - def is_success(self): - return (((self.sum() <= (self.sk + self.mod)) or (self.sum() <= 5)) and (self.sum() <= 95)) + + def is_ma(self): + return (self.sum() <= self.ma) - def is_ma(self): - return (self.sum() <= self.ma) + + def is_special(self): + return (self.sum() <= int(floor((self.sk + self.mod) / 5))) - def is_special(self): - return (self.sum() <= int(floor((self.sk + self.mod) / 5))) + + def is_critical(self): + return ((self.sum() <= int(floor((self.sk + self.mod) / 20)))) - def is_critical(self): - return ((self.sum() <= int(floor((self.sk + self.mod) / 20)))) - - def is_supercritical(self): - return (self.sum() == 1) + + def is_supercritical(self): + return (self.sum() == 1) - def is_fumble(self): - if ( self.sk >= 100 ): - fum = 0 - else: - fum = (100 - self.sk ) - final_fum = ( 100 - int( floor( fum/20 ) ) ) - return ( self.sum() >= final_fum ) + + def is_fumble(self): + if ( self.sk >= 100 ): + fum = 0 + else: + fum = (100 - self.sk ) + final_fum = ( 100 - int( floor( fum/20 ) ) ) + return ( self.sum() >= final_fum ) - def __str__(self): + + def __str__(self): - # get fumble roll result in case needed - fum_roll = random.randint(1,100) + # get fumble roll result in case needed + fum_roll = random.randint(1,100) - # get hit location roll result in case needed - location = random.randint(1,20) - myStr = " to the ["+ str(location) + "] " - if location < 5: - myStr += "<B>Right Leg</B>" - elif location < 9: - myStr += "<B>Left Leg</B>" - elif location < 12: - myStr += "<B>Abdomen</B>" - elif location < 13: - myStr += "<B>Chest</B>" - elif location < 16: - myStr += "<B>Right Arm</B>" - elif location < 19: - myStr += "<B>Left Arm</B>" - else: - myStr += "<B>Head</B>" - hit_loc = myStr + # get hit location roll result in case needed + location = random.randint(1,20) + myStr = " to the ["+ str(location) + "] " + if location < 5: + myStr += "<B>Right Leg</B>" + elif location < 9: + myStr += "<B>Left Leg</B>" + elif location < 12: + myStr += "<B>Abdomen</B>" + elif location < 13: + myStr += "<B>Chest</B>" + elif location < 16: + myStr += "<B>Right Arm</B>" + elif location < 19: + myStr += "<B>Left Arm</B>" + else: + myStr += "<B>Head</B>" + hit_loc = myStr - # get normal damage in case needed - norm_damage = random.randint(self.mindam*(self.trueswd+1),self.maxdam*(self.trueswd+1)) + self.bondam - norm_damage_string = "{" + str( self.mindam*(self.trueswd+1) ) + "-" - norm_damage_string += str(self.maxdam*(self.trueswd+1)) + "+" + str(self.bondam) - norm_damage_string += "}[" + str(norm_damage) + "] " + # get normal damage in case needed + norm_damage = random.randint(self.mindam*(self.trueswd+1),self.maxdam*(self.trueswd+1)) + self.bondam + norm_damage_string = "{" + str( self.mindam*(self.trueswd+1) ) + "-" + norm_damage_string += str(self.maxdam*(self.trueswd+1)) + "+" + str(self.bondam) + norm_damage_string += "}[" + str(norm_damage) + "] " - # get special/critical damage in case needed - crit_damage = random.randint( self.mindam*(self.trueswd+2), self.maxdam*(self.trueswd+2) ) + self.bondam - crit_damage_string = "{" + str( self.mindam*(self.trueswd+2) ) + "-" + str(self.maxdam*(self.trueswd+2)) + "+" + str(self.bondam) + "}[" + str(crit_damage) + "] " + # get special/critical damage in case needed + crit_damage = random.randint( self.mindam*(self.trueswd+2), self.maxdam*(self.trueswd+2) ) + self.bondam + crit_damage_string = "{" + str( self.mindam*(self.trueswd+2) ) + "-" + str(self.maxdam*(self.trueswd+2)) + "+" + str(self.bondam) + "}[" + str(crit_damage) + "] " - # get supercritical damage in case needed - super_damage = norm_damage + self.maxdam - super_damage_string = "{" + str( self.mindam*(self.trueswd+1) ) + "-" - super_damage_string += str(self.maxdam*(self.trueswd+1)) + "+" + str(self.maxdam) - super_damage_string += "+" + str(self.bondam) + "}[" + str(super_damage) + "] " + # get supercritical damage in case needed + super_damage = norm_damage + self.maxdam + super_damage_string = "{" + str( self.mindam*(self.trueswd+1) ) + "-" + super_damage_string += str(self.maxdam*(self.trueswd+1)) + "+" + str(self.maxdam) + super_damage_string += "+" + str(self.bondam) + "}[" + str(super_damage) + "] " - # figure out +/- for modifer - strAdd="+" - swapmod= self.mod - if self.mod < 0: - strAdd= "-" - swapmod= -self.mod - modSum = self.sum() + # figure out +/- for modifer + strAdd="+" + swapmod= self.mod + if self.mod < 0: + strAdd= "-" + swapmod= -self.mod + modSum = self.sum() - # build output string - myStr = " (" + str(modSum) + ")" - myStr += " vs [" + str(self.sk) + strAdd + str(swapmod) + "]" + # build output string + myStr = " (" + str(modSum) + ")" + myStr += " vs [" + str(self.sk) + strAdd + str(swapmod) + "]" - if self.is_fumble(): - myStr += " <b><font color=red>Fumble!</font> See Fumble Chart [" + str(fum_roll) + "]</b>" - elif (self.is_supercritical() and self.is_success()): - myStr += " <b><font color=green>Super Critical!</font></b> Damage: " + str(super_damage_string) + "<u>No Armor Stops</u>" + str(hit_loc) - elif (self.is_critical() and self.is_success()): - myStr += " <b><font color=green>Critical!</font></b> Damage: " + str(crit_damage_string) + "<u>No Armor Stops</u>" + str(hit_loc) - elif ( self.is_special() and self.is_success() ): - myStr += " <i><font color=green>Special!</font></i> Damage: " + str(crit_damage_string) + str(hit_loc) - elif (self.is_success() and self.is_ma()): - myStr += " <i><font color=green>Special!</font></i> Damage: " + str(crit_damage_string) + str(hit_loc) - elif self.is_success(): - myStr += " <font color=blue>Success!</font> Damage: " + str(norm_damage_string) + str(hit_loc) - else: - myStr += " <font color=red>Failure!</font>" + if self.is_fumble(): + myStr += " <b><font color=red>Fumble!</font> See Fumble Chart [" + str(fum_roll) + "]</b>" + elif (self.is_supercritical() and self.is_success()): + myStr += " <b><font color=green>Super Critical!</font></b> Damage: " + str(super_damage_string) + "<u>No Armor Stops</u>" + str(hit_loc) + elif (self.is_critical() and self.is_success()): + myStr += " <b><font color=green>Critical!</font></b> Damage: " + str(crit_damage_string) + "<u>No Armor Stops</u>" + str(hit_loc) + elif ( self.is_special() and self.is_success() ): + myStr += " <i><font color=green>Special!</font></i> Damage: " + str(crit_damage_string) + str(hit_loc) + elif (self.is_success() and self.is_ma()): + myStr += " <i><font color=green>Special!</font></i> Damage: " + str(crit_damage_string) + str(hit_loc) + elif self.is_success(): + myStr += " <font color=blue>Success!</font> Damage: " + str(norm_damage_string) + str(hit_loc) + else: + myStr += " <font color=red>Failure!</font>" - return myStr + return myStr # # @@ -595,102 +634,107 @@ # Hold: (-2% per point in spell Held) # class rqsorcery(std): - def __init__(self,source=[],sk=11,mod=0,pow=0,cer=0,int=0,acc=0,mlt=0): - std.__init__(self,source) - self.sk = sk # sorcery skill - self.mod = mod # additional modifier ( from duration, range, etc ) - self.pow = pow # boost pow and additional pow ( from duration, range, etc ) - self.cer = cer # ceremony d6 - self.int = int # intensity ( -3% ) - self.acc = acc # accelerate ( -5% ) - self.mlt = mlt # multispell ( -10% ) + + def __init__(self,source=[],sk=11,mod=0,pow=0,cer=0,int=0,acc=0,mlt=0): + std.__init__(self,source) + self.sk = sk # sorcery skill + self.mod = mod # additional modifier ( from duration, range, etc ) + self.pow = pow # boost pow and additional pow ( from duration, range, etc ) + self.cer = cer # ceremony d6 + self.int = int # intensity ( -3% ) + self.acc = acc # accelerate ( -5% ) + self.mlt = mlt # multispell ( -10% ) - def is_success(self): - return (((self.sum() <= (self.sk + self.mod)) or (self.sum() <= 5)) and (self.sum() <= 95)) + + def is_success(self): + return (((self.sum() <= (self.sk + self.mod)) or (self.sum() <= 5)) and (self.sum() <= 95)) - def is_special(self): - return ( ( self.sum() <= int( floor( ( self.sk + self.mod )/5 ) ) ) ) + + def is_special(self): + return ( ( self.sum() <= int( floor( ( self.sk + self.mod )/5 ) ) ) ) - def is_critical(self): - return ( ( self.sum() <= int( floor( ( self.sk + self.mod )/20 ) ) ) ) + + def is_critical(self): + return ( ( self.sum() <= int( floor( ( self.sk + self.mod )/20 ) ) ) ) - def is_fumble(self): - if ( self.sk >= 100 ): - fum = 0 - else: - fum = (100 - self.sk ) - final_fum = ( 100 - int( floor( fum/20 ) ) ) - return ( self.sum() >= final_fum ) + + def is_fumble(self): + if ( self.sk >= 100 ): + fum = 0 + else: + fum = (100 - self.sk ) + final_fum = ( 100 - int( floor( fum/20 ) ) ) + return ( self.sum() >= final_fum ) - def __str__(self): + + def __str__(self): - # get fumble roll result in case needed - fum_roll = random.randint(2,12) - if fum_roll == 12 : - fum_string = "<br /><font color=purple>Caster temporarily forgets spell. Make an INTx5 roll each day to remember.</font>" - if fum_roll == 11 : - fum_string = "<br /><font color=purple>Caster temporarily forgets spell. Make an INTx5 roll each hour to remember. </font>" - if fum_roll == 10 : - fum_string = "<br /><font color=purple>Spell produces reverse of the intended effect. </font>" - if fum_roll == 9 : - fum_string = "<br /><font color=purple>Caster is Stunned. Roll INTx3 to recover at SR 10 each round. </font>" - if fum_roll == 8 : - fum_string = "<br /><font color=purple>Caster takes 2D6 Damage to THP </font>" - if fum_roll == 7 : - fum_string = "<br /><font color=purple>Spell produces reverse of the intended effect at 2x Intensity. </font>" - if fum_roll == 6 : - fum_string = "<br /><font color=purple>Spell is cast on companions (if harmful) or on random nearby foes (if beneficial) </font>" - if fum_roll == 5 : - fum_string = "<br /><font color=purple>Caster takes 1d6 Damage to Head </font>" - if fum_roll == 4 : - fum_string = "<br /><font color=purple>Spell is cast on caster (if harmful) or on random nearby foe (if beneficial) </font>" - if fum_roll == 3 : - fum_string = "<br /><font color=purple>Caster takes 1d6 Damage to THP </font>" - if fum_roll == 2 : - fum_string = "<br /><font color=purple>Caster takes 1 point of Damage to Head </font>" + # get fumble roll result in case needed + fum_roll = random.randint(2,12) + if fum_roll == 12 : + fum_string = "<br /><font color=purple>Caster temporarily forgets spell. Make an INTx5 roll each day to remember.</font>" + if fum_roll == 11 : + fum_string = "<br /><font color=purple>Caster temporarily forgets spell. Make an INTx5 roll each hour to remember. </font>" + if fum_roll == 10 : + fum_string = "<br /><font color=purple>Spell produces reverse of the intended effect. </font>" + if fum_roll == 9 : + fum_string = "<br /><font color=purple>Caster is Stunned. Roll INTx3 to recover at SR 10 each round. </font>" + if fum_roll == 8 : + fum_string = "<br /><font color=purple>Caster takes 2D6 Damage to THP </font>" + if fum_roll == 7 : + fum_string = "<br /><font color=purple>Spell produces reverse of the intended effect at 2x Intensity. </font>" + if fum_roll == 6 : + fum_string = "<br /><font color=purple>Spell is cast on companions (if harmful) or on random nearby foes (if beneficial) </font>" + if fum_roll == 5 : + fum_string = "<br /><font color=purple>Caster takes 1d6 Damage to Head </font>" + if fum_roll == 4 : + fum_string = "<br /><font color=purple>Spell is cast on caster (if harmful) or on random nearby foe (if beneficial) </font>" + if fum_roll == 3 : + fum_string = "<br /><font color=purple>Caster takes 1d6 Damage to THP </font>" + if fum_roll == 2 : + fum_string = "<br /><font color=purple>Caster takes 1 point of Damage to Head </font>" - # roll ceremony - ceremony_roll = random.randint( self.cer, (self.cer*6) ) + # roll ceremony + ceremony_roll = random.randint( self.cer, (self.cer*6) ) - # subtract manipulations - extra_mod = self.mod - self.mod += ceremony_roll - self.int*3 - self.acc*5 - self.mlt*10 + # subtract manipulations + extra_mod = self.mod + self.mod += ceremony_roll - self.int*3 - self.acc*5 - self.mlt*10 - # add up power cost - extra_pow = self.pow - self.pow += self.int + self.mlt + self.acc - special_pow = int( floor( ( self.pow )/2 ) ) + # add up power cost + extra_pow = self.pow + self.pow += self.int + self.mlt + self.acc + special_pow = int( floor( ( self.pow )/2 ) ) - # figure out +/- for modifer - strAdd="+" - swapmod= self.mod - if self.mod < 0: - strAdd= "-" - swapmod= -self.mod - modSum = self.sum() + # figure out +/- for modifer + strAdd="+" + swapmod= self.mod + if self.mod < 0: + strAdd= "-" + swapmod= -self.mod + modSum = self.sum() - # build output string - myStr = " (" + str(modSum) + ")" - myStr += " vs [" + str(self.sk) + strAdd + str(swapmod) + "]" + # build output string + myStr = " (" + str(modSum) + ")" + myStr += " vs [" + str(self.sk) + strAdd + str(swapmod) + "]" - if self.is_fumble(): - myStr += " <b><font color=red>Fumble!</font> POW Cost: [" + str(self.pow) + "],</b> " + fum_string - elif self.is_critical(): - myStr += " <b><font color=green>Critical!</font></b> POW Cost: [1] " - elif self.is_special(): - myStr += " <i><font color=green>Special!</font></i> POW Cost: [" + str(special_pow) + "] " - elif self.is_success(): - myStr += " <font color=blue>Success!</font> POW Cost: [" + str(self.pow) + "] " - else: - myStr += " <font color=red>Failure!</font> POW Cost: [1]" + if self.is_fumble(): + myStr += " <b><font color=red>Fumble!</font> POW Cost: [" + str(self.pow) + "],</b> " + fum_string + elif self.is_critical(): + myStr += " <b><font color=green>Critical!</font></b> POW Cost: [1] " + elif self.is_special(): + myStr += " <i><font color=green>Special!</font></i> POW Cost: [" + str(special_pow) + "] " + elif self.is_success(): + myStr += " <font color=blue>Success!</font> POW Cost: [" + str(self.pow) + "] " + else: + myStr += " <font color=red>Failure!</font> POW Cost: [1]" - # print spell details - myStr += "<br /> --- Other Modifiers:[" + str( extra_mod ) + "], " - myStr += "Extra POW:[" + str( extra_pow ) + "], " - myStr += "Ceremony:[+" + str( ceremony_roll ) + "%], " - myStr += "Intensity(-3):[" + str( self.int ) + "], " - myStr += "Accelerate(-5):[" + str( self.acc ) + "], " - myStr += "Multispell(-10):[" + str( self.mlt ) + "] ---" + # print spell details + myStr += "<br /> --- Other Modifiers:[" + str( extra_mod ) + "], " + myStr += "Extra POW:[" + str( extra_pow ) + "], " + myStr += "Ceremony:[+" + str( ceremony_roll ) + "%], " + myStr += "Intensity(-3):[" + str( self.int ) + "], " + myStr += "Accelerate(-5):[" + str( self.acc ) + "], " + myStr += "Multispell(-10):[" + str( self.mlt ) + "] ---" - return myStr - + return myStr
--- a/orpg/dieroller/savage.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/dieroller/savage.py Thu Aug 20 03:00:39 2009 -0500 @@ -20,8 +20,6 @@ # from die import * -#from whrandom import randint -#import random import string from random import * __version__ = "$Id: savage.py,v 1.2 2007/05/06 16:42:55 digitalxero Exp $" @@ -29,32 +27,41 @@ # Savage, as in Savage Worlds class sw(std): #def __init__(self,source=[], wnd=1, loc="rnd", chmod=0): + def __init__(self,source=[],fmod=0): std.__init__(self,source) # these methods return new die objects for specific options + def fright(self,fearmod=0): return fright(self,fearmod=0) + def kob(self,wnd,loc): return kob(self,wnd=1,loc="rnd") + def ooc(self): return ooc(self) + def ract(self,chmod=0): return ract(self,chmod=0) + def vcrit(self): return vcrit(self) + def fortune(self): return fortune(self) + def freak(self): return freak(self) + def swdhelps(self): return swdhelps(self) @@ -67,6 +74,7 @@ # Usage: [fright()] # [fright(6)] - if the fear modifier of the monster was 6 #----------------- + def __init__(self,fmod=0): global fear std.__init__(self) @@ -74,6 +82,7 @@ #def sum(self): + def __str__(self): global fear iroll = randint(1,20) @@ -118,6 +127,7 @@ # [kob(3,"h") - If 3 wounds were received that sent the player to the Knockout Blow Table with a called shot to the head #--------------------- global wound, loca + def __init__(self, wnd, loc="rnd"): global wound, loca std.__init__(self, wnd) @@ -129,6 +139,7 @@ mystr = "You need to supply a number for the wound." return mystr + def __str__(self): global wound, loca itbl = "no" @@ -235,11 +246,13 @@ # [ract(-2)] - A -2 Charisma modifier #---------------------- global charisma + def __init__(self,chmod=0): global charisma std.__init__(self) charisma = chmod + def __str__(self): global charisma r1roll = randint(2,12) @@ -269,9 +282,11 @@ # roll and displays the results of the roll. This will also display altitude information for flying vehicles. # Usage: [ooc()] #-------------------- + def __init__(self): std.__init__(self) + def __str__(self): ooroll = randint(2,12) oodescripton = "Something" @@ -331,9 +346,11 @@ # modifiers to this roll # Usage [vcrit()] #---------------- + def __init__(self): std.__init__(self) + def __str__(self): chitroll = randint(2,12) if chitroll == 2: @@ -373,9 +390,11 @@ class swdhelps(std): #Display help information for this die roller - it will list all the available commands, and how to use them + def __init__(self): std.__init__(self) + def __str__(self): myStr = "<table border='1' valign='top'>\ <tr>\ @@ -421,9 +440,11 @@ return myStr class fortune(std): + def __init___(self): std.__init__(self) + def __str__(self): forroll = randint(2,12) if forroll == 2 or forroll == 12: #Need to roll on Freak Event Table @@ -453,13 +474,16 @@ myStr = "["+fortune+" ("+str(forroll)+")] ==>"+fdescription return myStr + def freak(self): return fortunefreak(self) class freak(std): + def __init__(self): std.__init__(self) + def __str__(self): feroll = randint(1,10) if feroll == 1: @@ -500,8 +524,10 @@ return myStr class rdm(std): #If I get the time and the inspiration - I may try to incorporate a Random Table roller... I need to think about this one. + def __init__(self): std.__init__(self) + def __str__(self): return myStr
--- a/orpg/dieroller/shadowrun.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/dieroller/shadowrun.py Thu Aug 20 03:00:39 2009 -0500 @@ -43,20 +43,24 @@ # the objective is to find the highest die total out of rolled dice. This is then generally # used as the target in a 'Success Test' (for which .vs functions) from die import * - + __version__ = "1.0" class shadowrun(std): + def __init__(self,source=[],target=2): std.__init__(self,source) + def vs(self,target): return srVs(self, target) + def open(self): return srOpen(self) class srVs(std): + def __init__(self,source=[], target=2): std.__init__(self, source) # In Shadowrun, not target number may be below 2. All defaults are set to two and any @@ -69,6 +73,7 @@ # made the dieroller generic enough to use any die type self.openended(self[0].sides) + def openended(self,num): if num <= 1: self @@ -82,6 +87,7 @@ else: return self.openended(num) + def __sum__(self): s = 0 for r in self.data: @@ -89,6 +95,7 @@ s += 1 return s + def __str__(self): if len(self.data) > 0: myStr = "[" + str(self.data[0]) @@ -102,10 +109,12 @@ return myStr class srOpen(std): + def __init__(self,source=[]): std.__init__(self,source) self.openended(self[0].sides) + def openended(self,num): if num <= 1: self @@ -119,6 +128,7 @@ else: return self.openended(num) + def __sum__(self): s = 0 for r in self.data: @@ -126,6 +136,7 @@ s = r return s + def __str__(self): if len(self.data) > 0: myStr = "[" + str(self.data[0])
--- a/orpg/dieroller/sr4.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/dieroller/sr4.py Thu Aug 20 03:00:39 2009 -0500 @@ -68,25 +68,32 @@ GLITCH_NUMBER = 1 class sr4(std): + def __init__(self,source=[]): std.__init__(self,source) self.threshold = None self.init_attrib = None + def vs(self,threshold=0): return sr4vs(self, threshold) + def edge(self,threshold=0): return sr4vs(self, threshold, 1) + def init(self,init_attrib=0): return sr4init(self, init_attrib) + def initedge(self,init_attrib=0): return sr4init(self, init_attrib, 1) + def edgeinit(self,init_attrib=0): return sr4init(self, init_attrib, 1) + def countEdge(self,num): if num <= 1: self @@ -106,6 +113,7 @@ else: return self.countEdge(num) + def countHits(self,num): for i in range(len(self.data)): if (self.data[i].lastroll() >= MIN_TARGET_NUMBER): @@ -115,6 +123,7 @@ self.ones += 1 self.total += 1 + def __str__(self): if len(self.data) > 0: self.hits = 0 @@ -145,6 +154,7 @@ return myStr class sr4init(sr4): + def __init__(self,source=[],init_attrib=1,edge=0): std.__init__(self,source) if init_attrib < 2: @@ -159,6 +169,7 @@ self.countEdge(self.dicesides) self.countHits(self.dicesides) + def __str__(self): if len(self.data) > 0: firstpass = 0 @@ -182,6 +193,7 @@ return myStr class sr4vs(sr4): + def __init__(self,source=[], threshold=1, edge=0): std.__init__(self, source) if threshold < 0: @@ -196,6 +208,7 @@ self.countEdge(self.dicesides) self.countHits(self.dicesides) + def __str__(self): if len(self.data) > 0: firstpass = 0 @@ -222,6 +235,7 @@ myStr = "[] = (0)" return myStr + def CheckIfGlitch(ones, hits, total_dice): if (ones * 2) >= total_dice: if hits >= 1:
--- a/orpg/dieroller/srex.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/dieroller/srex.py Thu Aug 20 03:00:39 2009 -0500 @@ -59,19 +59,24 @@ __version__ = "1.1" class srex(std): + def __init__(self,source=[]): std.__init__(self,source) + def vs(self,actualtarget=4,tnrange=3): #reports all tns around specified, max distance of range return srVs(self,actualtarget,(actualtarget-tnrange),(actualtarget+tnrange)) + def vswide(self,actualtarget=4,maxtarget=12): #wide simply means it reports TNs from 2 to a specified max. return srVs(self,actualtarget,2,maxtarget) + def open(self): #unchanged from standard shadowrun open. return srOpen(self) class srVs(std): + def __init__(self,source=[],actualtarget=4,mintn=2,maxtn=12): std.__init__(self, source) if actualtarget > 30: @@ -100,6 +105,7 @@ # made the dieroller generic enough to use any die type self.openended(self[0].sides) + def openended(self,num): if num <= 1: self @@ -116,6 +122,7 @@ return self.openended(num) #count successes, by looping through each die, and checking it against the currently set TN + def __sum__(self): s = 0 for r in self.data: @@ -126,6 +133,7 @@ #a modified sum, but this one takes a target argument, and is there because otherwise it is difficult to loop through #tns counting successes against each one without changing target, which is rather dangerous as the original TN could #easily be lost. + def xsum(self,curtarget): s = 0 for r in self.data: @@ -134,6 +142,7 @@ return s + def __str__(self): if len(self.data) > 0: myStr = "[" + str(self.data[0]) @@ -154,10 +163,12 @@ return myStr class srOpen(std): + def __init__(self,source=[]): std.__init__(self,source) self.openended(self[0].sides) + def openended(self,num): if num <= 1: self @@ -171,6 +182,7 @@ else: return self.openended(num) + def __sum__(self): s = 0 for r in self.data: @@ -178,6 +190,7 @@ s = r return s + def __str__(self): if len(self.data) > 0: myStr = "[" + str(self.data[0])
--- a/orpg/dieroller/trinity.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/dieroller/trinity.py Thu Aug 20 03:00:39 2009 -0500 @@ -37,47 +37,52 @@ class trinity(std): - def __init__(self,source=[],target=7,targetthr=0): - std.__init__(self,source) - self.target = target - self.targetthr = targetthr + + def __init__(self,source=[],target=7,targetthr=0): + std.__init__(self,source) + self.target = target + self.targetthr = targetthr - def vs(self,target): - self.target = target - return self + + def vs(self,target): + self.target = target + return self - def thr(self,targetthr): - self.targetthr = targetthr - return self + + def thr(self,targetthr): + self.targetthr = targetthr + return self - def sum(self): - rolls = [] - s = 0 - b = 0 - for a in self.data: - rolls.extend(a.gethistory()) - for r in rolls: - if r >= self.target: - s += 1 - elif r == 1: - b -= 1 - if s == 0: - return b - else: - return s + + def sum(self): + rolls = [] + s = 0 + b = 0 + for a in self.data: + rolls.extend(a.gethistory()) + for r in rolls: + if r >= self.target: + s += 1 + elif r == 1: + b -= 1 + if s == 0: + return b + else: + return s - def __str__(self): - if len(self.data) > 0: - myStr = "[" + str(self.data[0]) - for a in self.data[1:]: - myStr += "," - myStr += str(a) - if self.sum() < 0: - myStr += "] result of a (" + str(self.sum()) + ") botch" - elif self.sum() == 0: - myStr += "] result of a failure" - else: - myStr += "] result of (" + str(self.sum()) + ") success" + + def __str__(self): + if len(self.data) > 0: + myStr = "[" + str(self.data[0]) + for a in self.data[1:]: + myStr += "," + myStr += str(a) + if self.sum() < 0: + myStr += "] result of a (" + str(self.sum()) + ") botch" + elif self.sum() == 0: + myStr += "] result of a failure" + else: + myStr += "] result of (" + str(self.sum()) + ") success" - return myStr + return myStr
--- a/orpg/dieroller/utils.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/dieroller/utils.py Thu Aug 20 03:00:39 2009 -0500 @@ -42,29 +42,32 @@ from runequest import * from savage import * from trinity import * -from orpg.orpgCore import component - import re rollers = ['std','wod','d20','hero','shadowrun', 'sr4','hackmaster','srex','wodex', 'gurps', 'runequest', 'sw', 'trinity'] class roller_manager: + def __init__(self,roller_class="d20"): try: self.setRoller(roller_class) except: self.roller_class = "std" + def setRoller(self,roller_class): try: rollers.index(roller_class) self.roller_class = roller_class except: raise Exception, "Invalid die roller!" + def getRoller(self): return self.roller_class + def listRollers(self): return rollers + def stdDieToDClass(self,match): s = match.group(0) (num,sides) = s.split('d') @@ -77,6 +80,7 @@ return "(" + num.strip() + "**" + self.roller_class + "(" + sides.strip() + "))" # Use this to convert ndm-style (3d6) dice to d_base format + def convertTheDieString(self,s): reg = re.compile("\d+\s*[a-zA-Z]+\s*[\dFf]+") (result, num_matches) = reg.subn(self.stdDieToDClass, s) @@ -88,6 +92,8 @@ except: pass return result + def proccessRoll(self,s): - return str(eval(self.convertTheDieString(s))) -#component.add('dieroller', roller_manager()) + return str(eval(self.convertTheDieString(s))) + +DiceManager = roller_manager
--- a/orpg/dieroller/wod.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/dieroller/wod.py Thu Aug 20 03:00:39 2009 -0500 @@ -36,19 +36,23 @@ class wod(std): + def __init__(self,source=[],target=0,targetthr=0): std.__init__(self,source) self.target = target self.targetthr = targetthr + def vs(self,target): self.target = target return self + def thr(self,targetthr): self.targetthr = targetthr return self + def sum(self): rolls = [] s = 0 @@ -70,6 +74,7 @@ s = 0 return s + def __str__(self): if len(self.data) > 0: myStr = "[" + str(self.data[0])
--- a/orpg/dieroller/wodex.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/dieroller/wodex.py Thu Aug 20 03:00:39 2009 -0500 @@ -36,25 +36,32 @@ __version__ = "$Id: wodex.py,v 1.9 2007/05/06 16:42:55 digitalxero Exp $" class wodex(std): + def __init__(self,source=[]): std.__init__(self,source) + def vs(self,actualtarget=6): return oldwodVs(self,actualtarget,(6)) + def wod(self,actualtarget=8): return newwodVs(self,actualtarget,(8)) + def exalt(self, actualtarget=7): return exaltVs(self, actualtarget) + def exaltDmg(self, actualtarget=7): return exaltDmg(self, actualtarget) + def vswide(self,actualtarget=6,maxtarget=10): #wide simply means it reports TNs from 2 to a specified max. return oldwodVs(self,actualtarget,2,maxtarget) class oldwodVs(std): + def __init__(self,source=[],actualtarget=6,mintn=2,maxtn=10): std.__init__(self, source) if actualtarget > 10: @@ -84,6 +91,7 @@ #count successes, by looping through each die, and checking it against the currently set TN #1's subtract successes. + def __sum__(self): s = 0 for r in self.data: @@ -96,6 +104,7 @@ #a modified sum, but this one takes a target argument, and is there because otherwise it is difficult to loop through #tns counting successes against each one without changing target, which is rather dangerous as the original TN could #easily be lost. 1s subtract successes from everything. + def xsum(self,curtarget): s = 0 for r in self.data: @@ -106,6 +115,7 @@ return s + def __str__(self): if len(self.data) > 0: myStr = "[" + str(self.data[0]) @@ -126,6 +136,7 @@ return myStr class newwodVs(std): + def __init__(self,source=[],actualtarget=8,mintn=8,maxtn=8): std.__init__(self, source) if actualtarget > 30: @@ -156,6 +167,7 @@ #a modified sum, but this one takes a target argument, and is there because otherwise it is difficult to loop through #tns counting successes against each one without changing target, which is rather dangerous as the original TN could #easily be lost. 1s subtract successes from original but not re-rolls. + def xsum(self,curtarget,subones=1): s = 0 done = 1 @@ -173,6 +185,7 @@ else: return self.xsum(0) + def openended(self,num): if num <= 1: self @@ -187,6 +200,7 @@ return self.openended(num) + def __str__(self): if len(self.data) > 0: myStr = "[" + str(self.data[0]) @@ -207,6 +221,7 @@ return myStr class exaltVs(std): + def __init__(self, source=[], actualtarget=7): std.__init__(self, source) @@ -219,6 +234,7 @@ self.target = actualtarget + def xsum(self, target): s = 0 @@ -231,6 +247,7 @@ return s + def __str__(self): if len(self.data) > 0: myStr = str(self.data) @@ -249,6 +266,7 @@ return myStr class exaltDmg(std): + def __init__(self, source=[], actualtarget=7): std.__init__(self, source) if actualtarget > 10: @@ -259,6 +277,7 @@ else: self.target = actualtarget + def xsum(self, target): s = 0 @@ -267,6 +286,7 @@ s += 1 return s + def __str__(self): if len(self.data) > 0: myStr = str(self.data)
--- a/orpg/gametree/gametree.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/gametree/gametree.py Thu Aug 20 03:00:39 2009 -0500 @@ -32,23 +32,19 @@ from orpg.orpg_windows import * from orpg.orpgCore import component from orpg.dirpath import dir_struct -from nodehandlers import core -import orpg.gametree.nodehandlers.containers -import orpg.gametree.nodehandlers.forms -import orpg.gametree.nodehandlers.dnd3e -import orpg.gametree.nodehandlers.dnd35 -import orpg.gametree.nodehandlers.chatmacro -import orpg.gametree.nodehandlers.map_miniature_nodehandler -import orpg.gametree.nodehandlers.minilib -import orpg.gametree.nodehandlers.rpg_grid -import orpg.gametree.nodehandlers.d20 -import orpg.gametree.nodehandlers.StarWarsd20 -import orpg.gametree.nodehandlers.voxchat -from gametree_version import GAMETREE_VERSION +from nodehandlers import core import string import urllib import time -import os +import os + +from orpg.tools.orpg_log import logger +from orpg.tools.decorators import debugging +from orpg.gametree.nodehandlers import containers, forms, dnd3e, dnd35, chatmacro +from orpg.gametree.nodehandlers import map_miniature_nodehandler +from orpg.gametree.nodehandlers import minilib, rpg_grid, d20, StarWarsd20, voxchat + +from gametree_version import GAMETREE_VERSION STD_MENU_DELETE = wx.NewId() STD_MENU_DESIGN = wx.NewId() @@ -78,12 +74,12 @@ TOP_TREE_PROP = wx.NewId() TOP_FEATURES = wx.NewId() -class game_tree(wx.TreeCtrl): +class game_tree(wx.TreeCtrl): + @debugging def __init__(self, parent, id): wx.TreeCtrl.__init__(self,parent,id, wx.DefaultPosition, wx.DefaultSize,style=wx.TR_EDIT_LABELS | wx.TR_HAS_BUTTONS) self.orpgLog = component.get('log') - self.orpgLog.log("Enter game_tree", ORPG_DEBUG) self.validate = component.get('validate') self.xml = component.get('xml') self.settings = component.get('settings') @@ -106,7 +102,6 @@ self.Bind(wx.EVT_KEY_UP, self.on_key_up) self.id = 1 self.dragging = False - self.root_dir = dir_struct["home"] self.last_save_dir = dir_struct["user"] #Create tree from default if it does not exist @@ -118,53 +113,50 @@ self.rename_flag = 0 self.image_cache = {} self.orpgLog.log("Exit game_tree", ORPG_DEBUG) - + + @debugging def add_nodehandler(self, nodehandler, nodeclass): - self.orpgLog.log("Enter game_tree->add_nodehandler(self, nodehandler, nodeclass)", ORPG_DEBUG) if not self.nodehandlers.has_key(nodehandler): self.nodehandlers[nodehandler] = nodeclass else: self.orpgLog.log("Nodehandler for " + nodehandler + " already exists!", ORPG_DEBUG, True) - self.orpgLog.log("Exit game_tree->add_nodehandler(self, nodehandler, nodeclass)", ORPG_DEBUG) - + + @debugging def remove_nodehandler(self, nodehandler): - self.orpgLog.log("Enter game_tree->remove_nodehandler(self, nodehandler)", ORPG_DEBUG) if self.nodehandlers.has_key(nodehandler): del self.nodehandlers[nodehandler] else: self.orpgLog.log("No nodehandler for " + nodehandler + " exists!", ORPG_DEBUG, True) - self.orpgLog.log("Exit game_tree->remove_nodehandler(self, nodehandler)", ORPG_DEBUG) - + + @debugging def init_nodehandlers(self): - self.orpgLog.log("Enter game_tree->init_nodehandlers(self)", ORPG_DEBUG) - self.add_nodehandler('group_handler', orpg.gametree.nodehandlers.containers.group_handler) - self.add_nodehandler('tabber_handler', orpg.gametree.nodehandlers.containers.tabber_handler) - self.add_nodehandler('splitter_handler', orpg.gametree.nodehandlers.containers.splitter_handler) - self.add_nodehandler('form_handler', orpg.gametree.nodehandlers.forms.form_handler) - self.add_nodehandler('textctrl_handler', orpg.gametree.nodehandlers.forms.textctrl_handler) - self.add_nodehandler('listbox_handler', orpg.gametree.nodehandlers.forms.listbox_handler) - self.add_nodehandler('link_handler', orpg.gametree.nodehandlers.forms.link_handler) - self.add_nodehandler('webimg_handler', orpg.gametree.nodehandlers.forms.webimg_handler) - self.add_nodehandler('dnd3echar_handler', orpg.gametree.nodehandlers.dnd3e.dnd3echar_handler) - self.add_nodehandler('dnd35char_handler', orpg.gametree.nodehandlers.dnd35.dnd35char_handler) - self.add_nodehandler('macro_handler', orpg.gametree.nodehandlers.chatmacro.macro_handler) - self.add_nodehandler('map_miniature_handler', orpg.gametree.nodehandlers.map_miniature_nodehandler.map_miniature_handler) - self.add_nodehandler('minilib_handler', orpg.gametree.nodehandlers.minilib.minilib_handler) - self.add_nodehandler('mini_handler', orpg.gametree.nodehandlers.minilib.mini_handler) - self.add_nodehandler('rpg_grid_handler', orpg.gametree.nodehandlers.rpg_grid.rpg_grid_handler) - self.add_nodehandler('d20char_handler', orpg.gametree.nodehandlers.d20.d20char_handler) - self.add_nodehandler('SWd20char_handler', orpg.gametree.nodehandlers.StarWarsd20.SWd20char_handler) - self.add_nodehandler('voxchat_handler', orpg.gametree.nodehandlers.voxchat.voxchat_handler) + self.add_nodehandler('group_handler', containers.group_handler) + self.add_nodehandler('tabber_handler', containers.tabber_handler) + self.add_nodehandler('splitter_handler', containers.splitter_handler) + self.add_nodehandler('form_handler', forms.form_handler) + self.add_nodehandler('textctrl_handler', forms.textctrl_handler) + self.add_nodehandler('listbox_handler', forms.listbox_handler) + self.add_nodehandler('link_handler', forms.link_handler) + self.add_nodehandler('webimg_handler', forms.webimg_handler) + self.add_nodehandler('dnd3echar_handler', dnd3e.dnd3echar_handler) + self.add_nodehandler('dnd35char_handler', dnd35.dnd35char_handler) + self.add_nodehandler('macro_handler', chatmacro.macro_handler) + self.add_nodehandler('map_miniature_handler', map_miniature_nodehandler.map_miniature_handler) + self.add_nodehandler('minilib_handler', minilib.minilib_handler) + self.add_nodehandler('mini_handler', minilib.mini_handler) + self.add_nodehandler('rpg_grid_handler', rpg_grid.rpg_grid_handler) + self.add_nodehandler('d20char_handler', d20.d20char_handler) + self.add_nodehandler('SWd20char_handler', StarWarsd20.SWd20char_handler) + self.add_nodehandler('voxchat_handler', voxchat.voxchat_handler) self.add_nodehandler('file_loader', core.file_loader) self.add_nodehandler('node_loader', core.node_loader) self.add_nodehandler('url_loader', core.url_loader) self.add_nodehandler('min_map', core.min_map) - self.orpgLog.log("Exit game_tree->init_nodehandlers(self)", ORPG_DEBUG) # event = wxKeyEvent - # set to be called by wxWindows by EVT_CHAR macro in __init__ + # set to be called by wxWindows by EVT_CHAR macro in __init__ + @debugging def on_key_up(self, evt): - self.orpgLog.log("Enter game_tree->on_key_up(self, evt)", ORPG_DEBUG) key_code = evt.GetKeyCode() if self.dragging and (key_code == wx.WXK_SHIFT): curSelection = self.GetSelection() @@ -177,10 +169,9 @@ obj.on_drop(evt) self.drag_obj = None evt.Skip() - self.orpgLog.log("Exit game_tree->on_key_up(self, evt)", ORPG_DEBUG) - + + @debugging def on_char(self, evt): - self.orpgLog.log("Enter game_tree->on_char(self, evt)", ORPG_DEBUG) key_code = evt.GetKeyCode() curSelection = self.GetSelection() # Get the current selection if evt.ShiftDown() and ((key_code == wx.WXK_UP) or (key_code == wx.WXK_DOWN)) and not self.dragging: @@ -194,7 +185,6 @@ self.drag_obj = obj elif key_code == wx.WXK_LEFT: self.Collapse(curSelection) - elif key_code == wx.WXK_DELETE: # Handle the delete key if curSelection: nextSelect = self.GetItemParent(curSelection) @@ -208,13 +198,10 @@ self.rename_flag = 1 self.EditLabel(curSelection) evt.Skip() - self.orpgLog.log("Exit game_tree->on_char(self, evt)", ORPG_DEBUG) - - ## locate_valid_tree - ## GUI based dialogs to locate/fix missing treefile issues --Snowdog 3/05 - def locate_valid_tree(self, error, msg, dir, filename): + + @debugging + def locate_valid_tree(self, error, msg, dir, filename): ## --Snowdog 3/05 """prompts the user to locate a new tree file or create a new one""" - self.orpgLog.log("Enter game_tree->locate_valid_tree(self, error, msg, dir, filename)", ORPG_DEBUG) response = wx.MessageDialog(self, msg, error, wx.YES|wx.NO|wx.ICON_ERROR) if response == wx.YES: file = None @@ -224,16 +211,14 @@ dlg.Destroy() if not file: self.load_tree(error=1) else: self.load_tree(file) - self.orpgLog.log("Exit game_tree->locate_valid_tree(self, error, msg, dir, filename)", ORPG_DEBUG) return else: self.validate.config_file("tree.xml","default_tree.xml") self.load_tree(error=1) - self.orpgLog.log("Exit game_tree->locate_valid_tree(self, error, msg, dir, filename)", ORPG_DEBUG) return - + + @debugging def load_tree(self, filename=dir_struct["user"]+'tree.xml', error=0): - self.orpgLog.log("Enter game_tree->load_tree(self, filename, error)", ORPG_DEBUG) self.settings.set_setting("gametree", filename) tmp = None xml_dom = None @@ -256,7 +241,6 @@ fn = filename[ ((filename.rfind(os.sep))+len(os.sep)):] self.locate_valid_tree("Gametree Error", emsg, dir_struct["user"], fn) self.orpgLog.log(emsg, ORPG_GENERAL) - self.orpgLog.log("Exit game_tree->load_tree(self, filename, error)", ORPG_DEBUG) return if not xml_dom: @@ -272,7 +256,6 @@ "(Selecting 'No' will cause a new default gametree to be generated)" self.locate_valid_tree("Corrupt Gametree!", emsg, dir_struct["user"], fn) self.orpgLog.log(emsg, ORPG_GENERAL) - self.orpgLog.log("Exit game_tree->load_tree(self, filename, error)", ORPG_DEBUG) return if xml_dom._get_tagName() != "gametree": @@ -323,16 +306,15 @@ os.rename(filename,filename+".corrupt") self.validate.config_file("tree.xml","default_tree.xml") self.load_tree(error=1) - self.orpgLog.log("Exit game_tree->load_tree(self, filename, error)", ORPG_DEBUG) - + + @debugging def build_std_menu(self, obj=None): - self.orpgLog.log("Enter game_tree->build_std_menu(self, obj)", ORPG_DEBUG) - # build useful menu useful_menu = wx.Menu() useful_menu.Append(STD_MENU_NODE_USEFUL,"Use&ful") useful_menu.Append(STD_MENU_NODE_USELESS,"Use&less") - useful_menu.Append(STD_MENU_NODE_INDIFFERENT,"&Indifferent") + useful_menu.Append(STD_MENU_NODE_INDIFFERENT,"&Indifferent") + # build standard menu self.std_menu = wx.Menu() self.std_menu.SetTitle("game tree") @@ -386,20 +368,16 @@ self.Bind(wx.EVT_MENU, self.on_load_new_tree, id=TOP_NEW_TREE) self.Bind(wx.EVT_MENU, self.on_tree_prop, id=TOP_TREE_PROP) self.Bind(wx.EVT_MENU, self.on_insert_features, id=TOP_FEATURES) - self.orpgLog.log("Exit game_tree->build_std_menu(self, obj)", ORPG_DEBUG) - + + @debugging def do_std_menu(self, evt, obj): - self.orpgLog.log("Enter game_tree->do_std_menu(self, evt, obj)", ORPG_DEBUG) - try: - self.std_menu.Enable(STD_MENU_MAP, obj.checkToMapMenu()) - except: - self.std_menu.Enable(STD_MENU_MAP, obj.map_aware()) + try: self.std_menu.Enable(STD_MENU_MAP, obj.checkToMapMenu()) + except: self.std_menu.Enable(STD_MENU_MAP, obj.map_aware()) self.std_menu.Enable(STD_MENU_CLONE, obj.can_clone()) self.PopupMenu(self.std_menu) - self.orpgLog.log("Exit game_tree->do_std_menu(self, evt, obj)", ORPG_DEBUG) - + + @debugging def strip_html(self, player): - self.orpgLog.log("Enter game_tree->strip_html(self, player)", ORPG_DEBUG) ret_string = "" x = 0 in_tag = 0 @@ -414,26 +392,23 @@ else : ret_string = ret_string + player[0][x] self.orpgLog.log(ret_string, ORPG_DEBUG) - self.orpgLog.log("Exit game_tree->strip_html(self, player)", ORPG_DEBUG) return ret_string - + + @debugging def on_receive_data(self, data, player): - self.orpgLog.log("Enter game_tree->on_receive_data(self, data, player)", ORPG_DEBUG) beg = string.find(data,"<tree>") end = string.rfind(data,"</tree>") data = data[6:end] self.insert_xml(data) - self.orpgLog.log("Exit game_tree->on_receive_data(self, data, player)", ORPG_DEBUG) - + + @debugging def on_send_to_chat(self, evt): - self.orpgLog.log("Enter game_tree->on_send_to_chat(self, evt)", ORPG_DEBUG) item = self.GetSelection() obj = self.GetPyData(item) obj.on_send_to_chat(evt) - self.orpgLog.log("Exit game_tree->on_send_to_chat(self, evt)", ORPG_DEBUG) - + + @debugging def on_whisper_to(self, evt): - self.orpgLog.log("Enter game_tree->on_whisper_to(self, evt)", ORPG_DEBUG) players = self.session.get_players() opts = [] myid = self.session.get_id() @@ -458,10 +433,9 @@ for s in selections: player_ids.append(players[s][2]) self.chat.whisper_to_players(obj.tohtml(),player_ids) - self.orpgLog.log("Exit game_tree->on_whisper_to(self, evt)", ORPG_DEBUG) - + + @debugging def on_export_html(self, evt): - self.orpgLog.log("Enter game_tree->on_export_html(self, evt)", ORPG_DEBUG) f = wx.FileDialog(self,"Select a file", self.last_save_dir,"","HTML (*.html)|*.html",wx.SAVE) if f.ShowModal() == wx.ID_OK: item = self.GetSelection() @@ -476,35 +450,32 @@ file.close() self.last_save_dir, throwaway = os.path.split( f.GetPath() ) f.Destroy() - os.chdir(self.root_dir) - self.orpgLog.log("Exit game_tree->on_export_html(self, evt)", ORPG_DEBUG) - + os.chdir(dir_struct["home"]) + + @debugging def indifferent(self, evt): - self.orpgLog.log("Enter game_tree->indifferent(self, evt)", ORPG_DEBUG) item = self.GetSelection() obj = self.GetPyData(item) obj.usefulness("indifferent") - self.orpgLog.log("Exit game_tree->indifferent(self, evt)", ORPG_DEBUG) - + + @debugging def useful(self, evt): - self.orpgLog.log("Enter game_tree->useful(self, evt)", ORPG_DEBUG) item = self.GetSelection() obj = self.GetPyData(item) obj.usefulness("useful") - self.orpgLog.log("Exit game_tree->useful(self, evt)", ORPG_DEBUG) - + + @debugging def useless(self, evt): - self.orpgLog.log("Enter game_tree->useless(self, evt)", ORPG_DEBUG) item = self.GetSelection() obj = self.GetPyData(item) obj.usefulness("useless") - self.orpgLog.log("Exit game_tree->useless(self, evt)", ORPG_DEBUG) - + + @debugging def on_email(self,evt): pass - + + @debugging def on_send_to(self, evt): - self.orpgLog.log("Enter game_tree->on_send_to(self, evt)", ORPG_DEBUG) players = self.session.get_players() opts = [] myid = self.session.get_id() @@ -528,10 +499,9 @@ for s in selections: self.session.send(xmldata,players[s][2]) dlg.Destroy() - self.orpgLog.log("Exit game_tree->on_send_to(self, evt)", ORPG_DEBUG) - + + @debugging def on_icon(self, evt): - self.orpgLog.log("Enter game_tree->on_icon(self, evt)", ORPG_DEBUG) icons = self.icons.keys() icons.sort() dlg = wx.SingleChoiceDialog(self,"Choose Icon?","Change Icon",icons) @@ -541,10 +511,9 @@ obj = self.GetPyData(item) obj.change_icon(key) dlg.Destroy() - self.orpgLog.log("Exit game_tree->on_icon(self, evt)", ORPG_DEBUG) - + + @debugging def on_wizard(self, evt): - self.orpgLog.log("Enter game_tree->on_wizard(self, evt)", ORPG_DEBUG) item = self.GetSelection() obj = self.GetPyData(item) name = "New " + obj.master_dom.getAttribute("name") @@ -554,10 +523,9 @@ xml_data += "</nodehandler>" self.insert_xml(xml_data) self.orpgLog.log(xml_data, ORPG_DEBUG) - self.orpgLog.log("Exit game_tree->on_wizard(self, evt)", ORPG_DEBUG) - + + @debugging def on_clone(self, evt): - self.orpgLog.log("Enter game_tree->on_clone(self, evt)", ORPG_DEBUG) item = self.GetSelection() obj = self.GetPyData(item) if obj.can_clone(): @@ -570,55 +538,49 @@ parent = obj.master_dom._get_parentNode() xml_dom = parent.insertBefore(xml_dom, obj.master_dom) self.load_xml(xml_dom, parent_node, prev_sib) - self.orpgLog.log("Exit game_tree->on_clone(self, evt)", ORPG_DEBUG) - + + @debugging def on_save(self, evt): """save node to a xml file""" - self.orpgLog.log("Enter game_tree->on_save(self, evt)", ORPG_DEBUG) item = self.GetSelection() obj = self.GetPyData(item) obj.on_save(evt) - os.chdir(self.root_dir) - self.orpgLog.log("Exit game_tree->on_save(self, evt)", ORPG_DEBUG) - + os.chdir(dir_struct["home"]) + + @debugging def on_save_tree_as(self, evt): - self.orpgLog.log("Enter game_tree->on_save_tree_as(self, evt)", ORPG_DEBUG) f = wx.FileDialog(self,"Select a file", self.last_save_dir,"","*.xml",wx.SAVE) if f.ShowModal() == wx.ID_OK: self.save_tree(f.GetPath()) self.last_save_dir, throwaway = os.path.split( f.GetPath() ) f.Destroy() - os.chdir(self.root_dir) - self.orpgLog.log("Exit game_tree->on_save_tree_as(self, evt)", ORPG_DEBUG) - + os.chdir(dir_struct["home"]) + + @debugging def on_save_tree(self, evt=None): - self.orpgLog.log("Enter game_tree->on_save_tree(self, evt)", ORPG_DEBUG) filename = self.settings.get_setting("gametree") self.save_tree(filename) - self.orpgLog.log("Exit game_tree->on_save_tree(self, evt)", ORPG_DEBUG) - + + @debugging def save_tree(self, filename=dir_struct["user"]+'tree.xml'): - self.orpgLog.log("Enter game_tree->save_tree(self, filename)", ORPG_DEBUG) self.master_dom.setAttribute("version",GAMETREE_VERSION) self.settings.set_setting("gametree",filename) file = open(filename,"w") file.write(self.xml.toxml(self.master_dom,1)) file.close() - self.orpgLog.log("Exit game_tree->save_tree(self, filename)", ORPG_DEBUG) - + + @debugging def on_load_new_tree(self, evt): - self.orpgLog.log("Enter game_tree->on_load_new_tree(self, evt)", ORPG_DEBUG) f = wx.FileDialog(self,"Select a file", self.last_save_dir,"","*.xml",wx.OPEN) if f.ShowModal() == wx.ID_OK: self.load_tree(f.GetPath()) self.last_save_dir, throwaway = os.path.split( f.GetPath() ) f.Destroy() - os.chdir(self.root_dir) - self.orpgLog.log("Exit game_tree->on_load_new_tree(self, evt)", ORPG_DEBUG) - + os.chdir(dir_struct["home"]) + + @debugging def on_insert_file(self, evt): """loads xml file into the tree""" - self.orpgLog.log("Enter game_tree->on_insert_file(self, evt)", ORPG_DEBUG) if self.last_save_dir == ".": self.last_save_dir = dir_struct["user"] f = wx.FileDialog(self,"Select a file", self.last_save_dir,"","*.xml",wx.OPEN) @@ -626,62 +588,49 @@ self.insert_xml(open(f.GetPath(),"r").read()) self.last_save_dir, throwaway = os.path.split( f.GetPath() ) f.Destroy() - os.chdir(self.root_dir) - self.orpgLog.log("Exit game_tree->on_insert_file(self, evt)", ORPG_DEBUG) - + os.chdir(dir_struct["home"]) + + @debugging def on_insert_url(self, evt): """loads xml url into the tree""" - self.orpgLog.log("Enter game_tree->on_insert_url(self, evt)", ORPG_DEBUG) dlg = wx.TextEntryDialog(self,"URL?","Insert URL", "http://") if dlg.ShowModal() == wx.ID_OK: path = dlg.GetValue() file = urllib.urlopen(path) self.insert_xml(file.read()) dlg.Destroy() - self.orpgLog.log("Exit game_tree->on_insert_url(self, evt)", ORPG_DEBUG) - + + @debugging def on_insert_features(self, evt): - self.orpgLog.log("Enter game_tree->on_insert_features(self, evt)", ORPG_DEBUG) self.insert_xml(open(dir_struct["template"]+"feature.xml","r").read()) - self.orpgLog.log("Exit game_tree->on_insert_features(self, evt)", ORPG_DEBUG) - + + @debugging def on_tree_prop(self, evt): - self.orpgLog.log("Enter game_tree->on_tree_prop(self, evt)", ORPG_DEBUG) dlg = gametree_prop_dlg(self, self.settings) if dlg.ShowModal() == wx.ID_OK: pass dlg.Destroy() - self.orpgLog.log("Exit game_tree->on_tree_prop(self, evt)", ORPG_DEBUG) - + + @debugging def on_node_design(self, evt): - self.orpgLog.log("Enter game_tree->on_node_design(self, evt)", ORPG_DEBUG) - item = self.GetSelection() obj = self.GetPyData(item) obj.on_design(evt) - - self.orpgLog.log("Exit game_tree->on_node_design(self, evt)", ORPG_DEBUG) - + + @debugging def on_node_use(self, evt): - self.orpgLog.log("Enter game_tree->on_node_use(self, evt)", ORPG_DEBUG) - item = self.GetSelection() obj = self.GetPyData(item) obj.on_use(evt) - - self.orpgLog.log("Exit game_tree->on_node_use(self, evt)", ORPG_DEBUG) - + + @debugging def on_node_pp(self, evt): - self.orpgLog.log("Enter game_tree->on_node_pp(self, evt)", ORPG_DEBUG) - item = self.GetSelection() obj = self.GetPyData(item) obj.on_html_view(evt) - - self.orpgLog.log("Exit game_tree->on_node_pp(self, evt)", ORPG_DEBUG) - + + @debugging def on_del(self, evt): - self.orpgLog.log("Enter game_tree->on_del(self, evt)", ORPG_DEBUG) status_value = "none" try: item = self.GetSelection() @@ -721,30 +670,23 @@ msg = wx.MessageDialog(None,"Unknown error deleting node.","Delete Error",wx.OK) msg.ShowModal() msg.Destroy() - - self.orpgLog.log("Exit game_tree->on_del(self, evt)", ORPG_DEBUG) - + + @debugging def on_about(self, evt): - self.orpgLog.log("Enter game_tree->on_about(self, evt)", ORPG_DEBUG) - item = self.GetSelection() obj = self.GetPyData(item) about = MyAboutBox(self,obj.about()) about.ShowModal() about.Destroy() - - self.orpgLog.log("Exit game_tree->on_about(self, evt)", ORPG_DEBUG) - + + @debugging def on_send_to_map(self, evt): - self.orpgLog.log("Enter game_tree->on_send_to_map(self, evt)", ORPG_DEBUG) - item = self.GetSelection() obj = self.GetPyData(item) if hasattr(obj,"on_send_to_map"): obj.on_send_to_map(evt) - - self.orpgLog.log("Exit game_tree->on_send_to_map(self, evt)", ORPG_DEBUG) - + + @debugging def insert_xml(self, txt): self.orpgLog.log("Enter game_tree->insert_xml(self, txt)", ORPG_DEBUG) #Updated to allow safe merging of gametree files @@ -781,11 +723,10 @@ child = self.master_dom._get_firstChild() xml_dom = self.master_dom.insertBefore(xml_dom,child) self.load_xml(xml_dom,self.root,self.root) - self.orpgLog.log("Exit game_tree->insert_xml(self, txt)", ORPG_DEBUG) - + + @debugging def build_img_list(self): """make image list""" - self.orpgLog.log("Enter game_tree->build_img_list(self)", ORPG_DEBUG) helper = img_helper() self.icons = { } self._imageList= wx.ImageList(16,16,False) @@ -800,10 +741,9 @@ img = helper.load_file(path) self.icons[key] = self._imageList.Add(img) self.SetImageList(self._imageList) - self.orpgLog.log("Exit game_tree->build_img_list(self)", ORPG_DEBUG) - + + @debugging def load_xml(self, xml_dom, parent_node, prev_node=None): - self.orpgLog.log("Enter game_tree->load_xml(self, xml_dom, parent_node, prev_node)", ORPG_DEBUG) #add the first tree node i = 0 text = xml_dom.getAttribute("name") @@ -840,17 +780,14 @@ self.id = self.id + 1 except Exception, er: self.orpgLog.log(traceback.format_exc(), ORPG_GENERAL) - #self.orpgLog.log("Error Info: " + xml_dom.getAttribute("class") + "\n" + str(er), "Tree Node Load Error", ORPG_GENERAL, True) # Arbitrary fix! TaS. (gametree should thread in the future.) - self.orpgLog.log("Error Info: " + xml_dom.getAttribute("class") + "\n" + str(er), ORPG_GENERAL, True) + #self.orpgLog.log("Error Info: " + xml_dom.getAttribute("class") + "\n" + str(er), ORPG_GENERAL, True)?indent? self.Delete(new_tree_node) parent = xml_dom._get_parentNode() parent.removeChild(xml_dom) - #wx.EndBusyCursor() - self.orpgLog.log("Exit game_tree->load_xml(self, xml_dom, parent_node, prev_node)", ORPG_DEBUG) return new_tree_node - + + @debugging def cached_load_of_image(self, bmp_in, new_tree_node): - self.orpgLog.log("Enter game_tree->cached_load_of_image(self, bmp_in, new_tree_node)", ORPG_DEBUG) image_list = self.GetImageList() img = wx.ImageFromBitmap(bmp_in) img_data = img.GetData() @@ -865,12 +802,10 @@ self.image_cache[image_index] = img_data self.SetItemImage(new_tree_node,image_index) self.SetItemImage(new_tree_node,image_index, wx.TreeItemIcon_Selected) - self.orpgLog.log("Exit game_tree->cached_load_of_image(self, bmp_in, new_tree_node)", ORPG_DEBUG) return image_index - - + + @debugging def on_rclick(self, evt): - self.orpgLog.log("Enter game_tree->on_rclick(self, evt)", ORPG_DEBUG) pt = evt.GetPosition() (item, flag) = self.HitTest(pt) if item.IsOk(): @@ -882,10 +817,9 @@ self.PopupMenu(self.top_menu) else: self.PopupMenu(self.top_menu,pt) - self.orpgLog.log("Exit game_tree->on_rclick(self, evt)", ORPG_DEBUG) - + + @debugging def on_ldclick(self, evt): - self.orpgLog.log("Enter game_tree->on_ldclick(self, evt)", ORPG_DEBUG) self.rename_flag = 0 pt = evt.GetPosition() (item, flag) = self.HitTest(pt) @@ -903,10 +837,9 @@ obj.on_html_view(evt) elif action == "chat": self.on_send_to_chat(evt) - self.orpgLog.log("Exit game_tree->on_ldclick(self, evt)", ORPG_DEBUG) - + + @debugging def on_left_down(self, evt): - self.orpgLog.log("Enter game_tree->on_left_down(self, evt)", ORPG_DEBUG) pt = evt.GetPosition() (item, flag) = self.HitTest(pt) if item.IsOk() and self.was_labeling: @@ -919,10 +852,9 @@ else: self.SelectItem(item) evt.Skip() - self.orpgLog.log("Exit game_tree->on_left_down(self, evt)", ORPG_DEBUG) - + + @debugging def on_left_up(self, evt): - self.orpgLog.log("Enter game_tree->on_left_up(self, evt)", ORPG_DEBUG) if self.dragging: cur = wx.StockCursor(wx.CURSOR_ARROW) self.SetCursor(cur) @@ -935,10 +867,9 @@ if(isinstance(obj,core.node_handler)): obj.on_drop(evt) self.drag_obj = None - self.orpgLog.log("Exit game_tree->on_left_up(self, evt)", ORPG_DEBUG) - + + @debugging def on_label_change(self, evt): - self.orpgLog.log("Enter game_tree->on_label_change(self, evt)", ORPG_DEBUG) item = evt.GetItem() txt = evt.GetLabel() self.was_labeling = 0 @@ -948,10 +879,9 @@ obj.master_dom.setAttribute('name',txt) else: evt.Veto() - self.orpgLog.log("Exit game_tree->on_label_change(self, evt)", ORPG_DEBUG) - + + @debugging def on_label_begin(self, evt): - self.orpgLog.log("Enter game_tree->on_label_begin(self, evt)", ORPG_DEBUG) if not self.rename_flag: evt.Veto() else: @@ -959,10 +889,9 @@ item = evt.GetItem() if item == self.GetRootItem(): evt.Veto() - self.orpgLog.log("Exit game_tree->on_label_begin(self, evt)", ORPG_DEBUG) - + + @debugging def on_drag(self, evt): - self.orpgLog.log("Enter game_tree->on_drag(self, evt)", ORPG_DEBUG) self.rename_flag = 0 item = self.GetSelection() obj = self.GetPyData(item) @@ -972,25 +901,17 @@ cur = wx.StockCursor(wx.CURSOR_HAND) self.SetCursor(cur) self.drag_obj = obj - self.orpgLog.log("Exit game_tree->on_drag(self, evt)", ORPG_DEBUG) - + + @debugging def is_parent_node(self, node, compare_node): - self.orpgLog.log("Enter game_tree->is_parent_node(self, node, compare_node)", ORPG_DEBUG) - parent_node = self.GetItemParent(node) if compare_node == parent_node: - self.orpgLog.log("parent node", ORPG_DEBUG) - self.orpgLog.log("Exit game_tree->is_parent_node(self, node, compare_node)", ORPG_DEBUG) return 1 elif parent_node == self.root: - self.orpgLog.log("not parent", ORPG_DEBUG) - self.orpgLog.log("Exit game_tree->is_parent_node(self, node, compare_node)", ORPG_DEBUG) return 0 else: - - self.orpgLog.log("Exit game_tree->is_parent_node(self, node, compare_node)", ORPG_DEBUG) return self.is_parent_node(parent_node, compare_node) CTRL_TREE_FILE = wx.NewId() @@ -1001,7 +922,8 @@ CTRL_CHAT = wx.NewId() CTRL_PRINT = wx.NewId() -class gametree_prop_dlg(wx.Dialog): +class gametree_prop_dlg(wx.Dialog): + @debugging def __init__(self, parent, settings): wx.Dialog.__init__(self, parent, wx.ID_ANY, "Game Tree Properties") self.settings = settings @@ -1059,7 +981,8 @@ self.SetAutoLayout(True) self.Fit() self.Bind(wx.EVT_BUTTON, self.on_ok, id=wx.ID_OK) - + + @debugging def on_ok(self,evt): self.settings.set_setting("gametree",self.ctrls[CTRL_TREE_FILE].GetValue()) self.settings.set_setting("SaveGameTreeOnExit",str(self.ctrls[CTRL_YES].GetValue()))
--- a/orpg/gametree/nodehandlers/containers.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/gametree/nodehandlers/containers.py Thu Aug 20 03:00:39 2009 -0500 @@ -28,7 +28,7 @@ from core import * -import wx.lib.splitter +from wx.lib.splitter import MultiSplitterWindow ########################## @@ -295,7 +295,7 @@ self.pane = splitter_panel(parent, self) - self.splitter = wx.lib.splitter.MultiSplitterWindow(self.pane, -1, style=wx.SP_LIVE_UPDATE|wx.SP_3DSASH|wx.SP_NO_XP_THEME) + self.splitter = MultiSplitterWindow(self.pane, -1, style=wx.SP_LIVE_UPDATE|wx.SP_3DSASH|wx.SP_NO_XP_THEME) if self.split == '1': self.splitter.SetOrientation(wx.VERTICAL)
--- a/orpg/gametree/nodehandlers/core.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/gametree/nodehandlers/core.py Thu Aug 20 03:00:39 2009 -0500 @@ -32,7 +32,6 @@ try: from orpg.orpg_windows import * from orpg.dirpath import dir_struct - from orpg.orpg_xml import * from orpg.orpgCore import component import webbrowser from orpg.mapper import map @@ -41,8 +40,6 @@ import wx - - #html defaults TH_BG = "#E9E9E9" ########################## @@ -56,10 +53,10 @@ self.tree = component.get('tree') self.frame = component.get('frame') self.chat = component.get('chat') - self.xml = component.get('xml') + self.xml = component.get('xml') #Not used? self.drag = True self.myeditor = None # designing - self.myviewer = None # prett print + self.myviewer = None # pretty print self.mywindow = None # using # call version hook self.on_version(self.master_dom.getAttribute("version")) @@ -114,8 +111,7 @@ if self.create_designframe(): self.myeditor.Show() self.myeditor.Raise() - else: - return + else: return wx.CallAfter(self.myeditor.Layout) @@ -124,7 +120,7 @@ self.myeditor = wx.Frame(None, -1, title) self.myeditor.Freeze() if wx.Platform == '__WXMSW__': - icon = wx.Icon(orpg.dirpath.dir_struct["icon"] + 'grid.ico', wx.BITMAP_TYPE_ICO) + icon = wx.Icon(dir_struct["icon"] + 'grid.ico', wx.BITMAP_TYPE_ICO) self.myeditor.SetIcon(icon) del icon @@ -163,14 +159,13 @@ return wx.CallAfter(self.mywindow.Layout) - def create_useframe(self): caption = self.master_dom.getAttribute('name') self.mywindow = wx.Frame(None, -1, caption) self.mywindow.Freeze() if wx.Platform == '__WXMSW__': - icon = wx.Icon(orpg.dirpath.dir_struct["icon"] + 'note.ico', wx.BITMAP_TYPE_ICO) + icon = wx.Icon(dir_struct["icon"] + 'note.ico', wx.BITMAP_TYPE_ICO) self.mywindow.SetIcon(icon) del icon self.mywindow.panel = self.get_use_panel(self.mywindow) @@ -203,7 +198,7 @@ caption = self.master_dom.getAttribute('name') self.myviewer = wx.Frame(None, -1, caption) if wx.Platform == '__WXMSW__': - icon = wx.Icon(orpg.dirpath.dir_struct["icon"] + 'grid.ico', wx.BITMAP_TYPE_ICO) + icon = wx.Icon(dir_struct["icon"] + 'grid.ico', wx.BITMAP_TYPE_ICO) self.myviewer.SetIcon(icon) del icon self.myviewer.panel = self.get_html_panel(self.myviewer) @@ -246,7 +241,7 @@ self.tree.load_xml(xml_dom, parent_node, prev_sib) def toxml(self,pretty=0): - return toxml(self.master_dom,pretty) + return component.get('xml').toxml(self.master_dom,pretty) def tohtml(self): return self.master_dom.getAttribute("name") @@ -270,7 +265,7 @@ self.tree.Refresh() def on_save(self,evt): - f = wx.FileDialog(self.tree,"Select a file", orpg.dirpath.dir_struct["user"],"","XML files (*.xml)|*.xml",wx.SAVE) + f = wx.FileDialog(self.tree,"Select a file", dir_struct["user"],"","XML files (*.xml)|*.xml",wx.SAVE) if f.ShowModal() == wx.ID_OK: type = f.GetFilterIndex() if f.GetPath()[:len(f.GetPath())-4] != '.xml': file = open(f.GetPath()+'.xml',"w") @@ -396,7 +391,7 @@ def on_ldclick(self,evt): file_name = self.file_node.getAttribute("name") - self.tree.insert_xml(open(orpg.dirpath.dir_struct["nodes"] + file_name,"r").read()) + self.tree.insert_xml(open(dir_struct["nodes"] + file_name,"r").read()) return 1 def on_design(self,evt): @@ -460,4 +455,4 @@ def on_ldclick(self,evt): self.map.new_data(toxml(self.mapdata)) - return 1 + return 1
--- a/orpg/gametree/nodehandlers/dnd35.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/gametree/nodehandlers/dnd35.py Thu Aug 20 03:00:39 2009 -0500 @@ -1,4 +1,4 @@ -import orpg.tools.orpg_settings +import orpg.tools.orpg_settings #Settings import orpg.minidom from core import * from containers import *
--- a/orpg/gametree/nodehandlers/dnd3e.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/gametree/nodehandlers/dnd3e.py Thu Aug 20 03:00:39 2009 -0500 @@ -143,7 +143,7 @@ # r- resolved # o- open # -import orpg.tools.orpg_settings +import orpg.tools.orpg_settings #Not used?? import orpg.minidom from core import * from containers import *
--- a/orpg/gametree/nodehandlers/forms.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/gametree/nodehandlers/forms.py Thu Aug 20 03:00:39 2009 -0500 @@ -29,7 +29,7 @@ __version__ = "$Id: forms.py,v 1.53 2007/04/21 23:00:51 digitalxero Exp $" from containers import * -import wx.lib.scrolledpanel +from wx.lib.scrolledpanel import ScrolledPanel def bool2int(b): #in wxPython 2.5+, evt.Checked() returns True or False instead of 1.0 or 0. @@ -81,9 +81,9 @@ container_handler.on_drop(self,evt) -class form_panel(wx.lib.scrolledpanel.ScrolledPanel): +class form_panel(ScrolledPanel): def __init__(self, parent, handler): - wx.lib.scrolledpanel.ScrolledPanel.__init__(self, parent, wx.ID_ANY, style=wx.NO_BORDER|wx.VSCROLL|wx.HSCROLL) + ScrolledPanel.__init__(self, parent, wx.ID_ANY, style=wx.NO_BORDER|wx.VSCROLL|wx.HSCROLL) self.height = int(handler.atts.getAttribute("height")) self.width = int(handler.atts.getAttribute("width")) @@ -112,7 +112,7 @@ if x < nx: x = nx+10 y += ny+11 - wx.lib.scrolledpanel.ScrolledPanel.SetSize(self, (x, y)) + ScrolledPanel.SetSize(self, (x, y)) def create_child_wnd(self, obj, evt):
--- a/orpg/gametree/nodehandlers/map_miniature_nodehandler.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/gametree/nodehandlers/map_miniature_nodehandler.py Thu Aug 20 03:00:39 2009 -0500 @@ -33,7 +33,6 @@ from orpg.mapper.images import ImageHandler import urllib - class map_miniature_handler(node_handler): """ A node handler for miniatures
--- a/orpg/gametree/nodehandlers/minilib.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/gametree/nodehandlers/minilib.py Thu Aug 20 03:00:39 2009 -0500 @@ -35,7 +35,7 @@ from orpg.dirpath import dir_struct import string import map_miniature_nodehandler -import orpg.mapper.map_msg +import orpg.mapper.map_msg # import scriptkit # Constants @@ -218,7 +218,7 @@ label = mini.getAttribute( ATTRIBUTE_NAME ) else: label = '' - return msg.get_all_xml() + return msg().get_all_xml() def is_unique( self, mini ): unique = mini.getAttribute( ATTRIBUTE_UNIQUE )
--- a/orpg/gametree/nodehandlers/rpg_grid.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/gametree/nodehandlers/rpg_grid.py Thu Aug 20 03:00:39 2009 -0500 @@ -201,7 +201,7 @@ Show or hide the edit control. You can use the attr (if not None) to set colours or fonts for the control. """ - self.base_Show(show, attr) + self.base_Show(show, attr) #deprecated DeprecationWarning: Please use PyGridCellEditor.Show instead. def BeginEdit(self, row, col, grid):
--- a/orpg/main.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/main.py Thu Aug 20 03:00:39 2009 -0500 @@ -47,8 +47,8 @@ import orpg.gametree.gametree import orpg.chat.chatwnd +import orpg.networking.gsclient import orpg.networking.mplay_client -import orpg.networking.gsclient import orpg.mapper.map import orpg.mapper.images @@ -57,11 +57,11 @@ import upmana.manifest as manifest import wx.py -from orpg.dieroller.utils import roller_manager as DiceManager -from orpg.tools.orpg_log import logger +from orpg.dieroller.utils import DiceManager from orpg.tools.orpg_settings import settings #imported, not used yet from orpg.tools.validate import validate from orpg.tools.passtool import PassTool +from orpg.tools.orpg_log import logger from orpg.tools.decorators import debugging from orpg.tools.metamenus import MenuBarEx @@ -83,7 +83,6 @@ self.orpgLog = component.get('log') self.xml = component.get("xml") self.validate = component.get("validate") - self.settings = component.get("settings") self.orpgLog.log("Enter orpgFrame", ORPG_DEBUG) self.rgbcovert = orpg.tools.rgbhex.RGBHex() self._mgr = AUI.AuiManager(self) @@ -102,7 +101,7 @@ "on_status_event":self.on_status_event, "on_password_signal":self.on_password_signal, "orpgFrame":self} - + self.settings = component.get('settings') #Arbitrary until settings updated with Core. self.session = orpg.networking.mplay_client.mplay_client(self.settings.get_setting("player"), call_backs) self.poll_timer = wx.Timer(self, wx.NewId()) self.Bind(wx.EVT_TIMER, self.session.poll, self.poll_timer) @@ -111,7 +110,7 @@ self.Bind(wx.EVT_TIMER, self.session.update, self.ping_timer) # create roller manager - self.DiceManager = DiceManager(self.settings.get_setting("dieroller")) + self.DiceManager = DiceManager(settings.get_setting("dieroller")) component.add('DiceManager', self.DiceManager) #create password manager --SD 8/03 @@ -130,7 +129,7 @@ component.add("alias", self.aliaslib) self.orpgLog.log("openrpg components all added", ORPG_DEBUG) - self.tree.load_tree(self.settings.get_setting("gametree")) + self.tree.load_tree(settings.get_setting("gametree")) logger.debug("Tree Loaded") self.players.size_cols() @@ -237,10 +236,10 @@ ]] self.mainmenu = MenuBarEx(self, menu) - if self.settings.get_setting('Heartbeat') == '1': + if settings.get_setting('Heartbeat') == '1': self.mainmenu.SetMenuState("GameServerServerHeartbeat", True) - tabtheme = self.settings.get_setting('TabTheme') #This change is stable. TaS. + tabtheme = settings.get_setting('TabTheme') #This change is stable. TaS. self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedColorful", tabtheme == 'slanted&colorful') self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedBlackandWhite", tabtheme == 'slanted&bw') self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedAqua", tabtheme == 'slanted&aqua') @@ -249,7 +248,7 @@ self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedCustom", tabtheme == 'customslant') self.mainmenu.SetMenuState("OpenRPGTabStylesFlatCustom", tabtheme == 'customflat') - lvl = int(self.settings.get_setting('LoggingLevel')) + lvl = int(settings.get_setting('LoggingLevel')) if lvl & ORPG_DEBUG: self.mainmenu.SetMenuState("ToolsLoggingLevelDebug", True) if lvl & ORPG_DEBUG: self.mainmenu.SetMenuState("ToolsLoggingLevelNote", True) if lvl & ORPG_INFO: self.mainmenu.SetMenuState("ToolsLoggingLevelInfo", True) @@ -278,7 +277,7 @@ @debugging def SetTabStyles(self, *args, **kwargs): - tabtheme = self.settings.get_setting('TabTheme') #This change is stable. TaS. + tabtheme = settings.get_setting('TabTheme') #This change is stable. TaS. self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedColorful", tabtheme == 'slanted&colorful') self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedBlackandWhite", tabtheme == 'slanted&bw') self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedAqua", tabtheme == 'slanted&aqua') @@ -314,7 +313,7 @@ component.add("tabbedWindows", tabbedwindows) #Run though the new list and set the proper styles - tabbg = self.settings.get_setting('TabBackgroundGradient') + tabbg = settings.get_setting('TabBackgroundGradient') rgbc = orpg.tools.rgbhex.RGBHex() (red, green, blue) = rgbc.rgb_tuple(tabbg) @@ -338,14 +337,14 @@ @debugging def OnMB_OpenRPGTabStylesSlantedColorful(self): if self.mainmenu.GetMenuState("OpenRPGTabStylesSlantedColorful"): - self.settings.set_setting('TabTheme', 'slanted&colorful') + settings.set_setting('TabTheme', 'slanted&colorful') self.SetTabStyles("OpenRPGTabStylesSlantedColorful", FNB.FNB_VC8|FNB.FNB_COLORFUL_TABS) else: self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedColorful", True) @debugging def OnMB_OpenRPGTabStylesSlantedBlackandWhite(self): if self.mainmenu.GetMenuState("OpenRPGTabStylesSlantedBlackandWhite"): - self.settings.set_setting('TabTheme', 'slanted&bw') + settings.set_setting('TabTheme', 'slanted&bw') self.SetTabStyles("OpenRPGTabStylesSlantedBlackandWhite", FNB.FNB_VC8, graidentTo=wx.WHITE, graidentFrom=wx.WHITE, textColor=wx.BLACK) else: self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedBlackandWhite", True) @@ -353,7 +352,7 @@ @debugging def OnMB_OpenRPGTabStylesSlantedAqua(self): if self.mainmenu.GetMenuState("OpenRPGTabStylesSlantedAqua"): - self.settings.set_setting('TabTheme', 'slanted&aqua') + settings.set_setting('TabTheme', 'slanted&aqua') self.SetTabStyles("OpenRPGTabStylesSlantedAqua", FNB.FNB_VC8, graidentTo=wx.Color(0, 128, 255), graidentFrom=wx.WHITE, textColor=wx.BLACK) else: self.mainmenu.SetMenuState("OpenRPGTabStylesSlantedAqua", True) @@ -361,15 +360,15 @@ @debugging def OnMB_OpenRPGTabStylesSlantedCustom(self): if self.mainmenu.GetMenuState("OpenRPGTabStylesSlantedCustom"): - self.settings.set_setting('TabTheme', 'customslant') + settings.set_setting('TabTheme', 'customslant') rgbc = orpg.tools.rgbhex.RGBHex() - gfrom = self.settings.get_setting('TabGradientFrom') + gfrom = settings.get_setting('TabGradientFrom') (fred, fgreen, fblue) = rgbc.rgb_tuple(gfrom) - gto = self.settings.get_setting('TabGradientTo') + gto = settings.get_setting('TabGradientTo') (tored, togreen, toblue) = rgbc.rgb_tuple(gto) - tabtext = self.settings.get_setting('TabTextColor') + tabtext = settings.get_setting('TabTextColor') (tred, tgreen, tblue) = rgbc.rgb_tuple(tabtext) - tabbg = self.settings.get_setting('TabBackgroundGradient') + tabbg = settings.get_setting('TabBackgroundGradient') (red, green, blue) = rgbc.rgb_tuple(tabbg) self.SetTabStyles("OpenRPGTabStylesSlantedCustom", FNB.FNB_VC8, graidentTo=wx.Color(tored, togreen, toblue), graidentFrom=wx.Color(fred, fgreen, fblue), @@ -379,7 +378,7 @@ @debugging def OnMB_OpenRPGTabStylesFlatBlackandWhite(self): if self.mainmenu.GetMenuState("OpenRPGTabStylesFlatBlackandWhite"): - self.settings.set_setting('TabTheme', 'flat&bw') + settings.set_setting('TabTheme', 'flat&bw') self.SetTabStyles("OpenRPGTabStylesFlatBlackandWhite", FNB.FNB_FANCY_TABS, graidentTo=wx.WHITE, graidentFrom=wx.WHITE, textColor=wx.BLACK) else: self.mainmenu.SetMenuState("OpenRPGTabStylesFlatBlackandWhite", True) @@ -387,7 +386,7 @@ @debugging def OnMB_OpenRPGTabStylesFlatAqua(self): if self.mainmenu.GetMenuState("OpenRPGTabStylesFlatAqua"): - self.settings.set_setting('TabTheme', 'flat&aqua') + settings.set_setting('TabTheme', 'flat&aqua') self.SetTabStyles("OpenRPGTabStylesFlatAqua", FNB.FNB_FANCY_TABS, graidentTo=wx.Color(0, 128, 255), graidentFrom=wx.WHITE, textColor=wx.BLACK) else: self.mainmenu.SetMenuState("OpenRPGTabStylesFlatAqua", True) @@ -395,15 +394,15 @@ @debugging def OnMB_OpenRPGTabStylesFlatCustom(self): if self.mainmenu.GetMenuState("OpenRPGTabStylesFlatCustom"): - self.settings.set_setting('TabTheme', 'customflat') + settings.set_setting('TabTheme', 'customflat') rgbc = orpg.tools.rgbhex.RGBHex() - gfrom = self.settings.get_setting('TabGradientFrom') + gfrom = settings.get_setting('TabGradientFrom') (fred, fgreen, fblue) = rgbc.rgb_tuple(gfrom) - gto = self.settings.get_setting('TabGradientTo') + gto = settings.get_setting('TabGradientTo') (tored, togreen, toblue) = rgbc.rgb_tuple(gto) - tabtext = self.settings.get_setting('TabTextColor') + tabtext = settings.get_setting('TabTextColor') (tred, tgreen, tblue) = rgbc.rgb_tuple(tabtext) - tabbg = self.settings.get_setting('TabBackgroundGradient') + tabbg = settings.get_setting('TabBackgroundGradient') (red, green, blue) = rgbc.rgb_tuple(tabbg) self.SetTabStyles("OpenRPGTabStylesFlatCustom", FNB.FNB_FANCY_TABS, graidentTo=wx.Color(tored, togreen, toblue), graidentFrom=wx.Color(fred, fgreen, fblue), @@ -442,8 +441,8 @@ @debugging def OnMB_GameServerServerHeartbeat(self): - if self.mainmenu.GetMenuState("GameServerServerHeartbeat"): self.settings.set_setting('Heartbeat', '1') - else: self.settings.set_setting('Heartbeat', '0') + if self.mainmenu.GetMenuState("GameServerServerHeartbeat"): settings.set_setting('Heartbeat', '1') + else: settings.set_setting('Heartbeat', '0') @debugging def OnMB_GameServerStartServer(self): @@ -796,9 +795,9 @@ elif name == "tree": temp_wnd = orpg.gametree.gametree.game_tree(parent_wnd, -1) self.tree = temp_wnd - if self.settings.get_setting('ColorTree') == '1': - self.tree.SetBackgroundColour(self.settings.get_setting('bgcolor')) - self.tree.SetForegroundColour(self.settings.get_setting('textcolor')) + if settings.get_setting('ColorTree') == '1': + self.tree.SetBackgroundColour(settings.get_setting('bgcolor')) + self.tree.SetForegroundColour(settings.get_setting('textcolor')) else: self.tree.SetBackgroundColour('white') self.tree.SetForegroundColour('black') @@ -811,9 +810,9 @@ elif name == "player": temp_wnd = orpg.player_list.player_list(parent_wnd) self.players = temp_wnd - if self.settings.get_setting('ColorTree') == '1': - self.players.SetBackgroundColour(self.settings.get_setting('bgcolor')) - self.players.SetForegroundColour(self.settings.get_setting('textcolor')) + if settings.get_setting('ColorTree') == '1': + self.players.SetBackgroundColour(settings.get_setting('bgcolor')) + self.players.SetForegroundColour(settings.get_setting('textcolor')) else: self.players.SetBackgroundColour('white') self.players.SetForegroundColour('black') @@ -1100,7 +1099,7 @@ traceback.print_exc() #end mDuo13 added code self.saveLayout() - try: self.settings.save() + try: settings.save() except Exception: logger.general("[WARNING] Error saving 'settings' component", True) @@ -1109,9 +1108,9 @@ logger.general("[WARNING] Map error pre_exit_cleanup()", True) try: - save_tree = string.upper(self.settings.get_setting("SaveGameTreeOnExit")) + save_tree = string.upper(settings.get_setting("SaveGameTreeOnExit")) if (save_tree != "0") and (save_tree != "False") and (save_tree != "NO"): - self.tree.save_tree(self.settings.get_setting("gametree")) + self.tree.save_tree(settings.get_setting("gametree")) except Exception: logger.general("[WARNING] Error saving gametree", True) @@ -1177,7 +1176,7 @@ component.add('log', logger) component.add('xml', xml) - #component.add('settings', settings) + component.add('settings', settings) component.add('validate', validate) component.add("tabbedWindows", []) @@ -1185,8 +1184,7 @@ self.orpgLog = component.get('log') self.validate = component.get('validate') - self.settings = component.get('settings') - logger.log_level = int(self.settings.get_setting('LoggingLevel')) + logger.log_level = int(settings.get_setting('LoggingLevel')) self.called = False wx.InitAllImageHandlers() self.splash = orpgSplashScreen(None, dir_struct["icon"] + 'splash13.jpg', 3000, self.AfterSplash)
--- a/orpg/mapper/base.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/mapper/base.py Thu Aug 20 03:00:39 2009 -0500 @@ -30,7 +30,6 @@ from images import ImageHandler from orpg.tools.rgbhex import * from orpg.orpg_windows import * -from orpg.orpg_xml import * from math import * from threading import Lock import time
--- a/orpg/mapper/base_handler.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/mapper/base_handler.py Thu Aug 20 03:00:39 2009 -0500 @@ -51,15 +51,15 @@ self.buttonsizer = wx.BoxSizer(wx.HORIZONTAL) self.zoom_in_button = createMaskedButton( self, - orpg.dirpath.dir_struct["icon"]+'zoom_in.gif', "Zoom in from x1.0", wx.ID_ANY ) + dir_struct["icon"]+'zoom_in.gif', "Zoom in from x1.0", wx.ID_ANY ) self.zoom_out_button = createMaskedButton( self, - orpg.dirpath.dir_struct["icon"]+'zoom_out.gif', "Zoom out from x1.0", wx.ID_ANY ) + dir_struct["icon"]+'zoom_out.gif', "Zoom out from x1.0", wx.ID_ANY ) props = createMaskedButton( self, - orpg.dirpath.dir_struct["icon"]+'compass.gif', 'Edit map properties', wx.ID_ANY ) + dir_struct["icon"]+'compass.gif', 'Edit map properties', wx.ID_ANY ) mapopen = createMaskedButton( self, - orpg.dirpath.dir_struct["icon"]+'open.bmp', 'Load a map', wx.ID_ANY, '#c0c0c0', wx.BITMAP_TYPE_BMP ) + dir_struct["icon"]+'open.bmp', 'Load a map', wx.ID_ANY, '#c0c0c0', wx.BITMAP_TYPE_BMP ) mapsave = createMaskedButton( self, - orpg.dirpath.dir_struct["icon"]+'save.bmp', 'Save the map', wx.ID_ANY, '#c0c0c0', wx.BITMAP_TYPE_BMP ) + dir_struct["icon"]+'save.bmp', 'Save the map', wx.ID_ANY, '#c0c0c0', wx.BITMAP_TYPE_BMP ) self.buttonsizer.Add(self.zoom_in_button, 0, wx.ALIGN_CENTER ) self.buttonsizer.Add(self.zoom_out_button, 0, wx.ALIGN_CENTER ) self.buttonsizer.Add(props, 0, wx.ALIGN_CENTER ) @@ -98,7 +98,7 @@ self.main_menu = main_menu def on_save_map_jpg(self, evt): - directory = orpg.dirpath.dir_struct["user"] + directory = dir_struct["user"] if directory == None: directory = "" d = wx.FileDialog(self.GetParent(), "Save map as a jpg", directory, "", "*.jpg", wx.SAVE)
--- a/orpg/mapper/fog.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/mapper/fog.py Thu Aug 20 03:00:39 2009 -0500 @@ -33,33 +33,25 @@ class FogArea: def __init__(self, outline, log): - self.log = log - self.log.log("Enter FogArea", ORPG_DEBUG) self.outline = outline - self.log.log("Exit FogArea", ORPG_DEBUG) def set_fog_props(self, str): - self.log.log("Enter FogArea->set_fog_props(self, str)", ORPG_DEBUG) self.outline = str - self.log.log("Exit FogArea->set_fog_props(self, str)", ORPG_DEBUG) def points_to_elements(self, points=None): - self.log.log("Enter FogArea->points_to_elements(self, points)", ORPG_DEBUG) result = [] if points == None: - self.log.log("Exit FogArea->points_to_elements(self, points)", ORPG_DEBUG) return result + for pairs in string.split( points, ';' ): pair = string.split( pairs, ',' ) p = Element( "point" ) p.setAttribute( "x", pair[0] ) p.setAttribute( "y", pair[1] ) result.append( p ) - self.log.log("Exit FogArea->points_to_elements(self, points)", ORPG_DEBUG) return result def toxml(self, action="update"): - self.log.log("Enter FogArea->toxml(self, " + action + ")", ORPG_DEBUG) xml_str = "" localOutline = self.outline if localOutline != None and localOutline != "all" and localOutline != "none": @@ -73,8 +65,6 @@ for p in list: elem.appendChild( p ) str = elem.toxml() elem.unlink() - self.log.log(str, ORPG_DEBUG) - self.log.log("Exit FogArea->toxml(self, " + action + ")", ORPG_DEBUG) return str elem.setAttribute( "action", action ) if localOutline != None: @@ -84,15 +74,11 @@ for p in list: elem.appendChild( p ) xml_str = elem.toxml() elem.unlink() - self.log.log(xml_str, ORPG_DEBUG) - self.log.log("Exit FogArea->toxml(self, " + action + ")", ORPG_DEBUG) return xml_str class fog_layer(layer_base): def __init__(self, canvas): self.canvas = canvas - self.log = self.canvas.log - self.log.log("Enter fog_layer", ORPG_DEBUG) layer_base.__init__(self) self.color = wx.Color(128,128,128) if "__WXGTK__" not in wx.PlatformInfo: self.color = wx.Color(128,128,128, 128) @@ -103,51 +89,38 @@ self.height = 0 self.use_fog = False self.last_role = "" - self.log.log("Exit fog_layer", ORPG_DEBUG) def clear(self): - self.log.log("Enter fog_layer->clear(self)", ORPG_DEBUG) self.fogregion.Clear() self.use_fog = True self.del_area("all") self.recompute_fog() - self.log.log("Exit fog_layer->clear(self)", ORPG_DEBUG) def remove_fog(self): - self.log.log("Enter fog_layer->remove_fog(self)", ORPG_DEBUG) self.fogregion.Clear() self.use_fog = False self.del_area("all") self.add_area("none") self.fog_bmp = None - self.log.log("Exit fog_layer->remove_fog(self)", ORPG_DEBUG) def resize(self, size): - self.log.log("Enter fog_layer->resize(self, size)", ORPG_DEBUG) try: if self.width == size[0] and self.height == size[1]: - self.log.log("Exit fog_layer->resize(self, size)", ORPG_DEBUG) return self.recompute_fog() except: pass - self.log.log("Exit fog_layer->resize(self, size)", ORPG_DEBUG) def recompute_fog(self): - self.log.log("Enter fog_layer->recompute_fog(self)", ORPG_DEBUG) if not self.use_fog: - self.log.log("Exit fog_layer->recompute_fog(self)", ORPG_DEBUG) return size = self.canvas.size self.width = size[0]/COURSE+1 self.height = size[1]/COURSE+1 self.fog_bmp = wx.EmptyBitmap(self.width+2,self.height+2) self.fill_fog() - self.log.log("Exit fog_layer->recompute_fog(self)", ORPG_DEBUG) def fill_fog(self): - self.log.log("Enter fog_layer->fill_fog(self)", ORPG_DEBUG) if not self.use_fog: - self.log.log("Exit fog_layer->fill_fog(self)", ORPG_DEBUG) return if "__WXGTK__" in wx.PlatformInfo: mdc = wx.MemoryDC() @@ -165,12 +138,9 @@ mdc.DrawRectangle(0, 0, self.width+2, self.height+2) mdc.SelectObject(wx.NullBitmap) del mdc - self.log.log("Exit fog_layer->fill_fog(self)", ORPG_DEBUG) def layerDraw(self, dc, topleft, size): - self.log.log("Enter fog_layer->layerDraw(self, dc, topleft, size)", ORPG_DEBUG) if self.fog_bmp == None or not self.fog_bmp.Ok() or not self.use_fog: - self.log.log("Exit fog_layer->layerDraw(self, dc, topleft, size)", ORPG_DEBUG) return if self.last_role != self.canvas.frame.session.role: self.fill_fog() if "__WXGTK__" not in wx.PlatformInfo: @@ -209,10 +179,8 @@ dc.SetUserScale(sc[0],sc[1]) mdc.SelectObject(wx.NullBitmap) del mdc - self.log.log("Exit fog_layer->layerDraw(self, dc, topleft, size)", ORPG_DEBUG) def createregn2(self, polyline, mode, show): - self.log.log("Enter fog_layer->createregn2(self, polyline, mode, show)", ORPG_DEBUG) regn = self.scanConvert(polyline) area = "" for i in polyline: @@ -231,59 +199,46 @@ self.fogregion = wx.Region(0, 0, self.canvas.size[0]+2, self.canvas.size[1]+2) self.fogregion.SubtractRegion(regn) self.del_area(area, show) - self.log.log("Exit fog_layer->createregn2(self, polyline, mode, show)", ORPG_DEBUG) def createregn(self, polyline, mode, show="Yes"): - self.log.log("Enter fog_layer->createregn(self, polyline, mode, show)", ORPG_DEBUG) if not self.use_fog and mode == 'del': self.clear() self.canvas.Refresh(False) if self.use_fog: self.createregn2(polyline, mode, show) self.fill_fog() - self.log.log("Exit fog_layer->createregn(self, polyline, mode, show)", ORPG_DEBUG) def scanConvert(self, polypt): - self.log.log("Enter fog_layer->scanConvert(self, polypt)", ORPG_DEBUG) regn = wx.Region() regn.Clear() list = IRegion().scan_Convert(polypt) for i in list: if regn.IsEmpty(): - if "__WXGTK__" not in wx.PlatformInfo: - regn = wx.Region(i.left*COURSE, i.y*COURSE, i.right*COURSE+1-i.left*COURSE, 1*COURSE) + if "__WXGTK__" not in wx.PlatformInfo: regn = wx.Region(i.left*COURSE, i.y*COURSE, + i.right*COURSE+1-i.left*COURSE, 1*COURSE) else: regn = wx.Region(i.left, i.y, i.right+1-i.left, 1) else: - if "__WXGTK__" not in wx.PlatformInfo: - regn.Union(i.left*COURSE, i.y*COURSE, i.right*COURSE+1-i.left*COURSE, 1*COURSE) + if "__WXGTK__" not in wx.PlatformInfo: regn.Union(i.left*COURSE, i.y*COURSE, + i.right*COURSE+1-i.left*COURSE, 1*COURSE) else: regn.Union(i.left, i.y, i.right+1-i.left, 1) - self.log.log("Exit fog_layer->scanConvert(self, polypt)", ORPG_DEBUG) return regn def add_area(self, area="", show="Yes"): - self.log.log("Enter fog_layer->add_area(self, area, show)", ORPG_DEBUG) poly = FogArea(area, self.log) xml_str = "<map><fog>" xml_str += poly.toxml("new") xml_str += "</fog></map>" if show == "Yes": self.canvas.frame.session.send(xml_str) - self.log.log(xml_str, ORPG_DEBUG) - self.log.log("Exit fog_layer->add_area(self, area, show)", ORPG_DEBUG) def del_area(self, area="", show="Yes"): - self.log.log("Enter fog_layer->del_area(self, area, show)", ORPG_DEBUG) poly = FogArea(area, self.log) xml_str = "<map><fog>" xml_str += poly.toxml("del") xml_str += "</fog></map>" if show == "Yes": self.canvas.frame.session.send(xml_str) - self.log.log(xml_str, ORPG_DEBUG) - self.log.log("Exit fog_layer->del_area(self, area, show)", ORPG_DEBUG) def layerToXML(self, action="update"): - self.log.log("Enter fog_layer->layerToXML(self, " + action + ")", ORPG_DEBUG) if not self.use_fog: - self.log.log("Exit fog_layer->layerToXML(self, " + action + ") return None", ORPG_DEBUG) return "" fog_string = "" ri = wx.RegionIterator(self.fogregion) @@ -310,15 +265,11 @@ s += ">" s += fog_string s += "</fog>" - self.log.log(s, ORPG_DEBUG) - self.log.log("Exit fog_layer->layerToXML(self, " + action + ")", ORPG_DEBUG) return s else: - self.log.log("Exit fog_layer->layerToXML(self, " + action + ") return None", ORPG_DEBUG) return "" def layerTakeDOM(self, xml_dom): - self.log.log("Enter fog_layer->layerTakeDOM(self, xml_dom)", ORPG_DEBUG) try: if not self.use_fog: self.use_fog = True @@ -350,5 +301,4 @@ lasty = y if (len(polyline) > 1): self.createregn2(polyline, action, "No") self.fill_fog() - except: self.log.log(traceback.format_exc(), ORPG_GENERAL) - self.log.log("Exit fog_layer->layerTakeDOM(self, xml_dom)", ORPG_DEBUG) + except: pass
--- a/orpg/mapper/fog_msg.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/mapper/fog_msg.py Thu Aug 20 03:00:39 2009 -0500 @@ -71,10 +71,6 @@ return self.toxml(action,output_action) def toxml(self,action,output_action): - #print "fog_msg.toxml called" - #print "use_fog :",self.use_fog - #print "output_action :",output_action - #print "action :",action if not (self.use_fog): return "" fog_string = "" if self.fogregion.isEmpty(): fog_string=self.get_line("all","del",output_action) @@ -116,11 +112,11 @@ list = l._get_childNodes() for node in list: polyline.append( IPoint().make( int(node.getAttribute("x")), int(node.getAttribute("y")) ) ) - # pointarray = outline.split(";") - # for m in range(len(pointarray)): - # pt=pointarray[m].split(",") - # polyline.append(IPoint().make(int(pt[0]),int(pt[1]))) - #print "length of polyline", len(polyline) + # pointarray = outline.split(";") + # for m in range(len(pointarray)): + # pt=pointarray[m].split(",") + # polyline.append(IPoint().make(int(pt[0]),int(pt[1]))) + #print "length of polyline", len(polyline) if (len(polyline)>2): if action=="del": self.fogregion.FromPolygon(polyline,0) else: self.fogregion.FromPolygon(polyline,1)
--- a/orpg/mapper/grid.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/mapper/grid.py Thu Aug 20 03:00:39 2009 -0500 @@ -107,7 +107,7 @@ else: x = topLeft.x y = topLeft.y - return cmpPoint(int(x),int(y)) # Set the pos attribute + return cmpPoint(int(x),int(y)) # Set the pos attribute else: return cmpPoint(int(pos.x),int(pos.y)) def set_rect_mode(self): @@ -209,7 +209,6 @@ # and therefore (per transformation above) is at iso co-ord (iso_unit_size, 0) # the bottom corner of the first diamond is grid co-ord (width/2, height) # and therefore (per transformation above) is at iso co-ord (0, iso_unit_size) - # the calculation is now as simple as the rectangle case, but using iso co-ords return cmpPoint(floor(iso_x/iso_unit_size), floor(iso_y/iso_unit_size)) else: return None
--- a/orpg/mapper/grid_msg.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/mapper/grid_msg.py Thu Aug 20 03:00:39 2009 -0500 @@ -27,7 +27,8 @@ # __version__ = "$Id: grid_msg.py,v 1.8 2006/11/04 21:24:21 digitalxero Exp $" -from base_msg import * +from base_msg import map_element_msg_base +#from base_msg import * ## ?? import all? Deprecated!? class grid_msg(map_element_msg_base):
--- a/orpg/mapper/images.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/mapper/images.py Thu Aug 20 03:00:39 2009 -0500 @@ -33,8 +33,9 @@ from threading import Lock import time from orpg.orpg_wx import * -from orpg.orpgCore import * +from orpg.orpgCore import component from orpg.dirpath import dir_struct +from orpg.tools.orpg_log import logger def singleton(cls): instances = {} @@ -51,40 +52,38 @@ __lock = Lock() def load(self, path, image_type, imageId): - # Load an image, with a intermideary fetching image shown while it loads in a background thread + """Load an image, with a intermideary fetching image shown while it loads in a background thread""" if self.__cache.has_key(path): return wx.ImageFromMime(self.__cache[path][1], self.__cache[path][2]).ConvertToBitmap() if not self.__fetching.has_key(path): self.__fetching[path] = True - #Start Image Loading Thread + """Start Image Loading Thread""" thread.start_new_thread(self.__loadThread, (path, image_type, imageId)) else: if self.__fetching[path] is True: thread.start_new_thread(self.__loadCacheThread, (path, image_type, imageId)) return wx.Bitmap(dir_struct["icon"] + "fetching.png", wx.BITMAP_TYPE_PNG) def directLoad(self, path): - # Directly load an image, no threads + """Directly load an image, no threads""" if self.__cache.has_key(path): return wx.ImageFromMime(self.__cache[path][1], self.__cache[path][2]).ConvertToBitmap() uriPath = urllib.unquote(path) try: d = urllib.urlretrieve(uriPath) - # We have to make sure that not only did we fetch something, but that - # it was an image that we got back. + """We have to make sure that not only did we fetch something, but that + it was an image that we got back.""" if d[0] and d[1].getmaintype() == "image": self.__cache[path] = (path, d[0], d[1].gettype(), None) return wx.ImageFromMime(self.__cache[path][1], self.__cache[path][2]).ConvertToBitmap() else: - component.get('log').log("Image refused to load or URI did not reference a valid image: " + path, - ORPG_GENERAL, True) + logger.general("Image refused to load or URI did not reference a valid image: " + path) ##logger.general return None except IOError: - component.get('log').log("Unable to resolve/open the specified URI; image was NOT loaded: " + path, - ORPG_GENERAL, True) + logger.general("Unable to resolve/open the specified URI; image was NOT loaded: " + path) ##logger.general return None def cleanCache(self): - # Shrinks the Cache down to the proper size + """Shrinks the Cache down to the proper size""" try: cacheSize = int(component.get('settings').get_setting("ImageCacheSize")) except: cacheSize = 32 cache = self.__cache.keys() @@ -92,7 +91,7 @@ for key in cache[cacheSize:]: del self.__cache[key] def flushCache(self): - # This function will flush all images contained within the image cache. + """This function will flush all images contained within the image cache.""" self.__lock.acquire() try: keyList = self.__cache.keys() @@ -100,26 +99,24 @@ finally: self.__lock.release() urllib.urlcleanup() - #Private Methods + """Private Methods""" def __loadThread(self, path, image_type, imageId): uriPath = urllib.unquote(path) self.__lock.acquire() try: d = urllib.urlretrieve(uriPath) - # We have to make sure that not only did we fetch something, but that - # it was an image that we got back. + """We have to make sure that not only did we fetch something, but that + it was an image that we got back.""" if d[0] and d[1].getmaintype() == "image": self.__cache[path] = (path, d[0], d[1].gettype(), imageId) self.__queue.put((self.__cache[path], image_type, imageId)) - if self.__fetching.has_key(path): del self.__fetching[path] + if self.__fetching.has_key(path): self.__fetching[path] = False #Fix for failed multi-load? else: - component.get('log').log("Image refused to load or URI did not reference a valid image: " + path, - ORPG_GENERAL, True) + logger.general("Image refused to load or URI did not reference a valid image: " + path) ##logger.general del self.__fetching[path] except IOError: del self.__fetching[path] - component.get('log').log("Unable to resolve/open the specified URI; image was NOT laoded: " + path, - ORPG_GENERAL, True) + logger.general("Unable to resolve/open the specified URI; image was NOT laoded: " + path) ##logger.general finally: self.__lock.release() def __loadCacheThread(self, path, image_type, imageId): @@ -129,26 +126,26 @@ while self.__fetching.has_key(path) and self.__fetching[path] is not False: time.sleep(0.025) if (time.time()-st) > 120: - component.get('log').log("Timeout: " + path, ORPG_GENERAL, True) + logger.general("Timeout: " + path) break except: del self.__fetching[path] - component.get('log').log("Unable to resolve/open the specified URI; image was NOT loaded: " + path, ORPG_GENERAL, True) + logger.general("Unable to resolve/open the specified URI; image was NOT loaded: " + path) ##logger.general return self.__lock.acquire() try: - component.get('log').log("Adding Image to Queue from Cache: " + str(self.__cache[path]), ORPG_DEBUG) + logger.debug("Adding Image to Queue from Cache: " + str(self.__cache[path])) self.__queue.put((self.__cache[path], image_type, imageId)) finally: self.__lock.release() - #Property Methods + """Property Methods""" def _getCache(self): return self.__cache def _getQueue(self): return self.__queue - #Properties + """Properties""" Cache = property(_getCache) Queue = property(_getQueue)
--- a/orpg/mapper/map.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/mapper/map.py Thu Aug 20 03:00:39 2009 -0500 @@ -31,19 +31,22 @@ from map_msg import * from min_dialogs import * from map_prop_dialog import * -from orpg.dirpath import dir_struct + import random import os import thread import gc import traceback + from miniatures_handler import * from whiteboard_handler import * from background_handler import * -from fog_handler import * -from images import ImageHandler from grid_handler import * from map_handler import * +from fog_handler import * + +from orpg.dirpath import dir_struct +from images import ImageHandler from orpg.orpgCore import component # Various marker modes for player tools on the map @@ -55,8 +58,7 @@ class MapCanvas(wx.ScrolledWindow): def __init__(self, parent, ID, isEditor=0): self.parent = parent - self.log = component.get("log") - self.log.log("Enter MapCanvas", ORPG_DEBUG) + self.log = component.get('log') self.settings = component.get("settings") self.session = component.get("session") wx.ScrolledWindow.__init__(self, parent, ID, @@ -106,20 +108,14 @@ self.inside = 0 # miniatures drag self.drag = None - self.log.log("Exit MapCanvas", ORPG_DEBUG) def better_refresh(self, event=None): - self.log.log("Enter MapCanvas->better_refresh(self)", ORPG_DEBUG) self.Refresh(True) - self.log.log("Eexit MapCanvas->better_refresh(self)", ORPG_DEBUG) def pre_destory_cleanup(self): - self.log.log("Enter MapCanvas->pre_destory_cleanup(self)", ORPG_DEBUG) self.layers["miniatures"].del_all_miniatures() - self.log.log("Exit MapCanvas->pre_destory_cleanup(self)", ORPG_DEBUG) def processImages(self, evt=None): - self.log.log("Enter MapCanvas->processImages(self)", ORPG_DEBUG) self.session = component.get("session") if self.session.my_role() == self.session.ROLE_LURKER or (str(self.session.group_id) == '0' and str(self.session.status) == '1'): cidx = self.parent.get_tab_index("Background") @@ -162,9 +158,7 @@ self.cacheSizeSet = True cacheSize = self.settings.get_setting("ImageCacheSize") if len(cacheSize): self.cacheSize = int(cacheSize) - else: self.log.log("Default cache size being used.", ORPG_GENERAL) - self.log.log("Current image cache size is set at " + str(self.cacheSize) + " images, using random purge.", - ORPG_GENERAL) + else: pass if not ImageHandler.Queue.empty(): (path, image_type, imageId) = ImageHandler.Queue.get() img = wx.ImageFromMime(path[1], path[2]).ConvertToBitmap() @@ -180,15 +174,15 @@ # Flag that we now need to refresh! self.requireRefresh += 1 - # Randomly purge an item from the cache, while this is lamo, it does - # keep the cache from growing without bounds, which is pretty important! + """ Randomly purge an item from the cache, while this is lamo, it does + keep the cache from growing without bounds, which is pretty important!""" if len(ImageHandler.Cache) >= self.cacheSize: ImageHandler.cleanCache() else: - # Now, make sure not only that we require a refresh, but that enough time has - # gone by since our last refresh. This keeps back to back refreshing occuring during - # large map loads. Of course, we are now trying to pack as many image refreshes as - # we can into a single cycle. + """ Now, make sure not only that we require a refresh, but that enough time has + gone by since our last refresh. This keeps back to back refreshing occuring during + large map loads. Of course, we are now trying to pack as many image refreshes as + we can into a single cycle.""" if self.requireRefresh and (self.requireRefresh == self.lastRefreshValue): if (self.lastRefreshTime) < time.time(): self.requireRefresh = 0 @@ -196,86 +190,64 @@ self.lastRefreshTime = time.time() self.Refresh(True) else: self.lastRefreshValue = self.requireRefresh - self.log.log("Exit MapCanvas->processImages(self)", ORPG_DEBUG) def on_scroll(self, evt): - self.log.log("Enter MapCanvas->on_scroll(self, evt)", ORPG_DEBUG) if self.drag: self.drag.Hide() if self.settings.get_setting("AlwaysShowMapScale") == "1": self.printscale() evt.Skip() - self.log.log("Exit MapCanvas->on_scroll(self, evt)", ORPG_DEBUG) def on_char(self, evt): - self.log.log("Enter MapCanvas->on_char(self, evt)", ORPG_DEBUG) if self.settings.get_setting("AlwaysShowMapScale") == "1": self.printscale() evt.Skip() - self.log.log("Exit MapCanvas->on_char(self, evt)", ORPG_DEBUG) def printscale(self): - self.log.log("Enter MapCanvas->printscale(self)", ORPG_DEBUG) wx.BeginBusyCursor() dc = wx.ClientDC(self) self.PrepareDC(dc) self.showmapscale(dc) self.Refresh(True) wx.EndBusyCursor() - self.log.log("Exit MapCanvas->printscale(self)", ORPG_DEBUG) def send_map_data(self, action="update"): - self.log.log("Enter MapCanvas->send_map_data(self, " + action +")", ORPG_DEBUG) wx.BeginBusyCursor() send_text = self.toxml(action) if send_text: if not self.isEditor: self.frame.session.send(send_text) wx.EndBusyCursor() - self.log.log("Exit MapCanvas->send_map_data(self, " + action +")", ORPG_DEBUG) def get_size(self): - self.log.log("Enter MapCanvas->get_size(self)", ORPG_DEBUG) - self.log.log("Exit MapCanvas->get_size(self) return " + str(self.size), ORPG_DEBUG) return self.size def set_size(self, size): - self.log.log("Enter MapCanvas->set_size(self, size)", ORPG_DEBUG) if size[0] < 300: size = (300, size[1]) if size[1] < 300: size = (size[0], 300) self.size_changed = 1 self.size = size self.fix_scroll() self.layers['fog'].resize(size) - self.log.log("Exit MapCanvas->set_size(self, size)", ORPG_DEBUG) def fix_scroll(self): - self.log.log("Enter MapCanvas->fix_scroll(self)", ORPG_DEBUG) scale = self.layers['grid'].mapscale pos = self.GetViewStart() unit = self.GetScrollPixelsPerUnit() pos = [pos[0]*unit[0],pos[1]*unit[1]] size = self.GetClientSize() unit = [10*scale,10*scale] - if (unit[0] == 0 or unit[1] == 0): - self.log.log("Exit MapCanvas->fix_scroll(self)", ORPG_DEBUG) - return + if (unit[0] == 0 or unit[1] == 0): return pos[0] /= unit[0] pos[1] /= unit[1] mx = [int(self.size[0]*scale/unit[0])+1, int(self.size[1]*scale/unit[1]+1)] self.SetScrollbars(unit[0], unit[1], mx[0], mx[1], pos[0], pos[1]) - self.log.log("Exit MapCanvas->fix_scroll(self)", ORPG_DEBUG) def on_resize(self, evt): - self.log.log("Enter MapCanvas->on_resize(self, evt)", ORPG_DEBUG) self.fix_scroll() wx.CallAfter(self.Refresh, True) evt.Skip() - self.log.log("Exit MapCanvas->on_resize(self, evt)", ORPG_DEBUG) def on_erase_background(self, evt): - self.log.log("Enter MapCanvas->on_erase_background(self, evt)", ORPG_DEBUG) evt.Skip() - self.log.log("Exit MapCanvas->on_erase_background(self, evt)", ORPG_DEBUG) def on_paint(self, evt): - self.log.log("Enter MapCanvas->on_paint(self, evt)", ORPG_DEBUG) scale = self.layers['grid'].mapscale scrollsize = self.GetScrollPixelsPerUnit() clientsize = self.GetClientSize() @@ -307,17 +279,13 @@ self.showmapscale(wdc) try: evt.Skip() except: pass - self.log.log("Exit MapCanvas->on_paint(self, evt)", ORPG_DEBUG) def preppaint(self): - self.log.log("Enter MapCanvas->preppaint(self)", ORPG_DEBUG) dc = wx.PaintDC(self) self.PrepareDC(dc) - self.log.log("Exit MapCanvas->preppaint(self)", ORPG_DEBUG) return (dc) def showmapscale(self, dc): - self.log.log("Enter MapCanvas->showmapscale(self, dc)", ORPG_DEBUG) scalestring = "Scale x" + `self.layers['grid'].mapscale`[:3] (textWidth, textHeight) = dc.GetTextExtent(scalestring) dc.SetUserScale(1, 1) @@ -330,13 +298,11 @@ dc.DrawText(scalestring, x+1, y+1) dc.SetPen(wx.NullPen) dc.SetBrush(wx.NullBrush) - self.log.log("Exit MapCanvas->showmapscale(self, dc)", ORPG_DEBUG) def snapMarker(self, snapPoint): """Based on the position and unit size, figure out where we need to snap to. As is, on a square grid, there are four possible places to snap. On a hex gid, there are 6 or 12 snap points.""" - self.log.log("Enter MapCanvas->snapMarker(self, snapPoint)", ORPG_DEBUG) # If snap to grid is disabled, simply return snapPoint unmodified if self.layers['grid'].snap: @@ -362,48 +328,38 @@ else: quadYPos = offsetY + size # Create our snap snapPoint and return it snapPoint = wx.Point( quadXPos, quadYPos ) - self.log.log("Exit MapCanvas->snapMarker(self, snapPoint)", ORPG_DEBUG) return snapPoint # Bunch of math stuff for marking and measuring def calcSlope(self, start, stop): """Calculates the slop of a line and returns it.""" - self.log.log("Enter MapCanvas->calcSlope(self, start, stop)", ORPG_DEBUG) if start.x == stop.x: s = 0.0001 else: s = float((stop.y - start.y)) / float((stop.x - start.x)) - self.log.log("Exit MapCanvas->calcSlope(self, start, stop)", ORPG_DEBUG) return s def calcSlopeToAngle(self, slope): """Based on the input slope, the angle (in degrees) will be returned.""" - self.log.log("Enter MapCanvas->calcSlopeToAngle(self, slope)", ORPG_DEBUG) # See if the slope is neg or positive if slope == abs(slope): # Slope is positive, so make sure it's not zero if slope == 0: a = 0 else: a = 360 - atan(slope) * (180.0/pi) else: a = atan(abs(slope)) * (180.0/pi) - self.log.log("Exit MapCanvas->calcSlopeToAngle(self, slope)", ORPG_DEBUG) return a def calcLineAngle(self, start, stop): """Based on two points that are on a line, return the angle of that line.""" - self.log.log("Enter MapCanvas->calcLineAngle(self, start, stop)", ORPG_DEBUG) a = self.calcSlopeToAngle( self.calcSlope( start, stop ) ) - self.log.log("Exit MapCanvas->calcLineAngle(self, start, stop)", ORPG_DEBUG) return a def calcPixelDistance(self, start, stop): """Calculate the distance between two pixels and returns it. The calculated distance is the Euclidean Distance, which is: d = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )""" - self.log.log("Enter MapCanvas->calcPixelDistance(self, start, stop)", ORPG_DEBUG) d = sqrt( abs((stop.x - start.x)**2 - (stop.y - start.y)**2) ) - self.log.log("Exit MapCanvas->calcPixelDistance(self, start, stop)", ORPG_DEBUG) return d def calcUnitDistance(self, start, stop, lineAngle): - self.log.log("Enter MapCanvas->calcUnitDistance(self, start, stop, lineAngle)", ORPG_DEBUG) distance = self.calcPixelDistance( start, stop ) ln = "%0.2f" % lineAngle if self.layers['grid'].mode == GRID_HEXAGON: @@ -413,12 +369,10 @@ if ln == "0.00" or ln == "359.99": ud = distance / self.layers['grid'].unit_size else: ud = (sqrt(abs((stop.x - start.x)**2 + (stop.y - start.y)**2))) / self.layers['grid'].unit_size #ud = sqrt( abs((stop.x - start.x)**2 - (stop.y - start.y)**2) ) - self.log.log("Exit MapCanvas->calcUnitDistance(self, start, stop, lineAngle)", ORPG_DEBUG) return ud def on_tape_motion(self, evt): """Track mouse motion so we can update the marker visual every time it's moved""" - self.log.log("Enter MapCanvas->on_tape_motion(self, evt)", ORPG_DEBUG) # Make sure we have a mode to do anything, otherwise, we ignore this if self.markerMode: # Grap the current DC for all of the marker modes @@ -428,7 +382,7 @@ # Grab the current map position pos = self.snapMarker( evt.GetLogicalPosition( dc ) ) # Enable brush optimizations - #dc.SetOptimization( True ) + # dc.SetOptimization( True ) # Set up the pen used for drawing our marker dc.SetPen( wx.Pen(wx.RED, 1, wx.LONG_DASH) ) # Now, based on the marker mode, draw the right thing @@ -449,12 +403,10 @@ # Disable brush optimizations #dc.SetOptimization( False ) del dc - self.log.log("Exit MapCanvas->on_tape_motion(self, evt)", ORPG_DEBUG) def on_tape_down(self, evt): """Greg's experimental tape measure code. Hopefully, when this is done, it will all be modal based on a toolbar.""" - self.log.log("Enter MapCanvas->on_tape_down(self, evt)", ORPG_DEBUG) dc = wx.ClientDC( self ) self.PrepareDC( dc ) dc.SetUserScale(self.layers['grid'].mapscale,self.layers['grid'].mapscale) @@ -484,11 +436,9 @@ self.markerStart = pos self.markerStop = pos del dc - self.log.log("Exit MapCanvas->on_tape_down(self, evt)", ORPG_DEBUG) def on_tape_up(self, evt): """When we release the middle button, disable any marking updates that we have been doing.""" - self.log.log("Enter MapCanvas->on_tape_up(self, evt)", ORPG_DEBUG) # If we are in measure mode, draw the actual UNIT distance if self.markerMode == MARKER_MODE_MEASURE: dc = wx.ClientDC( self ) @@ -521,29 +471,21 @@ del font del dc self.markerMode = MARKER_MODE_NONE - self.log.log("Exit MapCanvas->on_tape_up(self, evt)", ORPG_DEBUG) # MODE 1 = MOVE, MODE 2 = whiteboard, MODE 3 = Tape measure def on_left_down(self, evt): - self.log.log("Enter MapCanvas->on_left_down(self, evt)", ORPG_DEBUG) if evt.ShiftDown(): self.on_tape_down (evt) else: self.frame.on_left_down(evt) - self.log.log("Exit MapCanvas->on_left_down(self, evt)", ORPG_DEBUG) def on_right_down(self, evt): - self.log.log("Enter MapCanvas->on_right_down(self, evt)", ORPG_DEBUG) if evt.ShiftDown(): pass else: self.frame.on_right_down(evt) - self.log.log("Exit MapCanvas->on_right_down(self, evt)", ORPG_DEBUG) def on_left_dclick(self, evt): - self.log.log("Enter MapCanvas->on_left_dclick(self, evt)", ORPG_DEBUG) if evt.ShiftDown(): pass else: self.frame.on_left_dclick(evt) - self.log.log("Exit MapCanvas->on_left_dclick(self, evt)", ORPG_DEBUG) def on_left_up(self, evt): - self.log.log("Enter MapCanvas->on_left_up(self, evt)", ORPG_DEBUG) if evt.ShiftDown(): self.on_tape_up(evt) elif component.get("tree").dragging: tree = component.get("tree") @@ -552,17 +494,13 @@ tree.dragging = False tree.drag_obj = None else: self.frame.on_left_up(evt) - self.log.log("Exit MapCanvas->on_left_up(self, evt)", ORPG_DEBUG) def on_motion(self, evt): - self.log.log("Enter MapCanvas->on_motion(self, evt)", ORPG_DEBUG) if evt.ShiftDown(): self.on_tape_motion(evt) elif evt.LeftIsDown() and component.get("tree").dragging: pass else: self.frame.on_motion(evt) - self.log.log("Exit MapCanvas->on_motion(self, evt)", ORPG_DEBUG) def on_zoom_out(self, evt): - self.log.log("Enter MapCanvas->on_zoom_out(self, evt)", ORPG_DEBUG) if self.layers['grid'].mapscale > 0.2: # attempt to keep same logical point at center of screen scale = self.layers['grid'].mapscale @@ -592,10 +530,8 @@ dc.EndDrawing() del dc self.zoom_display_timer.Start(500,1) - self.log.log("Exit MapCanvas->on_zoom_out(self, evt)", ORPG_DEBUG) def on_zoom_in(self, evt): - self.log.log("Enter MapCanvas->on_zoom_in(self, evt)", ORPG_DEBUG) # attempt to keep same logical point at center of screen scale = self.layers['grid'].mapscale scrollsize = self.GetScrollPixelsPerUnit() @@ -624,15 +560,12 @@ dc.EndDrawing() del dc self.zoom_display_timer.Start(500, 1) - self.log.log("Exit MapCanvas->on_zoom_in(self, evt)", ORPG_DEBUG) def on_prop(self, evt): - self.log.log("Enter MapCanvas->on_prop(self, evt)", ORPG_DEBUG) self.session = component.get("session") self.chat = component.get("chat") if (self.session.my_role() != self.session.ROLE_GM): self.chat.InfoPost("You must be a GM to use this feature") - self.log.log("Exit MapCanvas->on_prop(self, evt)", ORPG_DEBUG) return dlg = general_map_prop_dialog(self.frame.GetParent(),self.size,self.layers['bg'],self.layers['grid']) if dlg.ShowModal() == wx.ID_OK: @@ -641,10 +574,8 @@ self.Refresh(False) dlg.Destroy() os.chdir(self.root_dir) - self.log.log("Exit MapCanvas->on_prop(self, evt)", ORPG_DEBUG) def add_miniature(self, min_url, min_label='', min_unique=-1): - self.log.log("Enter MapCanvas->add_miniature(self, min_url, min_label, min_unique)", ORPG_DEBUG) if min_unique == -1: min_unique = not self.use_serial if min_url == "" or min_url == "http://": return if min_url[:7] != "http://" : min_url = "http://" + min_url @@ -659,27 +590,19 @@ try: id = 'mini-' + self.frame.session.get_next_id() self.layers['miniatures'].add_miniature(id, min_url, label=min_label) - except Exception, e: - self.log.log(traceback.format_exc(), ORPG_GENERAL) - self.log.log("Unable to load/resolve URL: " + min_url + " on resource ' + min_label + ' !!!", ORPG_GENERAL) + except: self.layers['miniatures'].rollback_serial() wx.EndBusyCursor() self.send_map_data() self.Refresh(False) - self.log.log("Exit MapCanvas->add_miniature(self, min_url, min_label, min_unique)", ORPG_DEBUG) def get_label_from_url(self, url=''): - self.log.log("Enter MapCanvas->get_label_from_url(self, url)", ORPG_DEBUG) - if url == '': - self.log.log("Exit MapCanvas->get_label_from_url(self, url)", ORPG_DEBUG) - return '' + if url == '': return '' start = url.rfind("/")+1 label = url[start:len(url)-4] - self.log.log("Exit MapCanvas->get_label_from_url(self, url)", ORPG_DEBUG) return label def toxml(self, action="update"): - self.log.log("Enter MapCanvas->toxml(self, " + action + ")", ORPG_DEBUG) if action == "new": self.size_changed = 1 xml_str = "<map version='" + self.map_version + "'" @@ -692,36 +615,27 @@ for k in keys: if (k != "fog" or action != "update"): s += self.layers[k].layerToXML(action) self.size_changed = 0 - if s: - self.log.log("Exit MapCanvas->toxml(self, " + action + ")", ORPG_DEBUG) - return xml_str + " action='" + action + "'>" + s + "</map>" + if s: return xml_str + " action='" + action + "'>" + s + "</map>" else: - if changed: - self.log.log("Exit MapCanvas->toxml(self, " + action + ")", ORPG_DEBUG) - return xml_str + " action='" + action + "'/>" - else: - self.log.log("Exit MapCanvas->toxml(self, " + action + ")", ORPG_DEBUG) - return "" + if changed: return xml_str + " action='" + action + "'/>" + else: return "" def takexml(self, xml): - # - # Added Process Dialog to display during long map parsings - # as well as a try block with an exception traceback to try - # and isolate some of the map related problems users have been - # experiencing --Snowdog 5/15/03 - # - # Apparently Process Dialog causes problems with linux.. commenting it out. sheez. - # --Snowdog 5/27/03 - self.log.log("Enter MapCanvas->takexml(self, xml)", ORPG_DEBUG) + """ + Added Process Dialog to display during long map parsings + as well as a try block with an exception traceback to try + and isolate some of the map related problems users have been + experiencing --Snowdog 5/15/03 + + Apparently Process Dialog causes problems with linux.. commenting it out. sheez. + --Snowdog 5/27/03 + """ try: #parse the map DOM xml_dom = parseXml(xml) - if xml_dom == None: - self.log.log("xml_dom == None\n" + xml, ORPG_INFO) - self.log.log("Exit MapCanvas->takexml(self, xml)", ORPG_DEBUG) - return + if xml_dom == None: return node_list = xml_dom.getElementsByTagName("map") - if len(node_list) < 1: self.log.log("Invalid XML format for mapper", ORPG_INFO) + if len(node_list) < 1: pass else: # set map version to incoming data so layers can convert self.map_version = node_list[0].getAttribute("version") @@ -762,18 +676,14 @@ self.map_version = MAP_VERSION self.Refresh(False) xml_dom.unlink() # eliminate circular refs - except: - self.log.log(traceback.format_exc(), ORPG_GENERAL) - self.log.log("EXCEPTION: Critical Error Loading Map!!!", ORPG_GENERAL) - self.log.log("Exit MapCanvas->takexml(self, xml)", ORPG_DEBUG) + except: pass def re_ids_in_xml(self, xml): - self.log.log("Enter MapCanvas->re_ids_in_xml(self, xml)", ORPG_DEBUG) new_xml = "" tmp_map = map_msg() xml_dom = parseXml(str(xml)) node_list = xml_dom.getElementsByTagName("map") - if len(node_list) < 1: self.log.log("Invalid XML format for mapper", ORPG_INFO) + if len(node_list) < 1: pass else: tmp_map.init_from_dom(node_list[0]) if tmp_map.children.has_key("miniatures"): @@ -801,13 +711,11 @@ l.init_prop("id", id) new_xml = tmp_map.get_all_xml() if xml_dom: xml_dom.unlink() - self.log.log("Exit MapCanvas->re_ids_in_xml(self, xml)", ORPG_DEBUG) return str(new_xml) class map_wnd(wx.Panel): def __init__(self, parent, id): self.log = component.get('log') - self.log.log("Enter map_wnd", ORPG_DEBUG) wx.Panel.__init__(self, parent, id) self.canvas = MapCanvas(self, -1) self.session = component.get('session') @@ -839,16 +747,13 @@ #self.Bind(wx.EVT_SIZE, self.on_size) self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeave) self.load_default() - self.log.log("Exit map_wnd", ORPG_DEBUG) def OnLeave(self, evt): if "__WXGTK__" in wx.PlatformInfo: wx.SetCursor(wx.StockCursor(wx.CURSOR_ARROW)) def load_default(self): - self.log.log("Enter map_wnd->load_default(self)", ORPG_DEBUG) if self.session.is_connected() and (self.session.my_role() != self.session.ROLE_GM) and (self.session.use_roles()): self.chat.InfoPost("You must be a GM to use this feature") - self.log.log("Exit map_wnd->load_default(self)", ORPG_DEBUG) return f = open(dir_struct["template"] + "default_map.xml") self.new_data(f.read()) @@ -856,19 +761,14 @@ self.canvas.send_map_data("new") if not self.session.is_connected() and (self.session.my_role() != self.session.ROLE_GM): self.session.update_role("GM") - self.log.log("Exit map_wnd->load_default(self)", ORPG_DEBUG) def new_data(self, data): - self.log.log("Enter map_wnd->new_data(self, data)", ORPG_DEBUG) self.canvas.takexml(data) self.update_tools() - self.log.log("Exit map_wnd->new_data(self, data)", ORPG_DEBUG) def on_save(self,evt): - self.log.log("Enter map_wnd->new_data(self, data)", ORPG_DEBUG) if (self.session.my_role() != self.session.ROLE_GM): self.chat.InfoPost("You must be a GM to use this feature") - self.log.log("Exit map_wnd->new_data(self, data)", ORPG_DEBUG) return d = wx.FileDialog(self.GetParent(), "Save map data", dir_struct["user"], "", "*.xml", wx.SAVE) if d.ShowModal() == wx.ID_OK: @@ -881,13 +781,10 @@ f.close() d.Destroy() os.chdir(self.root_dir) - self.log.log("Exit map_wnd->new_data(self, data)", ORPG_DEBUG) def on_open(self, evt): - self.log.log("Enter map_wnd->on_open(self, evt)", ORPG_DEBUG) if self.session.is_connected() and (self.session.my_role() != self.session.ROLE_GM) and (self.session.use_roles()): self.chat.InfoPost("You must be a GM to use this feature") - self.log.log("Exit map_wnd->on_open(self, evt)", ORPG_DEBUG) return d = wx.FileDialog(self.GetParent(), "Select a file", dir_struct["user"], "", "*.xml", wx.OPEN) if d.ShowModal() == wx.ID_OK: @@ -902,25 +799,18 @@ self.session.update_role("GM") d.Destroy() os.chdir(self.root_dir) - self.log.log("Exit map_wnd->on_open(self, evt)", ORPG_DEBUG) def get_current_layer_handler(self): - self.log.log("Enter map_wnd->get_current_layer_handler(self)", ORPG_DEBUG) - self.log.log("Exit map_wnd->get_current_layer_handler(self)", ORPG_DEBUG) return self.layer_handlers[self.current_layer] def get_tab_index(self, layer): """Return the index of a chatpanel in the wxNotebook.""" - self.log.log("Enter map_wnd->get_tab_index(self, layer)", ORPG_DEBUG) for i in xrange(self.layer_tabs.GetPageCount()): if (self.layer_tabs.GetPageText(i) == layer): - self.log.log("Exit map_wnd->get_tab_index(self, layer) return " + str(i), ORPG_DEBUG) return i - self.log.log("Exit map_wnd->get_tab_index(self, layer) return 0", ORPG_DEBUG) return 0 def on_layer_change(self, evt): - self.log.log("Enter map_wnd->on_layer_change(self, evt)", ORPG_DEBUG) layer = self.layer_tabs.GetPage(evt.GetSelection()) for i in xrange(0, len(self.layer_handlers)): if layer == self.layer_handlers[i]: self.current_layer = i @@ -930,67 +820,43 @@ else: bg.url_path.Show(True) self.canvas.Refresh(False) evt.Skip() - self.log.log("Exit map_wnd->on_layer_change(self, evt)", ORPG_DEBUG) def on_left_down(self, evt): - self.log.log("Enter map_wnd->on_left_down(self, evt)", ORPG_DEBUG) - self.log.log("Exit map_wnd->on_left_down(self, evt)", ORPG_DEBUG) self.layer_handlers[self.current_layer].on_left_down(evt) #double click handler added by Snowdog 5/03 def on_left_dclick(self, evt): - self.log.log("Enter map_wnd->on_left_dclick(self, evt)", ORPG_DEBUG) - self.log.log("Exit map_wnd->on_left_dclick(self, evt)", ORPG_DEBUG) self.layer_handlers[self.current_layer].on_left_dclick(evt) def on_right_down(self, evt): - self.log.log("Enter map_wnd->on_right_down(self, evt)", ORPG_DEBUG) - self.log.log("Exit map_wnd->on_right_down(self, evt)", ORPG_DEBUG) self.layer_handlers[self.current_layer].on_right_down(evt) def on_left_up(self, evt): - self.log.log("Enter map_wnd->on_left_up(self, evt)", ORPG_DEBUG) - self.log.log("Exit map_wnd->on_left_up(self, evt)", ORPG_DEBUG) self.layer_handlers[self.current_layer].on_left_up(evt) def on_motion(self, evt): - self.log.log("Enter map_wnd->on_motion(self, evt)", ORPG_DEBUG) - self.log.log("Exit map_wnd->on_motion(self, evt)", ORPG_DEBUG) self.layer_handlers[self.current_layer].on_motion(evt) def MapBar(self, id, data): - self.log.log("Enter map_wnd->MapBar(self, id, data)", ORPG_DEBUG) self.canvas.MAP_MODE = data - if id == 1: - self.canvas.MAP_MODE = data - self.log.log("Exit map_wnd->MapBar(self, id, data)", ORPG_DEBUG) + if id == 1: self.canvas.MAP_MODE = data def set_map_focus(self, evt): - self.log.log("Enter map_wnd->set_map_focus(self, evt)", ORPG_DEBUG) self.canvas.SetFocus() - self.log.log("Exit map_wnd->set_map_focus(self, evt)", ORPG_DEBUG) def pre_exit_cleanup(self): - self.log.log("Enter map_wnd->pre_exit_cleanup(self)", ORPG_DEBUG) # do some pre exit clean up for bitmaps or other objects try: ImageHandler.flushCache() self.canvas.pre_destory_cleanup() - except Exception, e: - self.log.log(traceback.format_exc(), ORPG_CRITICAL) - self.log.log("EXCEPTION: " + str(e), ORPG_CRITICAL) - self.log.log("Exit map_wnd->pre_exit_cleanup(self)", ORPG_DEBUG) + except: pass def update_tools(self): - self.log.log("Enter map_wnd->update_tools(self)", ORPG_DEBUG) for h in self.layer_handlers: h.update_info() - self.log.log("Exit map_wnd->update_tools(self)", ORPG_DEBUG) def on_hk_map_layer(self, evt): - self.log.log("Enter map_wnd->on_hk_map_layer(self, evt)", ORPG_DEBUG) id = self.top_frame.mainmenu.GetHelpString(evt.GetId()) - #print evt.GetMenu().GetTitle() if id == "Background Layer": self.current_layer = self.get_tab_index("Background") if id == "Grid Layer": self.current_layer = self.get_tab_index("Grid") if id == "Miniature Layer": self.current_layer = self.get_tab_index("Miniatures") @@ -998,15 +864,11 @@ elif id == "Fog Layer": self.current_layer = self.get_tab_index("Fog") elif id == "General Properties": self.current_layer = self.get_tab_index("General") self.layer_tabs.SetSelection(self.current_layer) - self.log.log("Exit map_wnd->on_hk_map_layer(self, evt)", ORPG_DEBUG) def on_flush_cache(self, evt): - self.log.log("Enter map_wnd->on_flush_cache(self, evt)", ORPG_DEBUG) ImageHandler.flushCache() - self.log.log("Exit map_wnd->on_flush_cache(self, evt)", ORPG_DEBUG) def build_menu(self): - self.log.log("Enter map_wnd->build_menu(self)", ORPG_DEBUG) # temp menu menu = wx.Menu() item = wx.MenuItem(menu, wx.ID_ANY, "&Load Map", "Load Map") @@ -1043,10 +905,7 @@ self.top_frame.Bind(wx.EVT_MENU, self.canvas.on_prop, item) menu.AppendItem(item) self.top_frame.mainmenu.Insert(2, menu, '&Map') - self.log.log("Exit map_wnd->build_menu(self)", ORPG_DEBUG) def get_hot_keys(self): - self.log.log("Enter map_wnd->get_hot_keys(self)", ORPG_DEBUG) self.build_menu() - self.log.log("Exit map_wnd->get_hot_keys(self)", ORPG_DEBUG) return []
--- a/orpg/mapper/map_msg.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/mapper/map_msg.py Thu Aug 20 03:00:39 2009 -0500 @@ -66,16 +66,11 @@ for c in xml_dom._get_childNodes(): name = c._get_nodeName() if not self.children.has_key(name): - if name == "miniatures": - self.children[name] = minis_msg(self.p_lock) - elif name == "grid": - self.children[name] = grid_msg(self.p_lock) - elif name == "bg": - self.children[name] = bg_msg(self.p_lock) - elif name == "whiteboard": - self.children[name] = whiteboard_msg(self.p_lock) - elif name == "fog": - self.children[name] = fog_msg(self.p_lock) + if name == "miniatures": self.children[name] = minis_msg(self.p_lock) + elif name == "grid": self.children[name] = grid_msg(self.p_lock) + elif name == "bg": self.children[name] = bg_msg(self.p_lock) + elif name == "whiteboard": self.children[name] = whiteboard_msg(self.p_lock) + elif name == "fog": self.children[name] = fog_msg(self.p_lock) else: print "Unrecognized tag " + name + " found in map_msg.init_from_dom - skipping" continue
--- a/orpg/mapper/map_prop_dialog.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/mapper/map_prop_dialog.py Thu Aug 20 03:00:39 2009 -0500 @@ -201,6 +201,7 @@ data = dlg.GetColourData() self.ctrls[CTRL_GRID_COLOR].SetBackgroundColour(data.GetColour()) dlg.Destroy() + def on_ok(self,evt): try: self.size = (int(self.ctrls[CTRL_WIDTH].GetValue()),int(self.ctrls[CTRL_HEIGHT].GetValue())) except: pass
--- a/orpg/mapper/map_utils.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/mapper/map_utils.py Thu Aug 20 03:00:39 2009 -0500 @@ -1,36 +1,35 @@ -#------------------------------------------------ -# file: map_utils.py -# -# This file contains generic utility functions -# for use in the openrpg mapping system -# ----------------------------------------------- +""" + file: map_utils.py + + This file contains generic utility functions + for use in the openrpg mapping system +""" import math - -#----------------------------------------------------------------------- -# distance_between() -# Returns the distance between two points -#----------------------------------------------------------------------- +""" + distance_between() + Returns the distance between two points +""" def distance_between( x1, y1, x2, y2 ): "Returns the distance between two points" dx = x2 - x1 dy = y2 - y1 return math.sqrt( dx*dx + dy*dy ) -#----------------------------------------------------------------------- -# proximity_test() -# Tests if 'test_point' (T) is close (within 'threshold' units) to the -# line segment 'start_point' to 'end_point' (PQ). -# -# The closest point (R) to T on the line PQ is given by: -# R = P + u (Q - P) -# TR is perpendicular to PQ so: -# (T - R) dot (Q - P) = 0 -# Solving these two equations gives the equation for u (see below). -# -# If u < 0 or u > 1 then R is not within the line segment and we simply -# test against point P or Q. -#----------------------------------------------------------------------- +""" + proximity_test() + Tests if 'test_point' (T) is close (within 'threshold' units) to the + line segment 'start_point' to 'end_point' (PQ). + + The closest point (R) to T on the line PQ is given by: + R = P + u (Q - P) + TR is perpendicular to PQ so: + (T - R) dot (Q - P) = 0 + Solving these two equations gives the equation for u (see below). + + If u < 0 or u > 1 then R is not within the line segment and we simply + test against point P or Q. +""" def proximity_test( start_point, end_point, test_point, threshold ): "Test if a point is close to a line segment" x1,y1 = start_point
--- a/orpg/mapper/min_dialogs.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/mapper/min_dialogs.py Thu Aug 20 03:00:39 2009 -0500 @@ -417,10 +417,14 @@ sizer.Add(self.label, 0, wx.EXPAND) sizer.Add(wx.Size(10,10)) self.heading = wx.RadioBox(self, MIN_HEADING, "Heading", - choices=["None","N","NE","E","SE","S","SW","W","NW"],majorDimension=5,style=wx.RA_SPECIFY_COLS) + choices=["None","N","NE", + "E","SE","S", + "SW","W","NW"],majorDimension=5,style=wx.RA_SPECIFY_COLS) self.heading.SetSelection(min.heading) self.face = wx.RadioBox(self, MIN_FACE, "Facing", - choices=["None","N","NE","E","SE","S","SW","W","NW"],majorDimension=5,style=wx.RA_SPECIFY_COLS) + choices=["None","N","NE", + "E","SE","S", + "SW","W","NW"],majorDimension=5,style=wx.RA_SPECIFY_COLS) self.face.SetSelection(min.face) self.locked = wx.CheckBox(self, MIN_LOCK, " Lock") self.locked.SetValue(min.locked)
--- a/orpg/mapper/miniatures.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/mapper/miniatures.py Thu Aug 20 03:00:39 2009 -0500 @@ -64,9 +64,10 @@ return value class BmpMiniature: - def __init__(self, id,path, bmp, pos=cmpPoint(0,0), heading=FACE_NONE, face=FACE_NONE, label="", locked=False, hide=False, snap_to_align=SNAPTO_ALIGN_CENTER, zorder=0, width=0, height=0, log=None, local=False, localPath='', localTime=-1): - self.log = log - self.log.log("Enter BmpMiniature", ORPG_DEBUG) + def __init__(self, id,path, bmp, pos=cmpPoint(0,0), + heading=FACE_NONE, face=FACE_NONE, label="", + locked=False, hide=False, snap_to_align=SNAPTO_ALIGN_CENTER, + zorder=0, width=0, height=0, log=None, local=False, localPath='', localTime=-1): self.heading = heading self.face = face self.label = label @@ -92,22 +93,15 @@ self.bottom = bmp.GetHeight() self.isUpdated = False self.gray = False - self.log.log("Exit BmpMiniature", ORPG_DEBUG) def __del__(self): - self.log.log("Enter BmpMiniature->__del__(self)", ORPG_DEBUG) del self.bmp self.bmp = None - self.log.log("Exit BmpMiniature->__del__(self)", ORPG_DEBUG) def set_bmp(self, bmp): - self.log.log("Enter BmpMiniature->set_bmp(self, bmp)", ORPG_DEBUG) self.bmp = bmp - self.log.log("Exit BmpMiniature->set_bmp(self, bmp)", ORPG_DEBUG) def set_min_props(self, heading=FACE_NONE, face=FACE_NONE, label="", locked=False, hide=False, width=0, height=0): - self.log.log("Enter BmpMiniature->set_min_props(self, heading, face, label, locked, hide, width, height)", - ORPG_DEBUG) self.heading = heading self.face = face self.label = label @@ -118,33 +112,24 @@ self.width = int(width) self.height = int(height) self.isUpdated = True - self.log.log("Exit BmpMiniature->set_min_props(self, heading, face, label, locked, hide, width, height)", - ORPG_DEBUG) def hit_test(self, pt): - self.log.log("Enter BmpMiniature->hit_test(self, pt)", ORPG_DEBUG) rect = self.get_rect() result = None result = rect.InsideXY(pt.x, pt.y) - self.log.log("Exit BmpMiniature->hit_test(self, pt)", ORPG_DEBUG) return result def get_rect(self): - self.log.log("Enter BmpMiniature->get_rect(self)", ORPG_DEBUG) ret = wx.Rect(self.pos.x, self.pos.y, self.bmp.GetWidth(), self.bmp.GetHeight()) - self.log.log("Exit BmpMiniature->get_rect(self)", ORPG_DEBUG) return ret def draw(self, dc, mini_layer, op=wx.COPY): - self.log.log("Enter BmpMiniature->draw(self, dc, mini_layer, op)", ORPG_DEBUG) if isinstance(self.bmp, tuple): - self.log.log("bmp is a tuple, it shouldnt be!", ORPG_INFO) self.bmp = wx.ImageFromMime(self.bmp[1], self.bmp[2]).ConvertToBitmap() if self.bmp != None and self.bmp.Ok(): # check if hidden and GM: we outline the mini in grey (little bit smaller than the actual size) # and write the label in the center of the mini if self.hide and mini_layer.canvas.frame.session.my_role() == mini_layer.canvas.frame.session.ROLE_GM: - self.log.log("Enter BmpMiniature->draw->Draw Hidden", ORPG_DEBUG) # set the width and height of the image if self.width and self.height: tmp_image = self.bmp.ConvertToImage() @@ -199,12 +184,10 @@ dc.DrawRectangle(self.pos.x, self.pos.y, self.bmp.GetWidth(), self.bmp.GetHeight()) dc.SetBrush(wx.NullBrush) dc.SetPen(wx.NullPen) - self.log.log("Exit BmpMiniature->draw->Draw Hidden", ORPG_DEBUG) return True - elif self.hide: self.log.log("Enter/Exit BmpMiniature->draw->Skip Hidden", ORPG_DEBUG); return True + elif self.hide: return True else: - self.log.log("Enter BmpMiniature->draw->Not Hidden", ORPG_DEBUG) # set the width and height of the image bmp = self.bmp if self.width and self.height: @@ -362,17 +345,12 @@ self.bottom+=5 self.left-=5 self.right+=5 - self.log.log("Exit BmpMiniature->draw->Not Hidden", ORPG_DEBUG) return True - else: self.log.log("Exit BmpMiniature->draw(self, dc, mini_layer, op) return False", ORPG_DEBUG); return False - self.log.log("Exit BmpMiniature->draw(self, dc, mini_layer, op)", ORPG_DEBUG) + else: return False def toxml(self, action="update"): - self.log.log("Enter BmpMiniature->toxml(self, " + action + ")", ORPG_DEBUG) if action == "del": xml_str = "<miniature action='del' id='" + self.id + "'/>" - self.log.log(xml_str, ORPG_DEBUG) - self.log.log("Exit BmpMiniature->toxml(self, " + action + ")", ORPG_DEBUG) return xml_str xml_str = "<miniature" xml_str += " action='" + action + "'" @@ -397,58 +375,41 @@ xml_str += ' localPath="' + str(urllib.quote(self.localPath).replace('%3A', ':')) + '"' xml_str += ' localTime="' + str(self.localTime) + '"' xml_str += " />" - self.log.log(xml_str, ORPG_DEBUG) - self.log.log("Exit BmpMiniature->toxml(self, " + action + ")", ORPG_DEBUG) if (action == "update" and self.isUpdated) or action == "new": self.isUpdated = False return xml_str else: return '' def takedom(self, xml_dom): - self.log.log("Enter BmpMiniature->takedom(self, xml_dom)", ORPG_DEBUG) self.id = xml_dom.getAttribute("id") - self.log.log("self.id=" + str(self.id), ORPG_DEBUG) if xml_dom.hasAttribute("posx"): self.pos.x = int(xml_dom.getAttribute("posx")) - self.log.log("self.pos.x=" + str(self.pos.x), ORPG_DEBUG) if xml_dom.hasAttribute("posy"): self.pos.y = int(xml_dom.getAttribute("posy")) - self.log.log("self.pos.y=" + str(self.pos.y), ORPG_DEBUG) if xml_dom.hasAttribute("heading"): self.heading = int(xml_dom.getAttribute("heading")) - self.log.log("self.heading=" + str(self.heading), ORPG_DEBUG) if xml_dom.hasAttribute("face"): self.face = int(xml_dom.getAttribute("face")) - self.log.log("self.face=" + str(self.face), ORPG_DEBUG) if xml_dom.hasAttribute("path"): self.path = urllib.unquote(xml_dom.getAttribute("path")) self.set_bmp(ImageHandler.load(self.path, 'miniature', self.id)) - self.log.log("self.path=" + self.path, ORPG_DEBUG) if xml_dom.hasAttribute("locked"): if xml_dom.getAttribute("locked") == '1' or xml_dom.getAttribute("locked") == 'True': self.locked = True else: self.locked = False - self.log.log("self.locked=" + str(self.locked), ORPG_DEBUG) if xml_dom.hasAttribute("hide"): if xml_dom.getAttribute("hide") == '1' or xml_dom.getAttribute("hide") == 'True': self.hide = True else: self.hide = False - self.log.log("self.hide=" + str(self.hide), ORPG_DEBUG) if xml_dom.hasAttribute("label"): self.label = xml_dom.getAttribute("label") - self.log.log("self.label=" + self.label, ORPG_DEBUG) if xml_dom.hasAttribute("zorder"): self.zorder = int(xml_dom.getAttribute("zorder")) - self.log.log("self.zorder=" + str(self.zorder), ORPG_DEBUG) if xml_dom.hasAttribute("align"): if xml_dom.getAttribute("align") == '1' or xml_dom.getAttribute("align") == 'True': self.snap_to_align = 1 else: self.snap_to_align = 0 - self.log.log("self.snap_to_align=" + str(self.snap_to_align), ORPG_DEBUG) if xml_dom.hasAttribute("width"): self.width = int(xml_dom.getAttribute("width")) - self.log.log("self.width=" + str(self.width), ORPG_DEBUG) if xml_dom.hasAttribute("height"): self.height = int(xml_dom.getAttribute("height")) - self.log.log("self.height=" + str(self.height), ORPG_DEBUG) - self.log.log("Exit BmpMiniature->takedom(self, xml_dom)", ORPG_DEBUG) ##----------------------------- ## miniature layer @@ -456,8 +417,6 @@ class miniature_layer(layer_base): def __init__(self, canvas): self.canvas = canvas - self.log = self.canvas.log - self.log.log("Enter miniature_layer", ORPG_DEBUG) self.settings = self.canvas.settings layer_base.__init__(self) self.id = -1 #added. @@ -470,22 +429,16 @@ if (font_size >= 10): font_size -= 2 self.label_font = wx.Font(font_size, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL, False, self.settings.get_setting('defaultfont')) - self.log.log("Exit miniature_layer", ORPG_DEBUG) def next_serial(self): - self.log.log("Enter miniature_layer->next_serial(self)", ORPG_DEBUG) self.serial_number += 1 - self.log.log("Exit miniature_layer->next_serial(self)", ORPG_DEBUG) return self.serial_number def get_next_highest_z(self): - self.log.log("Enter miniature_layer->get_next_highest_z(self)", ORPG_DEBUG) z = len(self.miniatures)+1 - self.log.log("Exit miniature_layer->get_next_highest_z(self)", ORPG_DEBUG) return z def cleanly_collapse_zorder(self): - self.log.log("Enter miniature_layer->cleanly_collapse_zorder(self)", ORPG_DEBUG) # lock the zorder stuff sorted_miniatures = self.miniatures[:] sorted_miniatures.sort(cmp_zorder) @@ -493,11 +446,9 @@ for mini in sorted_miniatures: mini.zorder = i i = i + 1 - self.log.log("Exit miniature_layer->cleanly_collapse_zorder(self)", ORPG_DEBUG) # unlock the zorder stuff def collapse_zorder(self): - self.log.log("Enter miniature_layer->collapse_zorder(self)", ORPG_DEBUG) # lock the zorder stuff sorted_miniatures = self.miniatures[:] sorted_miniatures.sort(cmp_zorder) @@ -506,46 +457,31 @@ if (mini.zorder != MIN_STICKY_BACK) and (mini.zorder != MIN_STICKY_FRONT): mini.zorder = i else: pass i = i + 1 - self.log.log("Exit miniature_layer->collapse_zorder(self)", ORPG_DEBUG) # unlock the zorder stuff def rollback_serial(self): - self.log.log("Enter miniature_layer->rollback_serial(self)", ORPG_DEBUG) self.serial_number -= 1 - self.log.log("Exit miniature_layer->rollback_serial(self)", ORPG_DEBUG) def add_miniature(self, id, path, pos=cmpPoint(0,0), label="", heading=FACE_NONE, face=FACE_NONE, width=0, height=0, local=False, localPath='', localTime=-1): - self.log.log("Enter miniature_layer->add_miniature(self, id, path, pos, label, heading, face, width, height)", - ORPG_DEBUG) - self.log.log("Before mini creation: " + str(self.get_next_highest_z()), ORPG_DEBUG) bmp = ImageHandler.load(path, 'miniature', id) if bmp: mini = BmpMiniature(id, path, bmp, pos, heading, face, label, zorder=self. get_next_highest_z(), width=width, - height=height, log=self.log, local=local, localPath=localPath, localTime=localTime) - self.log.log("After mini creation:" + str(self.get_next_highest_z()), ORPG_DEBUG) + height=height, local=local, localPath=localPath, localTime=localTime) self.miniatures.append(mini) - self.log.log("After mini addition:" + str(self.get_next_highest_z()), ORPG_DEBUG) xml_str = "<map><miniatures>" xml_str += mini.toxml("new") xml_str += "</miniatures></map>" self.canvas.frame.session.send(xml_str) - else: self.log.log("Invalid image " + path + " has been ignored!", ORPG_DEBUG) - self.log.log("Exit miniature_layer->add_miniature(self, id, path, pos, label, heading, face, width, height)", - ORPG_DEBUG) def get_miniature_by_id(self, id): - self.log.log("Enter miniature_layer->get_miniature_by_id(self, id)", ORPG_DEBUG) for mini in self.miniatures: if str(mini.id) == str(id): - self.log.log("Exit miniature_layer->get_miniature_by_id(self, id) return miniID: " + str(id), ORPG_DEBUG) return mini - self.log.log("Exit miniature_layer->get_miniature_by_id(self, id) return None", ORPG_DEBUG) return None def del_miniature(self, min): - self.log.log("Enter miniature_layer->del_miniature(self, min)", ORPG_DEBUG) xml_str = "<map><miniatures>" xml_str += min.toxml("del") xml_str += "</miniatures></map>" @@ -553,18 +489,14 @@ self.miniatures.remove(min) del min self.collapse_zorder() - self.log.log("Exit miniature_layer->del_miniature(self, min)", ORPG_DEBUG) def del_all_miniatures(self): - self.log.log("Enter miniature_layer->del_all_miniatures(self)", ORPG_DEBUG) while len(self.miniatures): min = self.miniatures.pop() del min self.collapse_zorder() - self.log.log("Exit miniature_layer->del_all_miniatures(self)", ORPG_DEBUG) def layerDraw(self, dc, topleft, size): - self.log.log("Enter miniature_layer->layerDraw(self, dc, topleft, size)", ORPG_DEBUG) dc.SetFont(self.label_font) sorted_miniatures = self.miniatures[:] sorted_miniatures.sort(cmp_zorder) @@ -574,10 +506,8 @@ m.pos.x<topleft[0]+size[0]-m.left and m.pos.y<topleft[1]+size[1]-m.top): m.draw(dc, self) - self.log.log("Exit miniature_layer->layerDraw(self, dc, topleft, size)", ORPG_DEBUG) def find_miniature(self, pt, only_unlocked=False): - self.log.log("Enter miniature_layer->find_miniature(self, pt, only_unlocked)", ORPG_DEBUG) min_list = [] for m in self.miniatures: if m.hit_test(pt): @@ -586,13 +516,11 @@ elif not only_unlocked and m.locked: min_list.append(m) else: continue if len(min_list) > 0: - self.log.log("Exit miniature_layer->find_miniature(self, pt, only_unlocked)", ORPG_DEBUG) return min_list - else: self.log.log("Exit miniature_layer->find_miniature(self, pt, only_unlocked)", ORPG_DEBUG); return None + else: return None def layerToXML(self, action="update"): """ format """ - self.log.log("Enter miniature_layer->layerToXML(self, " + action + ")", ORPG_DEBUG) minis_string = "" if self.miniatures: for m in self.miniatures: minis_string += m.toxml(action) @@ -602,12 +530,10 @@ s += ">" s += minis_string s += "</miniatures>" - self.log.log("Exit miniature_layer->layerToXML(self, " + action + ")", ORPG_DEBUG) return s - else: self.log.log("Exit miniature_layer->layerToXML(self, " + action + ") return None", ORPG_DEBUG); return "" + else: return "" def layerTakeDOM(self, xml_dom): - self.log.log("Enter miniature_layer->layerTakeDOM(self, xml_dom)", ORPG_DEBUG) if xml_dom.hasAttribute('serial'): self.serial_number = int(xml_dom.getAttribute('serial')) children = xml_dom._get_childNodes() @@ -619,7 +545,6 @@ if mini: self.miniatures.remove(mini) del mini - else: self.log.log("Map Synchronization Error :: Update of unknown mini attempted", ORPG_DEBUG) elif action == "new": pos = cmpPoint(int(c.getAttribute('posx')),int(c.getAttribute('posy'))) path = urllib.unquote(c.getAttribute('path')) @@ -635,7 +560,7 @@ if c.hasAttribute('align'): snap_to_align = int(c.getAttribute('align')) if c.getAttribute('zorder'): zorder = int(c.getAttribute('zorder')) min = BmpMiniature(id, path, ImageHandler.load(path, 'miniature', id), pos, heading, - face, label, locked, hide, snap_to_align, zorder, width, height, self.log) + face, label, locked, hide, snap_to_align, zorder, width, height) self.miniatures.append(min) if c.hasAttribute('local') and c.getAttribute('local') == 'True' and os.path.exists(urllib.unquote(c.getAttribute('localPath'))): localPath = urllib.unquote(c.getAttribute('localPath')) @@ -655,8 +580,6 @@ else: mini = self.get_miniature_by_id(id) if mini: mini.takedom(c) - else: self.log.log("Map Synchronization Error :: Update of unknown mini attempted", ORPG_DEBUG) - self.log.log("Exit miniature_layer->layerTakeDOM(self, xml_dom)", ORPG_DEBUG) def upload(self, postdata, filename, modify=False, pos=cmpPoint(0,0)): self.lock.acquire()
--- a/orpg/mapper/miniatures_handler.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/mapper/miniatures_handler.py Thu Aug 20 03:00:39 2009 -0500 @@ -117,7 +117,7 @@ self.tooltip_timer.Stop() dt = myFileDropTarget(self) self.canvas.SetDropTarget(dt) - # wxInitAllImageHandlers() + #wxInitAllImageHandlers() def build_ctrls(self): base_layer_handler.build_ctrls(self) @@ -126,7 +126,7 @@ self.auto_label_cb.SetValue(self.auto_label) self.min_url = wx.ComboBox(self, wx.ID_ANY, "http://", style=wx.CB_DROPDOWN | wx.CB_SORT) self.localBrowse = wx.Button(self, wx.ID_ANY, 'Browse', style=wx.BU_EXACTFIT) - minilist = createMaskedButton( self, orpg.dirpath.dir_struct["icon"]+'questionhead.gif', 'Edit miniature properties', wx.ID_ANY) + minilist = createMaskedButton( self, dir_struct["icon"]+'questionhead.gif', 'Edit miniature properties', wx.ID_ANY) miniadd = wx.Button(self, wx.ID_OK, "Add Miniature", style=wx.BU_EXACTFIT) self.sizer.Add(self.auto_label_cb,0,wx.ALIGN_CENTER) self.sizer.Add((6, 0)) @@ -144,7 +144,7 @@ def on_browse(self, evt): if not self.role_is_gm_or_player(): return - dlg = wx.FileDialog(None, "Select a Miniature to load", orpg.dirpath.dir_struct["user"]+'webfiles/', + dlg = wx.FileDialog(None, "Select a Miniature to load", dir_struct["user"]+'webfiles/', wildcard="Image files (*.bmp, *.gif, *.jpg, *.png)|*.bmp;*.gif;*.jpg;*.png", style=wx.OPEN) if not dlg.ShowModal() == wx.ID_OK: dlg.Destroy() @@ -162,11 +162,12 @@ dc.SetUserScale(self.canvas.layers['grid'].mapscale,self.canvas.layers['grid'].mapscale) x = dc.DeviceToLogicalX(0) y = dc.DeviceToLogicalY(0) - thread.start_new_thread(self.canvas.layers['miniatures'].upload, (postdata, dlg.GetPath()), {'pos':cmpPoint(x,y)}) + thread.start_new_thread(self.canvas.layers['miniatures'].upload, + (postdata, dlg.GetPath()), {'pos':cmpPoint(x,y)}) else: try: min_url = component.get("cherrypy") + filename - except: return - min_url = dlg.GetDirectory().replace(orpg.dirpath.dir_struct["user"]+'webfiles' + os.sep, + except: return #chat.InfoPost('CherryPy is not started!') + min_url = dlg.GetDirectory().replace(dir_struct["user"]+'webfiles' + os.sep, component.get("cherrypy")) + '/' + filename # build url if min_url == "" or min_url == "http://": return @@ -190,7 +191,6 @@ except: # When there is an exception here, we should be decrementing the serial_number for reuse!! unablemsg= "Unable to load/resolve URL: " + min_url + " on resource \"" + min_label + "\"!!!\n\n" - #print unablemsg dlg = wx.MessageDialog(self,unablemsg, 'Url not found',wx.ICON_EXCLAMATION) dlg.ShowModal() dlg.Destroy()
--- a/orpg/mapper/region.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/mapper/region.py Thu Aug 20 03:00:39 2009 -0500 @@ -156,10 +156,14 @@ return IRect().make(self.left+pt.X,self.top+pt.Y,self.right+pt.X,self.bottom+pt.Y) def intersect(self,rect): - return IRect().make(max(self.left,rect.left),max(self.top,rect.top),min(self.right,rect.right),min(self.bottom,rect.bottom)) + return IRect().make(max(self.left,rect.left), + max(self.top,rect.top),min(self.right,rect.right), + min(self.bottom,rect.bottom)) def union(self,rect): - return IRect().make(min(self.left,rect.left),min(self.top,rect.top),max(self.right,rect.right),max(self.bottom,rect.bottom)) + return IRect().make(min(self.left,rect.left), + min(self.top,rect.top),max(self.right,rect.right), + max(self.bottom,rect.bottom)) def equals(self,rect): if (self.top==rect.top and self.bottom==rect.bottom and self.left==rect.left and self.right==rect.right): return 1 @@ -206,7 +210,7 @@ x+="]" return x -#remove all rectangles from list + #remove all rectangles from list def Clear(self): while(self.first): rect=self.first @@ -215,7 +219,7 @@ self.last=None self.count=0 -#add a new clipping rectangle to list + #add a new clipping rectangle to list def AddRect(self,rect): rect.prev=None rect.next=self.first @@ -224,7 +228,7 @@ if self.last is None: self.last=rect self.count += 1 -#removes the passed clipping rectangle from the list + #removes the passed clipping rectangle from the list def RemoveRect(self,rect): if not (rect.prev is None): rect.prev.next=rect.next else: self.first=rect.next @@ -232,8 +236,8 @@ else: self.last=rect.prev self.count -= 1 -# find the clipping rectangle at the the beginning of the list, remove it, -# and return it + # find the clipping rectangle at the the beginning of the list, remove it, + # and return it def RemoveHead(self): if self.count==0: return None rect=self.first @@ -242,8 +246,8 @@ self.count -= 1 return rect -# stealrects -- appends the list of clipping rectangles in pclist to the current -# list. removes the entries from pclist + # stealrects -- appends the list of clipping rectangles in pclist to the current + # list. removes the entries from pclist def StealRects(self,pclist): if pclist.first is None: return if self.first is None: @@ -258,7 +262,7 @@ pclist.last = None pclist.count = 0 -# utilitarian procedure to return all clipping rectangles as a Python list + # utilitarian procedure to return all clipping rectangles as a Python list def GetList(self): result=[] f = self.first
--- a/orpg/mapper/whiteboard.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/mapper/whiteboard.py Thu Aug 20 03:00:39 2009 -0500 @@ -43,8 +43,6 @@ class WhiteboardText: def __init__(self, id, text_string, pos, style, pointsize, weight, color="#000000", log=None): - self.log = log - self.log.log("Enter WhiteboardText", ORPG_DEBUG) self.scale = 1 self.r_h = RGBHex() self.selected = False @@ -61,15 +59,11 @@ r,g,b = self.r_h.rgb_tuple(self.textcolor) self.highlight_color = self.r_h.hexstring(r^255, g^255, b^255) self.isUpdated = False - self.log.log("Exit WhiteboardText", ORPG_DEBUG) def highlight(self, highlight=True): - self.log.log("Enter WhiteboardText->highlight(self, highlight)", ORPG_DEBUG) self.highlighted = highlight - self.log.log("Exit WhiteboardText->highlight(self, highlight)", ORPG_DEBUG) def set_text_props(self, text_string, style, point, weight, color="#000000"): - self.log.log("Enter WhiteboardText->set_text_props(self, text_string, style, point, weight, color)", ORPG_DEBUG) self.text_string = text_string self.textcolor = color self.style = int(style) @@ -79,24 +73,18 @@ self.weight = int(weight) self.font.SetWeight(self.weight) self.isUpdated = True - self.log.log("Exit WhiteboardText->set_text_props(self, text_string, style, point, weight, color)", ORPG_DEBUG) def hit_test(self, pt, dc): - self.log.log("Enter WhiteboardText->hit_test(self, pt, dc)", ORPG_DEBUG) rect = self.get_rect(dc) result = rect.InsideXY(pt.x, pt.y) - self.log.log("Exit WhiteboardText->hit_test(self, pt, dc)", ORPG_DEBUG) return result def get_rect(self, dc): - self.log.log("Enter WhiteboardText->get_rect(self, dc)", ORPG_DEBUG) dc.SetFont(self.font) (w,x,y,z) = dc.GetFullTextExtent(self.text_string) - self.log.log("Exit WhiteboardText->get_rect(self, dc)", ORPG_DEBUG) return wx.Rect(self.posx,self.posy,w,(x+y+z)) def draw(self, parent, dc, op=wx.COPY): - self.log.log("Enter WhiteboardText->draw(self, parent, dc, op)", ORPG_DEBUG) self.scale = parent.canvas.layers['grid'].mapscale if self.highlighted: textcolor = self.highlight_color else: textcolor = self.textcolor @@ -109,14 +97,10 @@ dc.SetFont(self.font) dc.DrawText(self.text_string, self.posx, self.posy) dc.SetTextForeground(wx.Colour(0,0,0)) - self.log.log("Exit WhiteboardText->draw(self, parent, dc, op)", ORPG_DEBUG) def toxml(self, action="update"): - self.log.log("Enter WhiteboardText->toxml(self, " + action + ")", ORPG_DEBUG) if action == "del": xml_str = "<text action='del' id='" + str(self.id) + "'/>" - self.log.log(xml_str, ORPG_DEBUG) - self.log.log("Exit WhiteboardText->toxml(self, " + action + ")", ORPG_DEBUG) return xml_str xml_str = "<text" xml_str += " action='" + action + "'" @@ -129,47 +113,33 @@ if self.text_string != None: xml_str+= " text_string='" + self.text_string + "'" if self.textcolor != None: xml_str += " color='" + self.textcolor + "'" xml_str += "/>" - self.log.log(xml_str, ORPG_DEBUG) - self.log.log("Exit WhiteboardText->toxml(self, " + action + ")", ORPG_DEBUG) if (action == "update" and self.isUpdated) or action == "new": self.isUpdated = False return xml_str else: return '' def takedom(self, xml_dom): - self.log.log("Enter WhiteboardText->takedom(self, xml_dom)", ORPG_DEBUG) self.text_string = xml_dom.getAttribute("text_string") - self.log.log("self.text_string=" + self.text_string, ORPG_DEBUG) self.id = xml_dom.getAttribute("id") - self.log.log("self.id=" + str(self.id), ORPG_DEBUG) if xml_dom.hasAttribute("posy"): self.posy = int(xml_dom.getAttribute("posy")) - self.log.log("self.posy=" + str(self.posy), ORPG_DEBUG) if xml_dom.hasAttribute("posx"): self.posx = int(xml_dom.getAttribute("posx")) - self.log.log("self.posx=" + str(self.posx), ORPG_DEBUG) if xml_dom.hasAttribute("weight"): self.weight = int(xml_dom.getAttribute("weight")) self.font.SetWeight(self.weight) - self.log.log("self.weight=" + str(self.weight), ORPG_DEBUG) if xml_dom.hasAttribute("style"): self.style = int(xml_dom.getAttribute("style")) self.font.SetStyle(self.style) - self.log.log("self.style=" + str(self.style), ORPG_DEBUG) if xml_dom.hasAttribute("pointsize"): self.pointsize = int(xml_dom.getAttribute("pointsize")) self.font.SetPointSize(self.pointsize) - self.log.log("self.pointsize=" + str(self.pointsize), ORPG_DEBUG) if xml_dom.hasAttribute("color") and xml_dom.getAttribute("color") != '': self.textcolor = xml_dom.getAttribute("color") if self.textcolor == '#0000000': self.textcolor = '#000000' - self.log.log("self.textcolor=" + self.textcolor, ORPG_DEBUG) - self.log.log("Exit WhiteboardText->takedom(self, xml_dom)", ORPG_DEBUG) class WhiteboardLine: def __init__(self, id, line_string, upperleft, lowerright, color="#000000", width=1, log=None): - self.log = log - self.log.log("Enter WhiteboardLine", ORPG_DEBUG) self.scale = 1 self.r_h = RGBHex() if color == '': color = "#000000" @@ -183,16 +153,14 @@ self.highlighted = False r,g,b = self.r_h.rgb_tuple(self.linecolor) self.highlight_color = self.r_h.hexstring(r^255, g^255, b^255) - self.log.log("Exit WhiteboardLine", ORPG_DEBUG) def highlight(self, highlight=True): - self.log.log("Enter WhiteboardLine->highlight(self, highlight)", ORPG_DEBUG) self.highlighted = highlight - self.log.log("Enter WhiteboardLine->highlight(self, highlight)", ORPG_DEBUG) - def set_line_props(self, line_string="", upperleftx=0, upperlefty=0, - lowerrightx=0, lowerrighty=0, color="#000000", width=1): - self.log.log("Enter WhiteboardLine->set_line_props(self, line_string, upperleftx, upperlefty, lowerrightx, lowerrighty, color, width)", ORPG_DEBUG) + def set_line_props(self, line_string="", + upperleftx=0, upperlefty=0, + lowerrightx=0, lowerrighty=0, + color="#000000", width=1): self.line_string = line_string self.upperleft.x = upperleftx self.upperleft.y = upperlefty @@ -200,28 +168,22 @@ self.lowerright.y = lowerrighty self.linecolor = color self.linewidth = width - self.log.log("Exit WhiteboardLine->set_line_props(self, line_string, upperleftx, upperlefty, lowerrightx, lowerrighty, color, width)", ORPG_DEBUG) def hit_test(self, pt): - self.log.log("Enter WhiteboardLine->hit_test(self, pt)", ORPG_DEBUG) coords = self.line_string.split(";") stcords = coords[0].split(",") oldicords = (int(stcords[0]),int(stcords[1])) for coordinate_string_counter in range(1, len(coords)): stcords = coords[coordinate_string_counter].split(",") if stcords[0] == "": - self.log.log("Exit WhiteboardLine->hit_test(self, pt) return False", ORPG_DEBUG) return False icords = (int(stcords[0]),int(stcords[1])) if orpg.mapper.map_utils.proximity_test(oldicords,icords,pt,12): - self.log.log("Exit WhiteboardLine->hit_test(self, pt) return True", ORPG_DEBUG) return True oldicords = icords - self.log.log("Exit WhiteboardLine->hit_test(self, pt) return False", ORPG_DEBUG) return False def draw(self, parent, dc, op=wx.COPY): - self.log.log("Enter WhiteboardLine->draw(self, parent, dc, op=wx.COPY)", ORPG_DEBUG) self.scale = parent.canvas.layers['grid'].mapscale if self.highlighted: linecolor = self.highlight_color else: linecolor = self.linecolor @@ -248,14 +210,10 @@ dc.SetPen(wx.NullPen) dc.SetBrush(wx.NullBrush) #selected outline - self.log.log("Exit WhiteboardLine->draw(self, parent, dc, op=wx.COPY)", ORPG_DEBUG) def toxml(self, action="update"): - self.log.log("Enter WhiteboardLine->toxml(self, " + action + ")", ORPG_DEBUG) if action == "del": xml_str = "<line action='del' id='" + str(self.id) + "'/>" - self.log.log(xml_str, ORPG_DEBUG) - self.log.log("Exit WhiteboardLine->toxml(self, " + action + ")", ORPG_DEBUG) return xml_str # if there are any changes, make sure id is one of them xml_str = "<line" @@ -273,38 +231,26 @@ if self.linewidth != None: xml_str += " width='" + str(self.linewidth) + "'" xml_str += "/>" - self.log.log(xml_str, ORPG_DEBUG) - self.log.log("Exit WhiteboardLine->toxml(self, " + action + ")", ORPG_DEBUG) if action == "new": return xml_str return '' def takedom(self, xml_dom): - self.log.log("Enter WhiteboardLine->takedom(self, xml_dom)", ORPG_DEBUG) self.line_string = xml_dom.getAttribute("line_string") - self.log.log("self.line_string=" + self.line_string, ORPG_DEBUG) self.id = xml_dom.getAttribute("id") - self.log.log("self.id=" + str(self.id), ORPG_DEBUG) if xml_dom.hasAttribute("upperleftx"): self.upperleft.x = int(xml_dom.getAttribute("upperleftx")) - self.log.log("self.upperleft.x=" + str(self.upperleft.x), ORPG_DEBUG) if xml_dom.hasAttribute("upperlefty"): self.upperleft.y = int(xml_dom.getAttribute("upperlefty")) - self.log.log("self.upperleft.y=" + str(self.upperleft.y), ORPG_DEBUG) if xml_dom.hasAttribute("lowerrightx"): self.lowerright.x = int(xml_dom.getAttribute("lowerrightx")) - self.log.log("self.lowerright.x=" + str(self.lowerright.x), ORPG_DEBUG) if xml_dom.hasAttribute("lowerrighty"): self.lowerright.y = int(xml_dom.getAttribute("lowerrighty")) - self.log.log("self.lowerright.y=" + str(self.lowerright.y), ORPG_DEBUG) if xml_dom.hasAttribute("color") and xml_dom.getAttribute("color") != '': self.linecolor = xml_dom.getAttribute("color") if self.linecolor == '#0000000': self.linecolor = '#000000' - self.log.log("self.linecolor=" + self.linecolor, ORPG_DEBUG) if xml_dom.hasAttribute("width"): self.linewidth = int(xml_dom.getAttribute("width")) - self.log.log("self.linewidth=" + str(self.linewidth), ORPG_DEBUG) - self.log.log("Exit WhiteboardLine->takedom(self, xml_dom)", ORPG_DEBUG) ##----------------------------- ## whiteboard layer @@ -313,8 +259,6 @@ def __init__(self, canvas): self.canvas = canvas - self.log = self.canvas.log - self.log.log("Enter whiteboard_layer", ORPG_DEBUG) layer_base.__init__(self) self.r_h = RGBHex() self.id = -1 @@ -324,64 +268,48 @@ self.color = "#000000" self.width = 1 self.removedLines = [] - self.log.log("Exit whiteboard_layer", ORPG_DEBUG) def next_serial(self): - self.log.log("Enter whiteboard_layer->next_serial(self)", ORPG_DEBUG) self.serial_number += 1 - self.log.log("Exit whiteboard_layer->next_serial(self)", ORPG_DEBUG) return self.serial_number def get_next_highest_z(self): - self.log.log("Enter whiteboard_layer->get_next_highest_z(self)", ORPG_DEBUG) z = len(self.lines)+1 - self.log.log("Exit whiteboard_layer->get_next_highest_z(self)", ORPG_DEBUG) return z def cleanly_collapse_zorder(self): - self.log.log("Enter/Exit whiteboard_layer->cleanly_collapse_zorder(self)", ORPG_DEBUG) + pass def collapse_zorder(self): - self.log.log("Enter/Exit whiteboard_layer->collapse_zorder(self)", ORPG_DEBUG) + pass def rollback_serial(self): - self.log.log("Enter whiteboard_layer->rollback_serial(self)", ORPG_DEBUG) self.serial_number -= 1 - self.log.log("Exit whiteboard_layer->rollback_serial(self)", ORPG_DEBUG) def add_line(self, line_string="", upperleft=cmpPoint(0,0), lowerright=cmpPoint(0,0), color="#000000", width=1): - self.log.log("Enter whiteboard_layer->add_line(self, line_string, upperleft, lowerright, color, width)", ORPG_DEBUG) id = 'line-' + str(self.next_serial()) - line = WhiteboardLine(id, line_string, upperleft, lowerright, color=self.color, width=self.width, log=self.log) + line = WhiteboardLine(id, line_string, upperleft, lowerright, color=self.color, width=self.width) self.lines.append(line) xml_str = "<map><whiteboard>" xml_str += line.toxml("new") xml_str += "</whiteboard></map>" self.canvas.frame.session.send(xml_str) self.canvas.Refresh(True) - self.log.log("Exit whiteboard_layer->add_line(self, line_string, upperleft, lowerright, color, width)", ORPG_DEBUG) return line def get_line_by_id(self, id): - self.log.log("Enter whiteboard_layer->get_line_by_id(self, id)", ORPG_DEBUG) for line in self.lines: if str(line.id) == str(id): - self.log.log("Exit whiteboard_layer->get_line_by_id(self, id) return LineID: " + str(id), ORPG_DEBUG) return line - self.log.log("Exit whiteboard_layer->get_line_by_id(self, id) return None", ORPG_DEBUG) return None def get_text_by_id(self, id): - self.log.log("Enter whiteboard_layer->get_text_by_id(self, id)", ORPG_DEBUG) for text in self.texts: if str(text.id) == str(id): - self.log.log("Exit whiteboard_layer->get_text_by_id(self, id) return textID: " + str(id), ORPG_DEBUG) return text - self.log.log("Enter whiteboard_layer->get_text_by_id(self, id) return None", ORPG_DEBUG) return None def del_line(self, line): - self.log.log("Enter whiteboard_layer->del_line(self, line)", ORPG_DEBUG) xml_str = "<map><whiteboard>" xml_str += line.toxml("del") xml_str += "</whiteboard></map>" @@ -390,7 +318,6 @@ self.lines.remove(line) self.removedLines.append(line) self.canvas.Refresh(True) - self.log.log("Exit whiteboard_layer->del_line(self, line)", ORPG_DEBUG) def undo_line(self): if len(self.removedLines)>0: @@ -400,14 +327,11 @@ self.canvas.Refresh(True) def del_all_lines(self): - self.log.log("Enter whiteboard_layer->del_all_lines(self)", ORPG_DEBUG) for i in xrange(len(self.lines)): self.del_line(self.lines[0]) print self.lines - self.log.log("Exit whiteboard_layer->del_all_lines(self)", ORPG_DEBUG) def del_text(self, text): - self.log.log("Enter whiteboard_layer->del_text(self, text)", ORPG_DEBUG) xml_str = "<map><whiteboard>" xml_str += text.toxml("del") xml_str += "</whiteboard></map>" @@ -415,87 +339,64 @@ if text: self.texts.remove(text) self.canvas.Refresh(True) - self.log.log("Exit whiteboard_layer->del_text(self, text)", ORPG_DEBUG) def layerDraw(self, dc): - self.log.log("Enter whiteboard_layer->layerDraw(self, dc)", ORPG_DEBUG) for m in self.lines: m.draw(self, dc) for m in self.texts: m.draw(self,dc) - self.log.log("Exit whiteboard_layer->layerDraw(self, dc)", ORPG_DEBUG) def hit_test_text(self, pos, dc): - self.log.log("Enter whiteboard_layer->hit_test_text(self, pos, dc)", ORPG_DEBUG) list_of_texts_matching = [] if self.canvas.layers['fog'].use_fog == 1: if self.canvas.frame.session.role != "GM": - self.log.log("Exit whiteboard_layer->hit_test_text(self, pos, dc)", ORPG_DEBUG) return list_of_texts_matching for m in self.texts: if m.hit_test(pos,dc): list_of_texts_matching.append(m) - self.log.log("Exit whiteboard_layer->hit_test_text(self, pos, dc)", ORPG_DEBUG) return list_of_texts_matching def hit_test_lines(self, pos, dc): - self.log.log("Enter whiteboard_layer->hit_test_lines(self, pos, dc)", ORPG_DEBUG) list_of_lines_matching = [] if self.canvas.layers['fog'].use_fog == 1: if self.canvas.frame.session.role != "GM": - self.log.log("Exit whiteboard_layer->hit_test_lines(self, pos, dc)", ORPG_DEBUG) return list_of_lines_matching for m in self.lines: if m.hit_test(pos): list_of_lines_matching.append(m) - self.log.log("Exit whiteboard_layer->hit_test_lines(self, pos, dc)", ORPG_DEBUG) return list_of_lines_matching def find_line(self, pt): - self.log.log("Enter whiteboard_layer->find_line(self, pt)", ORPG_DEBUG) scale = self.canvas.layers['grid'].mapscale dc = wx.ClientDC( self.canvas ) self.canvas.PrepareDC( dc ) dc.SetUserScale(scale,scale) line_list = self.hit_test_lines(pt,dc) if line_list: - self.log.log("Exit whiteboard_layer->find_line(self, pt)", ORPG_DEBUG) return line_list[0] else: - self.log.log("Exit whiteboard_layer->find_line(self, pt) return None", ORPG_DEBUG) return None def setcolor(self, color): - self.log.log("Enter whiteboard_layer->setcolor(self, color)", ORPG_DEBUG) r,g,b = color.Get() self.color = self.r_h.hexstring(r,g,b) - self.log.log("Exit whiteboard_layer->setcolor(self, color)", ORPG_DEBUG) def sethexcolor(self, hexcolor): - self.log.log("Enter whiteboard_layer->sethexcolor(self, hexcolor)", ORPG_DEBUG) self.color = hexcolor - self.log.log("Exit whiteboard_layer->sethexcolor(self, hexcolor)", ORPG_DEBUG) def setwidth(self, width): - self.log.log("Enter whiteboard_layer->setwidth(self, width)", ORPG_DEBUG) self.width = int(width) - self.log.log("Exit whiteboard_layer->setwidth(self, width)", ORPG_DEBUG) def set_font(self, font): - self.log.log("Enter whiteboard_layer->set_font(self, font)", ORPG_DEBUG) self.font = font - self.log.log("Exit whiteboard_layer->set_font(self, font)", ORPG_DEBUG) def add_text(self, text_string, pos, style, pointsize, weight, color="#000000"): - self.log.log("Enter whiteboard_layer->add_text(self, text_string, pos, style, pointsize, weight, color)", ORPG_DEBUG) id = 'text-' + str(self.next_serial()) - text = WhiteboardText(id,text_string, pos, style, pointsize, weight, color, self.log) + text = WhiteboardText(id,text_string, pos, style, pointsize, weight, color) self.texts.append(text) xml_str = "<map><whiteboard>" xml_str += text.toxml("new") xml_str += "</whiteboard></map>" self.canvas.frame.session.send(xml_str) self.canvas.Refresh(True) - self.log.log("Exit whiteboard_layer->add_text(self, text_string, pos, style, pointsize, weight, color)", ORPG_DEBUG) def draw_working_line(self, dc, line_string): - self.log.log("Enter whiteboard_layer->draw_working_line(self, dc, line_string)", ORPG_DEBUG) scale = self.canvas.layers['grid'].mapscale dc.SetPen(wx.BLACK_PEN) dc.SetBrush(wx.BLACK_BRUSH) @@ -517,11 +418,9 @@ y2 = y1 dc.SetPen(wx.NullPen) dc.SetBrush(wx.NullBrush) - self.log.log("Exit whiteboard_layer->draw_working_line(self, dc, line_string)", ORPG_DEBUG) def layerToXML(self, action="update"): """ format """ - self.log.log("Enter whiteboard_layer->layerToXML(self, " + action + ")", ORPG_DEBUG) white_string = "" if self.lines: for l in self.lines: white_string += l.toxml(action) @@ -533,15 +432,11 @@ s += ">" s += white_string s += "</whiteboard>" - self.log.log(s, ORPG_DEBUG) - self.log.log("Exit whiteboard_layer->layerToXML(self, " + action + ")", ORPG_DEBUG) return s else: - self.log.log("Exit whiteboard_layer->layerToXML(self, " + action + ")", ORPG_DEBUG) return "" def layerTakeDOM(self, xml_dom): - self.log.log("Enter whiteboard_layer->layerTakeDOM(self, xml_dom)", ORPG_DEBUG) serial_number = xml_dom.getAttribute('serial') if serial_number != "": self.serial_number = int(serial_number) children = xml_dom._get_childNodes() @@ -553,12 +448,9 @@ if nodename == 'line': line = self.get_line_by_id(id) if line != None: self.lines.remove(line) - else: self.log.log("Whiteboard error: Deletion of unknown line object attempted.", ORPG_GENERAL) elif nodename == 'text': text = self.get_text_by_id(id) if text != None: self.texts.remove(text) - else: self.log.log("Whiteboard error: Deletion of unknown text object attempted.", ORPG_GENERAL) - else: self.log.log("Whiteboard error: Deletion of unknown whiteboard object attempted.", ORPG_GENERAL) elif action == "new": if nodename == "line": try: @@ -575,10 +467,8 @@ width = int(l.getAttribute('width')) except: line_string = upperleftx = upperlefty = lowerrightx = lowerrighty = color = 0 - self.log.log(traceback.format_exc(), ORPG_GENERAL) - self.log.log("invalid line", ORPG_GENERAL) continue - line = WhiteboardLine(id, line_string, upperleft, lowerright, color, width, self.log) + line = WhiteboardLine(id, line_string, upperleft, lowerright, color, width) self.lines.append(line) elif nodename == "text": try: @@ -595,26 +485,21 @@ pos.x = int(posx) pos.y = int(posy) except: - self.log.log(traceback.format_exc(), ORPG_GENERAL) - self.log.log("invalid line", ORPG_GENERAL) continue - text = WhiteboardText(id, text_string, pos, style, pointsize, weight, color, self.log) + text = WhiteboardText(id, text_string, pos, style, pointsize, weight, color) self.texts.append(text) else: if nodename == "line": line = self.get_line_by_id(id) if line: line.takedom(l) - else: self.log.log("Whiteboard error: Update of unknown line attempted.", ORPG_GENERAL) if nodename == "text": text = self.get_text_by_id(id) if text: text.takedom(l) - else: self.log.log("Whiteboard error: Update of unknown text attempted.", ORPG_GENERAL) - self.log.log("Enter whiteboard_layer->layerTakeDOM(self, xml_dom)", ORPG_DEBUG) #self.canvas.send_map_data() def add_temp_line(self, line_string): line = WhiteboardLine(0, line_string, wx.Point(0,0), wx.Point(0,0), - color=self.color, width=self.width, log=self.log) + color=self.color, width=self.width) self.lines.append(line) return line
--- a/orpg/mapper/whiteboard_handler.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/mapper/whiteboard_handler.py Thu Aug 20 03:00:39 2009 -0500 @@ -68,8 +68,8 @@ self.live_refresh = wx.CheckBox(self, wx.ID_ANY, " Live Refresh") self.live_refresh.SetValue(True) self.widthList= wx.Choice(self, wx.ID_ANY, size= wx.Size(40, 20), - choices=['1','2','3','4','5','6','7','8','9','10']) - self.widthList.SetSelection(0) #always start showing "1" + choices=['1','2','3','4','5','6','7','8','9','10']) + self.widthList.SetSelection(0) self.sizer.Add(wx.StaticText(self, wx.ID_ANY, "Line Width: "),0,wx.ALIGN_CENTER) self.sizer.Add(self.widthList, 0, wx.EXPAND) self.sizer.Add(wx.Size(10,25)) @@ -104,8 +104,10 @@ self.txt_boxer.Add(self.text_control,1,wx.EXPAND) self.point_boxer = wx.BoxSizer(wx.HORIZONTAL) self.point_static = wx.StaticText(self.text_properties_dialog, -1, "Text Size: ") - self.point_control = wx.SpinCtrl(self.text_properties_dialog, wx.ID_ANY, value = "12", - min = 1, initial = 12, name = "Font Size: ") + self.point_control = wx.SpinCtrl(self.text_properties_dialog, + wx.ID_ANY, value = "12", + min = 1, initial = 12, + name = "Font Size: ") self.point_boxer.Add(self.point_static,1,wx.EXPAND) self.point_boxer.Add(wx.Size(10,10)) self.point_boxer.Add(self.point_control,0,wx.EXPAND) @@ -274,7 +276,9 @@ if (session.my_role() != session.ROLE_GM) and (session.use_roles()): component.get("chat").InfoPost("You must be a GM to use this feature") return - dlg = wx.MessageDialog(self, "Are you sure you want to delete all lines?","Delete All Lines",wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) + dlg = wx.MessageDialog(self, + "Are you sure you want to delete all lines?","Delete All Lines", + wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) if dlg.ShowModal() != wx.ID_YES: return self.canvas.layers['whiteboard'].del_all_lines() dc = self.create_dc() @@ -534,8 +538,8 @@ # to allow alternate drawing method to be used # 05-09-2003 Snowdog def freeform_motion(self, evt): -# if not self.drawing: -# return + #if not self.drawing: + # return scale = self.canvas.layers['grid'].mapscale dc = wx.ClientDC( self.canvas ) self.canvas.PrepareDC( dc )
--- a/orpg/networking/gsclient.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/networking/gsclient.py Thu Aug 20 03:00:39 2009 -0500 @@ -30,9 +30,9 @@ from orpg.dirpath import dir_struct from orpg.orpg_windows import * -#from orpg.orpg_xml import * import meta_server_lib import orpg.tools.orpg_settings +from orpg.tools.orpg_settings import settings import orpg.tools.rgbhex from orpg.orpgCore import component import traceback @@ -99,13 +99,10 @@ def __init__(self,parent): wx.Panel.__init__(self, parent, -1) self.parent = parent - self.log = component.get('log') - self.log.log("Enter game_server_panel", ORPG_DEBUG) self.password_manager = component.get('password_manager') # passtool --SD 8/03 self.frame = component.get('frame') self.session = component.get('session') - self.settings = component.get('settings') - self.xml = component.get('xml') + self.xml = component.get('xml') #Not used?? self.serverNameSet = 0 self.last_motd = "" self.buttons = {} @@ -114,14 +111,11 @@ self.build_ctrls() self.refresh_server_list() self.refresh_room_list() - self.log.log("Exit game_server_panel", ORPG_DEBUG) #--------------------------------------------------------- # [START] Snowdog: Updated Game Server Window 12/02 #--------------------------------------------------------- def build_ctrls(self): - self.log.log("Enter game_server_panel->build_ctrls(self)", ORPG_DEBUG) - ## Section Sizers (with frame edges and text captions) self.box_sizers = {} self.box_sizers["server"] = wx.StaticBox(self, -1, "Server") @@ -237,7 +231,6 @@ self.cur_room_index = -1 self.cur_server_index = -1 self.rmList = {} - self.log.log("Exit game_server_panel->build_ctrls(self)", ORPG_DEBUG) #--------------------------------------------------------- # [END] Snowdog: Updated Game Server Window 12/02 @@ -249,8 +242,6 @@ # 5/16/05 -- Snowdog #----------------------------------------------------- def on_server_dbclick(self, evt=None): - self.log.log("Enter game_server_panel->on_server_dbclick(self, evt)", ORPG_DEBUG) - #make sure address is updated just in case list select wasn't done try: self.on_select(evt) @@ -265,7 +256,6 @@ #address differs, disconnect. self.frame.kill_mplay_session() self.do_connect(address) - self.log.log("Exit game_server_panel->on_server_dbclick(self, evt)", ORPG_DEBUG) #----------------------------------------------------- @@ -275,8 +265,6 @@ #----------------------------------------------------- def on_room_dbclick(self, evt=None): - self.log.log("Enter game_server_panel->on_room_dbclick(self, evt)", ORPG_DEBUG) - #make sure address is updated just in case list select wasn't done try: self.on_select(evt) @@ -302,11 +290,9 @@ else: pwd = "" self.session.send_join_group(group_id, pwd) - self.log.log("Exit game_server_panel->on_room_dbclick(self, evt)", ORPG_DEBUG) def on_select(self,evt): - self.log.log("Enter game_server_panel->on_select(self,evt)", ORPG_DEBUG) id = evt.GetId() if id == LIST_ROOM: self.cur_room_index = evt.m_itemIndex @@ -317,19 +303,15 @@ port = self.svrList[self.cur_server_index].port self.texts["address"].SetValue(address+":"+str(port)) self.refresh_room_list() - self.log.log("Exit game_server_panel->on_select(self,evt)", ORPG_DEBUG) def on_text(self,evt): - self.log.log("Enter game_server_panel->on_text(self,evt)", ORPG_DEBUG) id = evt.GetId() if (id == ADDRESS) and (self.cur_server_index >= 0): #print "ADDRESS id = ", id, "index = ", self.cur_server_index self.cur_server_index = -1 evt.Skip() - self.log.log("Exit game_server_panel->on_text(self,evt)", ORPG_DEBUG) def add_room(self,data): - self.log.log("Enter game_server_panel->add_room(self,data)", ORPG_DEBUG) i = self.room_list.GetItemCount() if (data[2]=="1") or (data[2]=="True"): pwd="yes" else: pwd="no" @@ -338,21 +320,17 @@ self.room_list.SetStringItem(i,2,pwd) self.room_list.SetItemData(i,int(data[0])) self.refresh_room_list() - self.log.log("Exit game_server_panel->add_room(self,data)", ORPG_DEBUG) def del_room(self, data): - self.log.log("Enter game_server_panel->del_room(self, data)", ORPG_DEBUG) i = self.room_list.FindItemData(-1, int(data[0])) self.room_list.DeleteItem(i) self.refresh_room_list() - self.log.log("Exit game_server_panel->del_room(self, data)", ORPG_DEBUG) #--------------------------------------------------------- # [START] Snowdog Password/Room Name altering code 12/02 #--------------------------------------------------------- def update_room(self,data): - self.log.log("Enter game_server_panel->update_room(self,data)", ORPG_DEBUG) #------------------------------------------------------- # Udated 12/02 by Snowdog @@ -365,7 +343,6 @@ self.room_list.SetStringItem(i,1,data[3]) self.room_list.SetStringItem(i,2,pwd) self.refresh_room_list() - self.log.log("Exit game_server_panel->update_room(self,data)", ORPG_DEBUG) #--------------------------------------------------------- # [END] Snowdog Password/Room Name altering code 12/02 @@ -377,12 +354,9 @@ #self.sizers["room"].Layout() def set_lobbybutton(self,allow): - self.log.log("Enter game_server_panel->set_lobbybutton(self,allow)", ORPG_DEBUG) self.buttons[GS_JOINLOBBY].Enable(allow) - self.log.log("Exit game_server_panel->set_lobbybutton(self,allow)", ORPG_DEBUG) def set_connected(self,connected): - self.log.log("Enter game_server_panel->set_connected(self,connected)", ORPG_DEBUG) self.buttons[GS_CONNECT].Enable(not connected) self.buttons[GS_DISCONNECT].Enable(connected) self.buttons[GS_JOIN].Enable(connected) @@ -397,10 +371,8 @@ #data = self.session.get_my_group() self.frame.status.set_connect_status(self.name) self.set_cur_room_text("Lobby") - self.log.log("Exit game_server_panel->set_connected(self,connected)", ORPG_DEBUG) def on_button(self,evt): - self.log.log("Enter game_server_panel->son_button(self,evt)", ORPG_DEBUG) id = evt.GetId() if id == GS_CONNECT: address = self.texts["address"].GetValue() @@ -410,18 +382,12 @@ except: self.name = `address` self.do_connect(address) - elif id == GS_DISCONNECT: - self.frame.kill_mplay_session() - elif id == GS_CREATE_ROOM: - self.do_create_group() - elif id == GS_JOIN: - self.do_join_group() - elif id == GS_JOINLOBBY: - self.do_join_lobby() - elif id == GS_SERVER_REFRESH: - self.refresh_server_list() - elif id == GS_PWD: - self.texts["room_pwd"].Enable(evt.Checked()) + elif id == GS_DISCONNECT: self.frame.kill_mplay_session() + elif id == GS_CREATE_ROOM: self.do_create_group() + elif id == GS_JOIN: self.do_join_group() + elif id == GS_JOINLOBBY: self.do_join_lobby() + elif id == GS_SERVER_REFRESH: self.refresh_server_list() + elif id == GS_PWD: self.texts["room_pwd"].Enable(evt.Checked()) elif id == OR_CLOSE: dlg = wx.MessageDialog(self,"Quit OpenRPG?","OpenRPG",wx.YES_NO) if dlg.ShowModal() == wx.ID_YES: @@ -430,10 +396,8 @@ self.frame.closed_confirmed() elif id == GS_CLOSE: self.parent.OnMB_GameServerBrowseServers() - self.log.log("Exit game_server_panel->son_button(self,evt)", ORPG_DEBUG) def refresh_room_list(self): - self.log.log("Enter game_server_panel->refresh_room_list(self)", ORPG_DEBUG) self.room_list.DeleteAllItems() address = self.texts["address"].GetValue() try: @@ -458,31 +422,24 @@ self.colorize_group_list(groups) self.room_list.SortItems(roomCmp) wx.CallAfter(self.autosizeRooms) - self.log.log("Exit game_server_panel->refresh_room_list(self)", ORPG_DEBUG) def autosizeRooms(self): - self.log.log("Enter game_server_panel->autosizeRooms(self)", ORPG_DEBUG) self.room_list.SetColumnWidth(0, wx.LIST_AUTOSIZE) - #self.room_list.SetColumnWidth(1, wx.LIST_AUTOSIZE) - #self.room_list.SetColumnWidth(2, wx.LIST_AUTOSIZE) if self.room_list.GetColumnWidth(0) < 70: self.room_list.SetColumnWidth(0, 70) if self.room_list.GetColumnWidth(1) < 70: self.room_list.SetColumnWidth(1, 70) if self.room_list.GetColumnWidth(2) < 50: self.room_list.SetColumnWidth(2, 50) - self.log.log("Exit game_server_panel->autosizeRooms(self)", ORPG_DEBUG) def refresh_server_list(self): - self.log.log("Enter game_server_panel->refresh_server_list(self)", ORPG_DEBUG) - try: self.svrList = [] self.server_list.DeleteAllItems() xml_dom = meta_server_lib.get_server_list(["2"]); node_list = xml_dom.getElementsByTagName('server') hex = orpg.tools.rgbhex.RGBHex() - color1 = self.settings.get_setting("RoomColor_Active") - color2 = self.settings.get_setting("RoomColor_Locked") - color3 = self.settings.get_setting("RoomColor_Empty") - color4 = self.settings.get_setting("RoomColor_Lobby") + color1 = settings.get_setting("RoomColor_Active") + color2 = settings.get_setting("RoomColor_Locked") + color3 = settings.get_setting("RoomColor_Empty") + color4 = settings.get_setting("RoomColor_Lobby") if len(node_list): length = len(node_list) @@ -490,7 +447,9 @@ partLength = 1.0/length for n in node_list: if n.hasAttribute('id') and n.hasAttribute('name') and n.hasAttribute('num_users') and n.hasAttribute('address') and n.hasAttribute('port'): - self.svrList.append( server_instance(n.getAttribute('id'),n.getAttribute('name'), n.getAttribute('num_users'), n.getAttribute('address'),n.getAttribute('port'))) + self.svrList.append(server_instance(n.getAttribute('id'), n.getAttribute('name'), + n.getAttribute('num_users'), n.getAttribute('address'), + n.getAttribute('port'))) address = n.getAttribute('address') + ':' + n.getAttribute('port') self.rmList[address] = [] rooms = n.getElementsByTagName('room') @@ -553,10 +512,8 @@ except Exception, e: print "Server List not available." traceback.print_exc() - self.log.log("Exit game_server_panel->refresh_server_list(self)", ORPG_DEBUG) def failed_connection(self): - self.log.log("Enter game_server_panel->failed_connection(self)", ORPG_DEBUG) if(self.cur_server_index >= 0): id = self.servers[self.cur_server_index].getAttribute('id') meta = self.servers[self.cur_server_index].getAttribute('meta') @@ -566,10 +523,8 @@ # was removed. If it was, refresh the display if(meta_server_lib.post_failed_connection(id,meta=meta,address=address,port=port)): self.refresh_server_list() - self.log.log("Exit game_server_panel->failed_connection(self)", ORPG_DEBUG) def do_connect(self, address): - self.log.log("Enter game_server_panel->do_connect(self, address)", ORPG_DEBUG) chat = component.get('chat') chat.InfoPost("Locating server at " + address + "...") if self.session.connect(address): @@ -577,17 +532,13 @@ else: chat.SystemPost("Failed to connect to game server...") self.failed_connection() - self.log.log("Exit game_server_panel->do_connect(self, address)", ORPG_DEBUG) def do_join_lobby(self): - self.log.log("Enter game_server_panel->do_join_lobby(self)", ORPG_DEBUG) self.cur_room_index = 0 self.session.send_join_group("0","") self.set_lobbybutton(0); - self.log.log("Exit game_server_panel->do_join_lobby(self)", ORPG_DEBUG) def do_join_group(self): - self.log.log("Enter game_server_panel->do_join_group(self)", ORPG_DEBUG) if self.cur_room_index >= 0: if self.cur_room_index != 0: self.set_lobbybutton(1); @@ -606,10 +557,8 @@ pwd = "" if pwd != None: #pwd==None means the user clicked "Cancel" self.session.send_join_group(group_id,pwd) - self.log.log("Exit game_server_panel->do_join_group(self)", ORPG_DEBUG) def do_create_group(self): - self.log.log("Enter game_server_panel->do_create_group(self)", ORPG_DEBUG) name = self.texts["room_name"].GetValue() boot_pwd = self.texts["room_boot_pwd"].GetValue() minversion = self.texts["room_min_version"].GetValue() @@ -654,7 +603,6 @@ self.session.send( msg ) self.session.send_create_group(name,pwd,boot_pwd,minversion) self.set_lobbybutton(1); #enable the Lobby quickbutton - self.log.log("Exit game_server_panel->do_create_group(self)", ORPG_DEBUG) #--------------------------------------------------------- @@ -676,39 +624,31 @@ def colorize_group_list(self, groups): - self.log.log("Enter game_server_panel->colorize_group_list(self, groups)", ORPG_DEBUG) - try: hex = orpg.tools.rgbhex.RGBHex() -# activ = self.settings.get_setting("RoomColor_Active") -# lockt = self.settings.get_setting("RoomColor_Locked") -# empty = self.settings.get_setting("RoomColor_Empty") -# lobby = self.settings.get_setting("RoomColor_Lobby") -#renamed colors - TaS sirebral for gr in groups: item_list_location = self.room_list.FindItemData(-1,int(gr[0])) if item_list_location != -1: item = self.room_list.GetItem(item_list_location) if gr[0] == "0": -# active_state = lobby - r,g,b = hex.rgb_tuple(self.settings.get_setting("RoomColor_Lobby")) + + r,g,b = hex.rgb_tuple(settings.get_setting("RoomColor_Lobby")) elif gr[3] <> "0": -# active_state = activ + if gr[2] == "True" or gr[2] == "1": -# active_state = lockt - r,g,b = hex.rgb_tuple(self.settings.get_setting("RoomColor_Locked")) + + r,g,b = hex.rgb_tuple(settings.get_setting("RoomColor_Locked")) else: -# active_state = activ - r,g,b = hex.rgb_tuple(self.settings.get_setting("RoomColor_Active")) + + r,g,b = hex.rgb_tuple(settings.get_setting("RoomColor_Active")) else: -# active_state = empty - r,g,b = hex.rgb_tuple(self.settings.get_setting("RoomColor_Empty")) + + r,g,b = hex.rgb_tuple(settings.get_setting("RoomColor_Empty")) -# r,g,b = hex.rgb_tuple(active_state) + color = wx.Colour(red=r,green=g,blue=b) item.SetTextColour(color) self.room_list.SetItem(item) except: traceback.print_exc() - self.log.log("Exit game_server_panel->colorize_group_list(self, groups)", ORPG_DEBUG)
--- a/orpg/networking/meta_server_lib.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/networking/meta_server_lib.py Thu Aug 20 03:00:39 2009 -0500 @@ -34,7 +34,8 @@ __version__ = "$Id: meta_server_lib.py,v 1.40 2007/04/04 01:18:42 digitalxero Exp $" from orpg.orpg_version import PROTOCOL_VERSION -from orpg.orpgCore import * +from orpg.orpgCore import component +from orpg.tools.validate import validate from orpg.dirpath import dir_struct import urllib import orpg.minidom @@ -68,8 +69,7 @@ # Remove any leading or trailing data. This can happen on some satellite connections p = re.compile('(<servers>.*?</servers>)',re.DOTALL|re.IGNORECASE) mo = p.search(data) - if mo: - data = mo.group(0) + if mo: data = mo.group(0) if META_DEBUG: print @@ -84,11 +84,6 @@ return xml_dom def post_server_data( name, realHostName=None): - # build POST data -## data = urllib.urlencode( {"server_data[name]":name, -## "server_data[version]":PROTOCOL_VERSION, -## "act":"new"} ) -## if realHostName: data = urllib.urlencode( {"server_data[name]":name, "server_data[version]":PROTOCOL_VERSION, @@ -101,7 +96,9 @@ "server_data[version]":PROTOCOL_VERSION, "act":"new"} ) - xml_dom = get_server_dom( data , "http://openrpg.sf.net/openrpg_servers.php") + #xml_dom = get_server_dom( data , "http://openrpg.sf.net/openrpg_servers.php")#Sourceforge still? + path = component.get('settings').get_setting('MetaServerBaseURL') #getMetaServerBaseURL() + xml_dom = get_server_dom(data, path) ret_val = int( xml_dom.getAttribute( "id" ) ) return ret_val @@ -109,10 +106,10 @@ # For now, turning this off. This needs to be re-vamped for # handling multiple Metas. return 0 -# data = urllib.urlencode({"id":id,"act":"failed"}); -# xml_dom = get_server_dom(data) -# ret_val = int(xml_dom.getAttribute("return")) -# return ret_val + #data = urllib.urlencode({"id":id,"act":"failed"}); + #xml_dom = get_server_dom(data) + #ret_val = int(xml_dom.getAttribute("return")) + #return ret_val def remove_server(id): data = urllib.urlencode({"id":id,"act":"del"}); @@ -125,15 +122,11 @@ # This function is used to easily sort a list of nodes # by their start time - if first.hasAttribute("start"): - first_start = int(first.getAttribute("start")) - else: - first_start = 0 + if first.hasAttribute("start"): first_start = int(first.getAttribute("start")) + else: first_start = 0 - if second.hasAttribute("start"): - second_start = int(second.getAttribute("start")) - else: - second_start = 0 + if second.hasAttribute("start"): second_start = int(second.getAttribute("start")) + else: second_start = 0 # Return the result of the cmp function on the two strings return cmp(first_start,second_start) @@ -144,18 +137,13 @@ # Ensure there is something to sort with for each - if first.hasAttribute("name"): - first_name = str(first.getAttribute("name")).lower() - else: - first_name = "" + if first.hasAttribute("name"): first_name = str(first.getAttribute("name")).lower() + else: first_name = "" - if second.hasAttribute("name"): - second_name = str(second.getAttribute("name")).lower() - else: - second_name = "" + if second.hasAttribute("name"): second_name = str(second.getAttribute("name")).lower() + else: second_name = "" # Return the result of the cmp function on the two strings - return cmp(first_name,second_name) @@ -171,11 +159,10 @@ for meta in all_metas: # check all of the metas - # get the server's xml from the current meta + #get the server's xml from the current meta bad_meta = 0 #print "Getting server list from " + meta + "..." - try: - xml_dom = get_server_dom(data=data,path=meta) + try: xml_dom = get_server_dom(data=data,path=meta) except: #print "Trouble getting servers from " + meta + "..." bad_meta = 1 @@ -224,14 +211,11 @@ # sort them by their name attribute. Uses byNameAttribute() # defined above as a comparison function - if sort_by == "start": - return_list.sort(byStartAttribute) - elif sort_by == "name": - return_list.sort(byNameAttribute) + if sort_by == "start": return_list.sort(byStartAttribute) + elif sort_by == "name": return_list.sort(byNameAttribute) # Add each node to the DOM - for n in return_list: - return_dom.appendChild(n) + for n in return_list: return_dom.appendChild(n) return return_dom ## List Format: @@ -269,7 +253,7 @@ try: metacache_lock.acquire() # Read in the metas - component.get('validate').config_file("metaservers.cache","metaservers.cache") + validate.config_file("metaservers.cache","metaservers.cache") ini = open(dir_struct["user"]+"metaservers.cache","r") metas = ini.readlines() ini.close() @@ -282,23 +266,27 @@ return [] def getMetaServers(versions = None, pick_random=0): - # get meta server URLs as a list + """ + get meta server URLs as a list - # versions is a list of acceptable version numbers. - # A False truth value will use getMetaServerBaseURL() + versions is a list of acceptable version numbers. + A False truth value will use getMetaServerBaseURL() - # set a default if we have weird reading problems - # default_url = "http://www.openrpg.com/openrpg_servers.php" + set a default if we have weird reading problems + default_url = "http://www.openrpg.com/openrpg_servers.php" + """ meta_names = [] if(versions): # If versions are supplied, then look in metaservers.conf try: - # read in the metas from file - # format of file is one meta entry per line - # each entry will be the meta url, followed by one or more version numbers that it - # handle. Generally, this will be either a 1 for the original Meta format, or - # 2 for the new one. + """ + read in the metas from file + format of file is one meta entry per line + each entry will be the meta url, followed by one or more version numbers that it + handle. Generally, this will be either a 1 for the original Meta format, or + 2 for the new one. + """ # Read in the metas metas = getRawMetaList() @@ -311,13 +299,10 @@ # split the line on whitespace # obviously, your meta servers urls shouldn't contain whitespace. duh. words = meta.split() - success = 0 # init success flag for version check - for version in versions: # run through each allowed version from caller if version in words[1:]: # if the allowed version token was found success += 1 # then increment the success indicator - if success: # if the meta entry is acceptable to the caller meta_names.append(words[0]) # add the entry if META_DEBUG: print "adding metaserver " + meta @@ -326,8 +311,8 @@ if not meta_names: default_meta = getMetaServerBaseURL() # grab the meta from ini.xml meta_names.append(default_meta) # add it to the return list -# print "Warning!!\nNo valid metaservers cached." -# print "Using meta from MetaServerBaseURL: " + default_meta + "\n" + # print "Warning!!\nNo valid metaservers cached." + # print "Using meta from MetaServerBaseURL: " + default_meta + "\n" # if we have more than one and want a random one elif pick_random: if META_DEBUG: print "choosing random meta from: " + str(meta_names) @@ -364,47 +349,47 @@ url = node_list[0].getAttribute("value") # allow tree to be collected - try: - tree.unlink() - except: - pass + try: tree.unlink() + except: pass except Exception,e: print e -# print "using meta server URI: " + url + #print "using meta server URI: " + url return url -####################################################################################### -# Beginning of Class registerThread -# -# A Class to Manage Registration with the Meta2 -# Create an instance and call it's start() method -# if you want to be (and stay) registered. This class -# will take care of registering and re-registering as -# often as necessary to stay in the Meta list. -# -# You may call register() yourself if you wish to change your -# server's name. It will immediately update the Meta. There -# is no need to unregister first. -# -# Call unregister() when you no longer want to be registered. -# This will result in the registerThread dying after -# attempting to immediately remove itself from the Meta. -# -# If you need to become registered again after that, you -# must create a new instance of class registerThread. Don't -# just try to call register() on the old, dead thread class. +""" + Beginning of Class registerThread + + A Class to Manage Registration with the Meta2 + Create an instance and call it's start() method + if you want to be (and stay) registered. This class + will take care of registering and re-registering as + often as necessary to stay in the Meta list. + You may call register() yourself if you wish to change your + server's name. It will immediately update the Meta. There + is no need to unregister first. + + Call unregister() when you no longer want to be registered. + This will result in the registerThread dying after + attempting to immediately remove itself from the Meta. + + If you need to become registered again after that, you + must create a new instance of class registerThread. Don't + just try to call register() on the old, dead thread class. +""" class registerThread(Thread): -# Originally, I wrote this as a sub-class of wxThread, but -# A) I couldn't get it to import right -# B) I realized that I want this to be used in a server, -# which I don't want needing wxWindows to run! -# -# Because of this fact, there are some methods from wxThread -# that I implemented to minimize changes to the code I had -# just written, i.e. TestDeleteStatus() and Delete() + """ + Originally, I wrote this as a sub-class of wxThread, but + A) I couldn't get it to import right + B) I realized that I want this to be used in a server, + which I don't want needing wxWindows to run! + + Because of this fact, there are some methods from wxThread + that I implemented to minimize changes to the code I had + just written, i.e. TestDeleteStatus() and Delete() + """ def __init__(self,name=None,realHostName=None,num_users = "Hmmm",MetaPath=None,port=6774,register_callback=None): @@ -426,15 +411,17 @@ # re-register, in minutes. self.destroy = 0 # Used to flag that this thread should die self.port = str(port) - self.register_callback = register_callback # set a method to call to report result of register - # This thread will communicate with one and only one - # Meta. If the Meta in ini.xml is changed after - # instantiation, then this instance must be - # unregistered and a new instance instantiated. - # - # Also, if MetaPath is specified, then use that. Makes - # it easier to have multiple registerThreads going to keep the server registered - # on multiple (compatible) Metas. + self.register_callback = register_callback # set a method to call to report result of register + """ + This thread will communicate with one and only one + Meta. If the Meta in ini.xml is changed after + instantiation, then this instance must be + unregistered and a new instance instantiated. + + Also, if MetaPath is specified, then use that. Makes + it easier to have multiple registerThreads going to keep the server registered + on multiple (compatible) Metas. + """ if MetaPath == None: self.path = getMetaServerBaseURL() # Do this if no Meta specified @@ -459,18 +446,19 @@ self.rlock.release() def run(self): - # This method gets called by Thread implementation - # when self.start() is called to begin the thread's - # execution - # - # We will basically enter a loop that continually - # re-registers this server and sleeps Interval - # minutes until the thread is ordered to die in place + """ + This method gets called by Thread implementation + when self.start() is called to begin the thread's + execution + + We will basically enter a loop that continually + re-registers this server and sleeps Interval + minutes until the thread is ordered to die in place + """ while(not self.TestDeleteStatus()): # Loop while until told to die # Otherwise, call thread safe register(). self.register(self.name, self.realHostName, self.num_users) if META_DEBUG: print "Sent Registration Data" - # register() will end up setting the state variables # for us, including self.interval. try: @@ -493,19 +481,21 @@ # calls to Thread.isAlive() return False. def unregister(self): - # This method can (I hope) be called from both within the thread - # and from other threads. It will attempt to unregister this - # server from the Meta database - # When this is either accomplished or has been tried hard enough - # (after which it just makes sense to let the Meta remove the - # entry itself when we don't re-register using this id), - # this method will either cause the thread to immediately die - # (if called from this thread's context) or set the Destroy flag - # (if called from the main thread), a positive test for which will cause - # the code in Entry() to exit() when the thread wakes up and - # checks TestDeleteStatus(). - # lock the critical section. The unlock will - # automatically occur at the end of the function in the finally clause + """ + This method can (I hope) be called from both within the thread + and from other threads. It will attempt to unregister this + server from the Meta database + When this is either accomplished or has been tried hard enough + (after which it just makes sense to let the Meta remove the + entry itself when we don't re-register using this id), + this method will either cause the thread to immediately die + (if called from this thread's context) or set the Destroy flag + (if called from the main thread), a positive test for which will cause + the code in Entry() to exit() when the thread wakes up and + checks TestDeleteStatus(). + lock the critical section. The unlock will + automatically occur at the end of the function in the finally clause + """ try: self.rlock.acquire() if not self.isAlive(): # check to see if this thread is dead @@ -528,35 +518,31 @@ # way, we can't do anything else, so die. self.Delete() # This will cause the registerThread to die in register() # prep xml_dom for garbage collection - try: - xml_dom.unlink() - except: - pass + try: xml_dom.unlink() + except: pass return 0 - finally: - self.rlock.release() + finally: self.rlock.release() def register(self, name=None, realHostName=None, num_users=None): - # Designed to handle the registration, both new and - # repeated. - # - # It is intended to be called once every interval - # (or interval - delta) minutes. + """ + Designed to handle the registration, both new and + repeated. + + It is intended to be called once every interval + (or interval - delta) minutes. - # lock the critical section. The unlock will - # automatically occur at the end of the function in the finally clause + lock the critical section. The unlock will + automatically occur at the end of the function in the finally clause + """ try: self.rlock.acquire() if not self.isAlive(): # check to see if this thread is dead return 1 # If so, return an error result # Set the server's attibutes, if specified. - if name: - self.name = name - if num_users != None: - self.num_users = num_users - if realHostName: - self.realHostName = realHostName + if name: self.name = name + if num_users != None: self.num_users = num_users + if realHostName: self.realHostName = realHostName # build POST data if self.realHostName: data = urllib.urlencode( {"server_data[id]":self.id, @@ -583,17 +569,20 @@ if META_DEBUG: print data if META_DEBUG: print self.interval = 0 - # If we are in the registerThread thread, then setting interval to 0 - # will end up causing a retry in about 6 seconds (see self.run()) - # If we are in the main thread, then setting interval to 0 will do one - # of two things: - # 1) Do the same as if we were in the registerThread - # 2) Cause the next, normally scheduled register() call to use the values - # provided in this call. - # - # Which case occurs depends on where the registerThread thread is when - # the main thread calls register(). + """ + If we are in the registerThread thread, then setting interval to 0 + will end up causing a retry in about 6 seconds (see self.run()) + If we are in the main thread, then setting interval to 0 will do one + of two things: + 1) Do the same as if we were in the registerThread + 2) Cause the next, normally scheduled register() call to use the values + provided in this call. + + Which case occurs depends on where the registerThread thread is when + the main thread calls register(). + """ return 0 # indicates that it was okay to call, not that no errors occurred + # If there is a DOM returned .... if xml_dom: # If there's an error, echo it to the console @@ -601,22 +590,24 @@ print "Error durring registration: " + xml_dom.getAttribute("errmsg") if META_DEBUG: print data if META_DEBUG: print - # No special handling is required. If the registration worked, id, cookie, and interval - # can be stored and used for the next time. - # If an error occurred, then the Meta will delete us and we need to re-register as - # a new server. The way to indicate this is with a "0" id and "0" cookie sent to - # the server during the next registration. Since that's what the server returns to - # us on an error anyway, we just store them and the next registration will - # automatically be set up as a new one. - # - # Unless the server calls register() itself in the meantime. Of course, that's okay - # too, because a success on THAT register() call will set up the next one to use - # the issued id and cookie. - # - # The interval is stored unconditionally for similar reasons. If there's an error, - # the interval will be less than 1, and the main thread's while loop will reset it - # to 6 seconds for the next retry. - # Is it wrong to have a method where there's more comments than code? :) + """ + No special handling is required. If the registration worked, id, cookie, and interval + can be stored and used for the next time. + If an error occurred, then the Meta will delete us and we need to re-register as + a new server. The way to indicate this is with a "0" id and "0" cookie sent to + the server during the next registration. Since that's what the server returns to + us on an error anyway, we just store them and the next registration will + automatically be set up as a new one. + + Unless the server calls register() itself in the meantime. Of course, that's okay + too, because a success on THAT register() call will set up the next one to use + the issued id and cookie. + + The interval is stored unconditionally for similar reasons. If there's an error, + the interval will be less than 1, and the main thread's while loop will reset it + to 6 seconds for the next retry. + Is it wrong to have a method where there's more comments than code? :) + """ try: self.interval = int(xml_dom.getAttribute("interval")) self.id = xml_dom.getAttribute("id")
--- a/orpg/networking/mplay_client.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/networking/mplay_client.py Thu Aug 20 03:00:39 2009 -0500 @@ -42,7 +42,8 @@ import errno import os import time -from orpg.orpgCore import * +from orpg.orpgCore import component +from orpg.orpg_xml import xml try: import bz2 @@ -82,7 +83,7 @@ def parseXml(data): "parse and return doc" #print data - doc = component.get('xml').parseXml(data) + doc = xml.parseXml(data) doc.normalize() return doc @@ -116,9 +117,11 @@ self.group_id = "0" self.name = "" self.role = "GM" + ## Soon to be removed self.ROLE_GM = "GM" self.ROLE_PLAYER = "Player" self.ROLE_LURKER = "Lurker" + ## --TaS self.ip = socket.gethostbyname(socket.gethostname()) self.remote_ip = None self.version = VERSION @@ -143,8 +146,7 @@ # Loop as long as we have a connection while( self.get_status() == MPLAY_CONNECTED ): - try: - readMsg = self.outbox.get( block=1 ) + try: readMsg = self.outbox.get( block=1 ) except Exception, text: self.log_msg( ("outbox.get() got an exception: ", text) ) @@ -217,12 +219,9 @@ # Now, send the message the the length was describing sentm = sock.send( msg ) - if self.isServer(): - self.log_msg(("data_sent", sentl+sentm)) - except socket.error, e: - self.log_msg( e ) - except Exception, e: - self.log_msg( e ) + if self.isServer(): self.log_msg(("data_sent", sentl+sentm)) + except socket.error, e: self.log_msg( e ) + except Exception, e: self.log_msg( e ) return sentm def recvData( self, sock, readSize ): @@ -270,10 +269,8 @@ # Make the peer IP address available for reference later if self.remote_ip is None: self.remote_ip = self.sock.getpeername() - except IOError, e: - self.log_msg( e ) - except Exception, e: - self.log_msg( e ) + except IOError, e: self.log_msg( e ) + except Exception, e: self.log_msg( e ) return msgData def initialize_threads(self): @@ -289,8 +286,7 @@ self.set_status(MPLAY_DISCONNECTING) self.log_msg("client stub " + self.ip +" disconnecting...") self.log_msg("closing sockets...") - try: - self.sock.shutdown( 2 ) + try: self.sock.shutdown( 2 ) except Exception, e: print "Caught exception: " + str(e) print @@ -312,8 +308,9 @@ else: return 0 def update_self_from_player(self, player): - try: - (self.name, self.ip, self.id, self.text_status, self.version, self.protocol_version, self.client_string,role) = player + try: (self.name, self.ip, self.id, + self.text_status, self.version, + self.protocol_version, self.client_string, role) = player except Exception, e: print e """ @@ -340,8 +337,6 @@ def log_msg(self,msg): if self.log_console: self.log_console(msg) -# else: -# print "message", msg def get_status(self): self.statLock.acquire() @@ -500,15 +495,17 @@ players = self.get_players() if self.players.has_key(player): for m in players: - if player == m[2]: - return m + if player == m[2]: return m return -1 def get_id(self): return self.id def get_my_info(self): - return (self.name, self.ip, self.id, self.text_status, self.version, self.protocol_version, self.client_string, self.role) + return (self.name, self.ip, self.id, + self.text_status, self.version, + self.protocol_version, self.client_string, + self.role) def is_valid_id(self,id): self.statLock.acquire() @@ -519,25 +516,21 @@ def clear_players(self,save_self=0): self.statLock.acquire() keys = self.players.keys() - for k in keys: - del self.players[k] + for k in keys: del self.players[k] self.statLock.release() def clear_groups(self): self.statLock.acquire() keys = self.groups.keys() - for k in keys: - del self.groups[k] + for k in keys: del self.groups[k] self.statLock.release() def find_role(self,id): return self.players[id].role def get_ignore_list(self): - try: - return (self.ignore_id, self.ignore_name) - except: - return (None, None) + try: return (self.ignore_id, self.ignore_name) + except: return (None, None) def toggle_ignore(self, id): for m in self.ignore_id: @@ -560,7 +553,10 @@ #--------------------------------------------------------- def set_room_pass(self,npwd,pwd=""): - self.outbox.put("<alter key=\"pwd\" val=\"" +npwd+ "\" bpw=\"" + pwd + "\" plr=\"" + self.id +"\" gid=\"" + self.group_id + "\" />") + recycle_bin = "<alter key=\"pwd\" " + recycle_bin += "val=\"" +npwd+ "\" bpw=\"" + pwd + "\" " + recycle_bin += "plr=\"" + self.id +"\" gid=\"" + self.group_id + "\" />" + self.outbox.put(recycle_bin); del recycle_bin #makes line easier to read. --TaS self.update() def set_room_name(self,name,pwd=""): @@ -591,7 +587,10 @@ e = name[loc+1:] name = b + "'" + e oldloc = loc+1 - self.outbox.put("<alter key=\"name\" val=\"" + name + "\" bpw=\"" + pwd + "\" plr=\"" + self.id +"\" gid=\"" + self.group_id + "\" />") + recycle_bin = "<alter key=\"name\" " + recycle_bin += "val=\"" + name + "\" bpw=\"" + pwd + "\" " + recycle_bin += "plr=\"" + self.id +"\" gid=\"" + self.group_id + "\" />" + self.outbox.put(recycle_bin); del recycle_bin #makes line easier to read. --TaS self.update() #--------------------------------------------------------- @@ -605,7 +604,9 @@ self.outbox.put("<role action=\"get\" player=\"" + self.id +"\" group_id=\""+self.group_id + "\" />") def set_role(self,player,role,pwd=""): - self.outbox.put("<role action=\"set\" player=\"" + player + "\" role=\"" +role+ "\" boot_pwd=\"" + pwd + "\" group_id=\"" + self.group_id + "\" />") + recycle_bin = "<role action=\"set\" player=\"" + player + "\" " + recycle_bin += "role=\"" +role+ "\" boot_pwd=\"" + pwd + "\" group_id=\"" + self.group_id + "\" />" + self.outbox.put(recycle_bin); del recycle_bin #makes line easer to read. --TaS self.update() def send(self,msg,player="all"): @@ -619,12 +620,13 @@ self.check_my_status() def send_create_group(self,name,pwd,boot_pwd,minversion): - self.outbox.put("<create_group from=\""+self.id+"\" pwd=\""+pwd+"\" name=\""+ - name+"\" boot_pwd=\""+boot_pwd+"\" min_version=\"" + minversion +"\" />") + recycle_bin = "<create_group from=\""+self.id+"\" " + recycle_bin += "pwd=\""+pwd+"\" name=\""+ name+"\" boot_pwd=\""+boot_pwd+"\" " + recycle_bin += "min_version=\"" + minversion +"\" />" + self.outbox.put(recycle_bin); del recycle_bin #makes line easier to read. --TaS def send_join_group(self,group_id,pwd): - if (group_id != 0): - self.update_role("Lurker") + if (group_id != 0): self.update_role("Lurker") self.outbox.put("<join_group from=\""+self.id+"\" pwd=\""+pwd+"\" group_id=\""+str(group_id)+"\" />") def poll(self, evt=None): @@ -634,8 +636,7 @@ if self.get_status() != MPLAY_CONNECTED: self.check_my_status() else: - try: - self.pretranslate(msg) + try: self.pretranslate(msg) except Exception, e: print "The following message: " + str(msg) print "created the following exception: " @@ -644,16 +645,13 @@ def add_msg_handler(self, tag, function, core=False): if not self.msg_handlers.has_key(tag): self.msg_handlers[tag] = function - if core: - self.core_msg_handlers.append(tag) - else: - print 'XML Messages ' + tag + ' already has a handler' + if core: self.core_msg_handlers.append(tag) + else: print 'XML Messages ' + tag + ' already has a handler' def remove_msg_handler(self, tag): if self.msg_handlers.has_key(tag) and not tag in self.core_msg_handlers: del self.msg_handlers[tag] - else: - print 'XML Messages ' + tag + ' already deleted' + else: print 'XML Messages ' + tag + ' already deleted' def load_core_msg_handlers(self): self.add_msg_handler('msg', self.on_msg, True) @@ -667,8 +665,7 @@ def pretranslate(self,data): # Pre-qualify our data. If we don't have atleast 5-bytes, then there is # no way we even have a valid message! - if len(data) < 5: - return + if len(data) < 5: return end = data.find(">") head = data[:end+1] msg = data[end+1:] @@ -676,10 +673,8 @@ xml_dom = xml_dom._get_documentElement() tag_name = xml_dom._get_tagName() id = xml_dom.getAttribute("from") - if id == '': - id = xml_dom.getAttribute("id") - if self.msg_handlers.has_key(tag_name): - self.msg_handlers[tag_name](id, data, xml_dom) + if id == '': id = xml_dom.getAttribute("id") + if self.msg_handlers.has_key(tag_name): self.msg_handlers[tag_name](id, data, xml_dom) else: #Unknown messages recived ignoring #using pass insted or printing an error message @@ -687,8 +682,7 @@ #if someone is using a plugin to send messages and this user does not #have the plugin they would be getting errors pass - if xml_dom: - xml_dom.unlink() + if xml_dom: xml_dom.unlink() def on_sound(self, id, data, xml_dom): (ignore_id,ignore_name) = self.get_ignore_list() @@ -710,10 +704,8 @@ self.on_receive(msg,None) # None get's interpreted in on_receive as the sys admin. # Doing it this way makes it harder to impersonate the admin else: - if self.is_valid_id(id): - self.on_receive(msg,self.players[id]) - if xml_dom: - xml_dom.unlink() + if self.is_valid_id(id): self.on_receive(msg,self.players[id]) + if xml_dom: xml_dom.unlink() def on_ping(self, id, msg, xml_dom): #a REAL ping time implementation by Snowdog 8/03 @@ -728,8 +720,7 @@ latency = float( latency) / 10.0 ping_msg = "Ping Results: " + str(latency) + " ms (parsed message, round trip)" self.on_receive(ping_msg,None) - if xml_dom: - xml_dom.unlink() + if xml_dom: xml_dom.unlink() def on_group(self, id, msg, xml_dom): name = xml_dom.getAttribute("name") @@ -747,8 +738,7 @@ elif act == 'update': self.groups[id] = group_data self.on_group_event(mplay_event(GROUP_UPDATE, group_data)) - if xml_dom: - xml_dom.unlink() + if xml_dom: xml_dom.unlink() def on_role(self, id, msg, xml_dom): act = xml_dom.getAttribute("action") @@ -759,13 +749,10 @@ if id == self.id: self.players[id] = (a,b,c,d,e,f,g,role) self.update_role(role) - else: - self.players[id] = (a,b,c,d,e,f,g,role) + else: self.players[id] = (a,b,c,d,e,f,g,role) self.on_player_event(mplay_event(PLAYER_UPDATE,self.players[id])) - except: - pass - if xml_dom: - xml_dom.unlink() + except: pass + if xml_dom: xml_dom.unlink() def on_player(self, id, msg, xml_dom): act = xml_dom.getAttribute("action") @@ -775,42 +762,39 @@ version = xml_dom.getAttribute("version") protocol_version = xml_dom.getAttribute("protocol_version") client_string = xml_dom.getAttribute("client_string") - try: - player = (name,ip,id,status,version,protocol_version,client_string,self.players[id][7]) + try: player = (name, ip, id, status, + version, protocol_version, + client_string, self.players[id][7]) except Exception, e: - player = (name,ip,id,status,version,protocol_version,client_string,"Player") + player = (name, ip, id, status, + version, protocol_version, + client_string, "Player") if act == "new": self.players[id] = player - self.on_player_event(mplay_event(PLAYER_NEW,self.players[id])) + self.on_player_event(mplay_event(PLAYER_NEW, self.players[id])) elif act == "group": self.group_id = xml_dom.getAttribute("group_id") self.clear_players() - self.on_mplay_event(mplay_event(MPLAY_GROUP_CHANGE,self.groups[self.group_id])) + self.on_mplay_event(mplay_event(MPLAY_GROUP_CHANGE, self.groups[self.group_id])) self.players[self.id] = self.get_my_info() #(self.name,self.ip,self.id,self.text_status) - self.on_player_event(mplay_event(PLAYER_NEW,self.players[self.id])) + self.on_player_event(mplay_event(PLAYER_NEW, self.players[self.id])) elif act == "failed": self.on_mplay_event(mplay_event(MPLAY_GROUP_CHANGE_F)) elif act == "del": self.on_player_event(mplay_event(PLAYER_DEL,self.players[id])) - if self.players.has_key(id): - del self.players[id] - if id == self.id: - self.do_disconnect() + if self.players.has_key(id): del self.players[id] + if id == self.id: self.do_disconnect() # the next two cases handle the events that are used to let you know when others are typing elif act == "update": if id == self.id: self.players[id] = player self.update_self_from_player(player) - else: - self.players[id] = player + else: self.players[id] = player dont_send = 0 for m in self.ignore_id: - if m == id: - dont_send=1 - if dont_send != 1: - self.on_player_event(mplay_event(PLAYER_UPDATE,self.players[id])) - if xml_dom: - xml_dom.unlink() + if m == id: dont_send=1 + if dont_send != 1: self.on_player_event(mplay_event(PLAYER_UPDATE,self.players[id])) + if xml_dom: xml_dom.unlink() def on_password(self, id, msg, xml_dom): signal = type = id = data = None @@ -824,8 +808,7 @@ def check_my_status(self): status = self.get_status() - if status == MPLAY_DISCONNECTING: - self.do_disconnect() + if status == MPLAY_DISCONNECTING: self.do_disconnect() def connect(self, addressport): """Establish a connection to a server while still using sendThread & recvThread for its @@ -862,31 +845,29 @@ self.compressionType = bz2 elif cmpZLIB and xml_dom.getAttribute('cmpType') == 'zlib': self.compressionType = zlib - else: - self.compressionType = None - else: - self.compressionType = bz2 + else: self.compressionType = None + else: self.compressionType = bz2 #send confirmation self.sendMsg( self.sock, self.toxml("new") ) except Exception, e: self.log_msg(e) - if xml_dom: - xml_dom.unlink() + if xml_dom: xml_dom.unlink() return 0 # Start things rollings along self.initialize_threads() self.on_mplay_event(mplay_event(MPLAY_CONNECTED)) - self.players[self.id] = (self.name,self.ip,self.id,self.text_status,self.version,self.protocol_version,self.client_string,self.role) + self.players[self.id] = (self.name, self.ip, self.id, + self.text_status, self.version, + self.protocol_version, self.client_string, self.role) self.on_player_event(mplay_event(PLAYER_NEW,self.players[self.id])) - if xml_dom: - xml_dom.unlink() + if xml_dom: xml_dom.unlink() return 1 def start_disconnect(self): self.on_mplay_event(mplay_event(MPLAY_DISCONNECTING)) self.outbox.put( self.toxml("del") ) - ## Client Side Disconect Forced -- Snowdog 10-09-2003 + ## Client Side Disconect Forced -- Snowdog 10-09-2003 #pause to allow GUI events time to sync. time.sleep(1) self.do_disconnect() @@ -906,4 +887,3 @@ self.unique_cookie += 1 return_str = self.id + "-" + str(self.unique_cookie) return return_str -
--- a/orpg/networking/mplay_groups.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/networking/mplay_groups.py Thu Aug 20 03:00:39 2009 -0500 @@ -1,7 +1,9 @@ from orpg.mapper.map_msg import * class game_group: - def __init__( self, id, name, pwd, desc="", boot_pwd="", minVersion="", mapFile=None, messageFile=None, persist =0 ): + def __init__( self, id, name, pwd, desc="", + boot_pwd="", minVersion="", + mapFile=None, messageFile=None, persist=0 ): self.id = id self.name = name self.desc = desc @@ -33,8 +35,7 @@ self.players.append(id) def remove_player(self,id): - if self.voice.has_key(id): - del self.voice[id] + if self.voice.has_key(id): del self.voice[id] self.players.remove(id) def get_num_players(self): @@ -45,7 +46,6 @@ tmp = self.players return tmp - def check_pwd(self,pwd): return (pwd==self.pwd) @@ -61,13 +61,10 @@ w=max(len(minVersion[i]),len(version[i])) v1=minVersion[i].rjust(w); v2=version[i].rjust(w); - if v1<v2: - return 1 - if v1>v2: - return 0 + if v1<v2: return 1 + if v1>v2: return 0 - if len(minVersion)>len(version): - return 0 + if len(minVersion)>len(version): return 0 return 1 #depreciated - see send_group_list()
--- a/orpg/networking/mplay_messaging.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/networking/mplay_messaging.py Thu Aug 20 03:00:39 2009 -0500 @@ -36,22 +36,22 @@ from xml.sax.saxutils import escape from struct import pack, unpack, calcsize from string import * -from orpg.orpg_version import * +from orpg.orpg_version import VERSION, PROTOCOL_VERSION, CLIENT_STRING, SERVER_MIN_CLIENT_VERSION import os import time -from orpg.orpgCore import * +from orpg.tools.orpg_log import logger +from orpg.orpgCore import component def myescape(data): return escape(data,{"\"":""}) class messenger: def __init__(self, *args, **kwargs): - self.log = component.get("log") - self.xml = component.get("xml") - self.dir_struct = component.get("dir_struct") - self.validate = component.get("validate") - self.settings = component.get("settings") + #self.xml = component.get("xml") used once, no need for the object. + self.dir_struct = component.get("dir_struct") #used? + self.validate = component.get("validate") #used?? + #self.settings = component.get("settings") ## used once, no need for the object. if kwargs.has_key('isServer'): self.isServer = kwargs['isServer'] else: @@ -64,7 +64,7 @@ self.exitEvent = Event() self.sendThreadExitEvent = Event() self.recvThreadExitEvent = Event() - self.port = int(self.settings.get_setting("port")) + self.port = int(component.get("settings").get_setting("port")) ##used even? self.ip = socket.gethostbyname(socket.gethostname()) self.lensize = calcsize('i') self.mplay_type = ('disconnected', 'connected', 'disconnecting', 'group change', 'group change failed') @@ -137,12 +137,12 @@ def disconnect(self): self.set_status(2) - self.log.log("client stub " + self.ip +" disconnecting...", ORPG_DEBUG) - self.log.log("closing sockets...", ORPG_DEBUG) + logger.debug("client stub " + self.ip +" disconnecting...") + logger.debug("closing sockets...") try: self.sock.shutdown( 2 ) except: - self.log.log("Caught exception:\n" + traceback.format_exc(), ORPG_GENERAL) + logger.general("Caught exception:\n" + traceback.format_exc()) self.set_status(0) def reset(self, sock): @@ -161,10 +161,10 @@ try: (self.name, self.ip, self.id, self.text_status, self.version, self.protocol_version, self.client_string,role) = player except: - self.log.log("Exception: messenger->update_self_from_player():\n" + traceback.format_exc(), ORPG_GENERAL) + logger.general("Exception: messenger->update_self_from_player():\n" + traceback.format_exc()) def toxml(self, act): - self.log.log("DEPRECIATED! messenger->toxml()", ORPG_CRITICAL) + logger.exception("DEPRECIATED! messenger->toxml()") xml_data = self.build_message('player', name=myescape(self.name), action=act, @@ -290,7 +290,7 @@ #Message Handaling def message_handler(self, arg): xml_dom = None - self.log.log("message handler thread running...", ORPG_NOTE) + logger.note("message handler thread running...", ORPG_NOTE) while self.alive or self.status == 'connected': data = None try: @@ -308,24 +308,24 @@ del data data = None except Exception, e: - self.log.log(traceback.format_exc(), ORPG_GENERAL) + logger.general(traceback.format_exc()) if xml_dom: xml_dom.unlink() if xml_dom: xml_dom.unlink() - self.log.log("message handler thread exiting...", ORPG_NOTE) + logger.note("message handler thread exiting...") self.inbox_event.set() def parse_incoming_dom(self, data): #print data xml_dom = None try: - xml_dom = self.xml.parseXml(data) + xml_dom = component.get("xml").parseXml(data) xml_dom = xml_dom._get_documentElement() self.message_action(xml_dom, data) except Exception, e: - self.log.log("Error in parse of inbound message. Ignoring message.", ORPG_GENERAL) - self.log.log("\tOffending data(" + str(len(data)) + "bytes)=" + data, ORPG_GENERAL) - self.log.log("Exception=" + traceback.format_exc(), ORPG_GENERAL) + logger.general("Error in parse of inbound message. Ignoring message.") + logger.general("\tOffending data(" + str(len(data)) + "bytes)=" + data) + logger.general("Exception=" + traceback.format_exc()) if xml_dom: xml_dom.unlink() def message_action(self, xml_dom, data): @@ -333,8 +333,8 @@ if self.msg_handlers.has_key(tag_name): self.msg_handlers[tag_name](xml_dom, data) else: - self.log.log("Unknown Message Type", ORPG_GENERAL) - self.log.log(data, ORPG_GENERAL) + logger.general("Unknown Message Type") + logger.general(data) #Message Action thread expires and closes here. return @@ -350,7 +350,7 @@ readMsg = self.outbox.get( block=1 ) except Exception, text: - self.log.log("Exception: messenger->sendThread(): " + str(text), ORPG_CRITICAL) + logger.exception("Exception: messenger->sendThread(): " + str(text) # If we are here, it's because we have data to send, no doubt! if self.status == 'connected': @@ -358,12 +358,12 @@ # Send the entire message, properly formated/encoded sent = self.sendMsg( self.sock, readMsg ) except: - self.log.log("Exception: messenger->sendThread():\n" + traceback.format_exc(), ORPG_CRITICAL) + logger.exception("Exception: messenger->sendThread():\n" + traceback.format_exc() else: # If we are not connected, purge the data queue - self.log.log("Data queued without a connection, purging data from queue...", ORPG_NOTE) + logger.note("Data queued without a connection, purging data from queue...") self.sendThreadExitEvent.set() - self.log.log( "sendThread has terminated...", ORPG_NOTE) + logger.note( "sendThread has terminated...") def sendMsg( self, sock, msg ): """Very simple function that will properly encode and send a message to te @@ -382,12 +382,12 @@ # Now, send the message the the length was describing sentm = sock.send( msg ) if self.isServer: - self.log.log("('data_sent', " + str(sentl+sentm) + ")", ORPG_DEBUG) + logger.debug("('data_sent', " + str(sentl+sentm) + ")") return sentm except socket.error, e: - self.log.log("Socket Error: messenger->sendMsg(): " + traceback.format_exc(), ORPG_CRITICAL) + logger.exception("Socket Error: messenger->sendMsg(): " + traceback.format_exc()) except: - self.log.log("Exception: messenger->sendMsg(): " + traceback.format_exc(), ORPG_CRITICAL) + logger.exception("Exception: messenger->sendMsg(): " + traceback.format_exc()) def recvThread( self, arg ): "Receiving thread. This thread reads from the socket and writes to the data queue." @@ -413,11 +413,11 @@ self.inbox.put( readMsg ) self.update_idle_time() #update the last message time if bytes == 0: - self.log.log("Remote has disconnected!", ORPG_NOTE) + logger.note("Remote has disconnected!") self.set_status(2) self.outbox.put( "" ) # Make sure the other thread is woken up! self.sendThreadExitEvent.set() - self.log.log("messenger->recvThread() has terminated...", ORPG_NOTE) + logger.note("messenger->recvThread() has terminated...") def recvData( self, sock, readSize ): """Simple socket receive method. This method will only return when the exact @@ -439,7 +439,7 @@ offset += rs data += frag except socket.error, e: - self.log.log("Socket Error: messenger->recvData(): " + str(e), ORPG_CRITICAL) + logger.exception("Socket Error: messenger->recvData(): " + str(e)) data = "" return data @@ -465,9 +465,9 @@ msgData = self.recvData( sock, length ) if self.isServer: - self.log.log("('data_recv', " + str(length+4) + ")", ORPG_DEBUG) + logger.debug("('data_recv', " + str(length+4) + ")") except: - self.log.log("Exception: messenger->recvMsg():\n" + traceback.format_exc(), ORPG_CRITICAL) + logger.exception("Exception: messenger->recvMsg():\n" + traceback.format_exc()) return msgData if __name__ == "__main__":
--- a/orpg/networking/mplay_server.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/networking/mplay_server.py Thu Aug 20 03:00:39 2009 -0500 @@ -43,28 +43,30 @@ <role action='set,get,display' player='' group_id='' boot_pwd='' role=''/> """ -from mplay_client import * -from mplay_client import MPLAY_LENSIZE -from orpg.dirpath import dir_struct -import orpg.tools.validate +import re import gc import cgi import sys import string import time import urllib +import traceback + +from mplay_client import * +from mplay_client import MPLAY_LENSIZE +from orpg.dirpath import dir_struct +import orpg.tools.validate + from orpg.mapper.map_msg import * from threading import Lock, RLock from struct import pack, unpack, calcsize from meta_server_lib import * -import traceback -import re # Import the minidom XML module from xml.dom import minidom # Snag the version number -from orpg.orpg_version import * +from orpg.orpg_version import VERSION, PROTOCOL_VERSION, CLIENT_STRING, SERVER_MIN_CLIENT_VERSION #Plugins from server_plugins import ServerPlugins @@ -110,7 +112,6 @@ f.write(self.game_map.get_all_xml()) f.close() - def add_player(self,id): self.players.append(id) @@ -127,7 +128,6 @@ tmp = self.players return tmp - def check_pwd(self,pwd): return (pwd==self.pwd) @@ -135,19 +135,15 @@ return (pwd==self.boot_pwd) def check_version(self,ver): - if (self.minVersion == ""): - return 1 + if (self.minVersion == ""): return 1 minVersion=self.minVersion.split('.') version=ver.split('.') for i in xrange(min(len(minVersion),len(version))): w=max(len(minVersion[i]),len(version[i])) v1=minVersion[i].rjust(w); v2=version[i].rjust(w); - if v1<v2: - return 1 - if v1>v2: - return 0 - + if v1<v2: return 1 + if v1>v2: return 0 if len(minVersion)>len(version): return 0 return 1 @@ -163,7 +159,6 @@ return xml_data - class client_stub(client_base): def __init__(self,inbox,sock,props,log): client_base.__init__(self) @@ -189,14 +184,11 @@ self.timeout_time = None def check_time_out(self): - if self.timeout_time==None: - self.timeout_time = time.time() + if self.timeout_time==None: self.timeout_time = time.time() curtime = time.time() diff = curtime - self.timeout_time - if diff > 1800: - return 1 - else: - return 0 + if diff > 1800: return 1 + else: return 0 def send(self,msg,player,group): if self.get_status() == MPLAY_CONNECTED: @@ -219,7 +211,7 @@ self.name = xml_dom.getAttribute("name") self.text_status = xml_dom.getAttribute("status") - +""" ###################################################################### ###################################################################### ## @@ -229,6 +221,7 @@ ## ###################################################################### ###################################################################### +""" class mplay_server: def __init__(self, log_console=None, name=None): @@ -264,19 +257,19 @@ self.allowRemoteKill = False self.allowRemoteAdmin = True self.sendLobbySound = False - self.lobbySound = 'http://www.digitalxero.net/music/mus_tavern1.bmu' + self.lobbySound = 'http://www.digitalxero.net/music/mus_tavern1.bmu' ##used? def initServer(self, **kwargs): - for atter, value in kwargs.iteritems(): - setattr(self, atter, value) - self.validate = orpg.tools.validate.Validate(self.userPath) - self.validate.config_file( self.lobbyMapFile, "default_Lobby_map.xml" ) - self.validate.config_file( self.lobbyMessageFile, "default_LobbyMessage.html" ) + for atter, value in kwargs.iteritems(): setattr(self, atter, value) + validate.config_file( self.lobbyMapFile, "default_Lobby_map.xml" ) + validate.config_file( self.lobbyMessageFile, "default_LobbyMessage.html" ) self.server_start_time = time.time() # Since the server is just starting here, we read in the XML configuration # file. Notice the lobby is still created here by default. - self.groups = { '0': game_group('0','Lobby','','The game lobby', '', '', self.userPath + self.lobbyMapFile, self.userPath + self.lobbyMessageFile, 1)} + self.groups = { '0': game_group('0','Lobby','', + 'The game lobby', '', '', self.userPath + self.lobbyMapFile, + self.userPath + self.lobbyMessageFile, 1)} # Make sure the server's name gets set, in case we are being started from # elsewhere. Basically, if it's passed in, we'll over ride what we were # prompted for. This should never really happen at any rate. @@ -314,13 +307,12 @@ self.addsvrcmd('plugin', self.plugin_msg_handler) self.addsvrcmd('sound', self.sound_msg_handler) - # This method reads in the server's ban list added by Darren def initBanList( self ): self.log_msg("Processing Ban List File...") # make sure the server_ini.xml exists! - self.validate.config_file(self.banFile, "default_ban_list.xml" ) + validate.config_file(self.banFile, "default_ban_list.xml" ) # try to use it. try: @@ -361,7 +353,7 @@ def initServerConfig(self): self.log_msg("Processing Server Configuration File... " + self.userPath) # make sure the server_ini.xml exists! - self.validate.config_file( "server_ini.xml", "default_server_ini.xml" ) + validate.config_file( "server_ini.xml", "default_server_ini.xml" ) # try to use it. try: self.configDom = minidom.parse(self.userPath + 'server_ini.xml') @@ -383,6 +375,7 @@ if len(opt) and (opt[0].upper() == 'Y'): self.reg = 'Y' else: self.reg = 'N' LobbyName = 'Lobby' + if self.configDoc.hasAttribute("lobbyname"): LobbyName = self.configDoc.getAttribute("lobbyname") map_node = service_node = self.configDoc.getElementsByTagName("map")[0] msg_node = service_node = self.configDoc.getElementsByTagName("message")[0] @@ -391,6 +384,7 @@ if mapFile == '': mapFile = 'Lobby_map.xml' if msgFile == '': msgFile = 'LobbyMessage.html' # Update the lobby with the passwords if they've been specified + if len(self.boot_pwd): self.groups = {'0': game_group( '0', LobbyName, "", 'The game lobby', self.boot_pwd, "", self.userPath + mapFile.replace("myfiles/", ""), @@ -411,12 +405,14 @@ if self.reg[0].upper() == "Y": if self.name == None: self.name = raw_input("Server Name? ") self.register() - + """ # Get the minimum openrpg version from config if available # if it isn't set min version to internal default. # # server_ini.xml entry for version tag... # <version min="x.x.x"> + """ + try: mver = self.configDoc.getElementsByTagName("version")[0] self.minClientVersion = mver.getAttribute("min") @@ -425,13 +421,14 @@ # This try/except bit is to allow older versions of python to continue without a list error. - + """ #------------------------[ START <AUTOKICK> TAG PROCESSING ]-------------- # Auto-kick option defaults for silent booting and # setting the default zombie-client delay time --Snowdog 9/05 # # server_ini.xml entry for autikick tag... # <autokick silent=["no","yes"] delay="(# of seconds)"> + """ try: ak = self.configDoc.getElementsByTagName("autokick")[0] @@ -455,10 +452,10 @@ alk = "" if (self.silent_auto_kick == 1): alk = "(Silent Mode)" self.log_msg("Auto Kick: Delay="+str(self.zombie_time) + " " + alk) - #------------------------[ END <AUTOKICK> TAG PROCESSING ]-------------- + """------------------------[ END <AUTOKICK> TAG PROCESSING ]--------------""" - + """ #-------------------------------[ START <ROOM_DEFAULT> TAG PROCESSING ]-------------------- # # New room_defaults configuration option used to set various defaults @@ -467,6 +464,7 @@ # # option syntax # <room_defaults passwords="yes" map="myfiles/LobbyMap.xml" message="myfiles/LobbyMessage.html" /> + """ #default settings for tag options... roomdefault_msg = str(self.defaultMessageFile) #no message is the default @@ -493,8 +491,7 @@ if map != "": roomdefault_map = self.userPath + map.replace("myfiles/", "") self.log_msg("Room Defaults: Using " + str(map) + " for room map") - except: - self.log_msg("Room Defaults: [Warning] Using Default Map") + except: self.log_msg("Room Defaults: [Warning] Using Default Map") try: setting = roomdefaults.getElementsByTagName('message')[0] @@ -508,12 +505,10 @@ traceback.print_exc() self.log_msg("**WARNING** Error loading default room settings from configuration file. Using internal defaults.") - #set the defaults if roomdefault_msg != "" or roomdefault_msg != None: self.defaultMessageFile = roomdefault_msg #<room_defaults> tag superceeds older <newrooms> tag else: self.defaultMessageFile = None - if roomdefault_map != "" or roomdefault_map != None: self.defaultMapFile = roomdefault_map #<room_defaults> tag superceeds older <newrooms> tag else: self.defaultMapFile = None @@ -521,9 +516,7 @@ ##### room default map not handled yet. SETTING IGNORED if roomdefault_pass == 0: self.allow_room_passwords = 0 else: self.allow_room_passwords = 1 - - #-------------------------------[ END <ROOM_DEFAULT> TAG PROCESSING ]-------------------- - + """-------------------------------[ END <ROOM_DEFAULT> TAG PROCESSING ]--------------------""" ###Server Cheat message try: @@ -533,27 +526,19 @@ self.cheat_msg = "**FAKE ROLL**" self.log_msg("**WARNING** <cheat txt=\"\"> tag missing from server configuration file. Using empty string.") - - # should validate protocal validate_protocol_node = self.configDom.getElementsByTagName("validate_protocol ") - self.validate_protocol = 1 - if(validate_protocol_node): self.validate_protocol = (validate_protocol_node[0].getAttribute("value") == "True") if(self.validate_protocol != 1): self.log_msg("Protocol Validation: OFF") self.makePersistentRooms() - self.log_msg("Server Configuration File: Processing Completed.") - except Exception, e: traceback.print_exc() self.log_msg("Exception in initServerConfig() " + str(e)) - def makePersistentRooms(self): 'Creates rooms on the server as defined in the server config file.' - for element in self.configDom.getElementsByTagName('room'): roomName = element.getAttribute('name') roomPassword = element.getAttribute('password') @@ -567,31 +552,28 @@ # we only care about the first map element found -- others are ignored mapElement = element.getElementsByTagName('map')[0] mapFile = self.userPath + mapElement.getAttribute('file').replace("myfiles/", "") - messageElement = element.getElementsByTagName('message')[0] messageFile = messageElement.getAttribute('file') - if messageFile[:4] != 'http': messageFile = self.userPath + messageFile.replace("myfiles/", "") # Make sure we have a message to even mess with if(len(messageFile) == 0): messageFile = self.defaultMessageFile - if(len(mapFile) == 0): mapFile = self.defaultMapFile - moderated = 0 if element.hasAttribute('moderated') and element.getAttribute('moderated').lower() == "true": moderated = 1 #create the new persistant group - self.new_group(roomName, roomPassword, bootPassword, minVersion, mapFile, messageFile, persist = 1, moderated=moderated) - - + self.new_group(roomName, roomPassword, + bootPassword, minVersion, mapFile, + messageFile, persist = 1, moderated=moderated) def isPersistentRoom(self, id): 'Returns True if the id is a persistent room (other than the lobby), otherwise, False.' - + """ # altered persistance tracking from simple room id based to per-group setting # allows arbitrary rooms to be marked as persistant without needing the self.persistRoomThreshold # -- Snowdog 4/04 + """ try: id = str(id) #just in case someone sends an int instead of a str into the function if id not in self.groups: return 0 #invalid room, can't be persistant @@ -601,8 +583,6 @@ self.log_msg("Exception occured in isPersistentRoom(self,id)") return 0 - - #----------------------------------------------------- # Toggle Meta Logging -- Added by Snowdog 4/03 #----------------------------------------------------- @@ -633,15 +613,13 @@ for n in self.players: try: self.players[n].EnableMessageLogging = mode except: self.log_msg("Error changing Message Logging Mode for client #" + str(self.players[n].id)) + def NetworkLoggingStatus(self): if self.log_network_messages == 0: return "Network Traffic Log: Off" elif self.log_network_messages == 1: return "Network Traffic Log: Logging (composite file)" elif self.log_network_messages == 2: return "Network Traffic Log: Logging (inbound/outbound files)" else: self.log_msg("Network Traffic Log: [Unknown]") - - - def register_callback(instance, xml_dom = None,source=None): if xml_dom: # if we get something if source == getMetaServerBaseURL(): # if the source of this DOM is the authoritative meta @@ -655,17 +633,19 @@ if newlist != curlist: # If the two lists aren't identical # then something has changed. - instance.register() # Call self.register() + instance.register() # Call self.register() # which will force a re-read of the meta cache and # redo the registerThreads else: instance.register() - # Eventually, reset the MetaServerBaseURL here + # Eventually, reset the MetaServerBaseURL here + """ ## Added to help clean up parser errors in the XML on clients ## due to characters that break welformedness of the XML from ## the meta server. ## NOTE: this is a stopgap measure -SD + """ def clean_published_servername(self, name): #clean name of all apostrophes and quotes badchars = "\"\\`><" @@ -679,11 +659,8 @@ for rnum in self.groups.keys(): rooms += urllib.urlencode( {"room_data[rooms][" + str(rnum) + "][name]":self.groups[rnum].name, "room_data[rooms][" + str(rnum) + "][pwd]":str(self.groups[rnum].pwd != "")})+'&' - for pid in self.groups[rnum].players: rooms += urllib.urlencode( {"room_data[rooms][" + str(rnum) + "][players]["+str(pid)+"]":self.players[pid].name,})+'&' - - for meta in self.metas.keys(): while id == '0': id, cookie = self.metas[meta].getIdAndCookie() @@ -691,11 +668,9 @@ "act":'registerrooms'}) get_server_dom(data+'&'+rooms, self.metas[meta].path) - def register(self,name_given=None): if name_given == None: name = self.name else: self.name = name = name_given - name = self.clean_published_servername(name) # Set up the value for num_users @@ -708,14 +683,16 @@ self.log_msg("Found these valid metas:") for meta in metalist: self.log_msg("Meta:" + meta) + """ # Go through the list and see if there is already a running register # thread for the meta. # If so, call it's register() method # If not, start one, implicitly calling the new thread's register() method - # iterate through the currently running metas and prune any # not currently listed in the Meta Server list. + """ + if self.show_meta_messages != 0: self.log_msg( "Checking running register threads for outdated metas.") for meta in self.metas.keys(): if self.show_meta_messages != 0: self.log_msg("meta:" + meta + ": ") @@ -729,39 +706,43 @@ # Now call register() for alive metas or start one if we need one for meta in metalist: if self.metas.has_key(meta) and self.metas[meta] and self.metas[meta].isAlive(): - self.metas[meta].register(name=name, realHostName=self.server_address, num_users=num_players) + self.metas[meta].register(name=name, + realHostName=self.server_address, + num_users=num_players) else: - self.metas[meta] = registerThread(name=name, realHostName=self.server_address, num_users=num_players, MetaPath=meta, port=self.server_port,register_callback=self.register_callback) + self.metas[meta] = registerThread(name=name, realHostName=self.server_address, + num_users=num_players, MetaPath=meta, port=self.server_port, + register_callback=self.register_callback) self.metas[meta].start() #The register Rooms thread - self.be_registered = 1 thread.start_new_thread(self.registerRooms,(0,)) - - def unregister(self): + """ # loop through all existing meta entries # Don't rely on getMetaServers(), as a server may have been # removed since it was started. In that case, then the meta # would never get unregistered. # # Instead, loop through all existing meta threads and unregister them + """ for meta in self.metas.values(): if meta and meta.isAlive(): meta.unregister() self.be_registered = 0 + """ # This method runs as it's own thread and does the group_member_check every # sixty seconds. This should eliminate zombies that linger when no one is # around to spook them. GC: Frequency has been reduced as I question how valid # the implementation is as it will only catch a very small segment of lingering # connections. + """ def player_reaper_thread_func(self,arg): while self.alive: time.sleep(60) - self.p_lock.acquire() for group in self.groups.keys(): self.check_group_members(group) self.p_lock.release() @@ -771,7 +752,6 @@ while self.alive: self.p_lock.acquire() players = ServerPlugins.getPlayer() - for player in players: if player is not None: pass #Do something here so they can show up in the chat room for non web users' data = ServerPlugins.preParseOutgoing() @@ -779,28 +759,22 @@ try: xml_dom = parseXml(msg) xml_dom = xml_dom._get_documentElement() - if xml_dom.hasAttribute('from') and int(xml_dom.getAttribute('from')) > -1: xml_dom.setAttribute('from', '-1') - xml_dom.setAttribute('to', 'all') self.incoming_msg_handler(xml_dom, msg) xml_dom.unlink() except: pass - self.p_lock.release() time.sleep(0.250) - def sendMsg( self, sock, msg, useCompression=False, cmpType=None): """Very simple function that will properly encode and send a message to te remote on the specified socket.""" - if useCompression and cmpType != None: mpacket = cmpType.compress(msg) lpacket = pack('!i', len(mpacket)) sock.send(lpacket) - offset = 0 while offset < len(mpacket): slice = buffer(mpacket, offset, len(mpacket)-offset) @@ -821,7 +795,6 @@ """Simple socket receive method. This method will only return when the exact byte count has been read from the connection, if remote terminates our connection or we get some other socket exception.""" - data = "" offset = 0 try: @@ -834,7 +807,6 @@ else: # Continue to build complete message offset += rs data += frag - except socket.error, e: self.log_msg("Socket Error: recvData(): " + e ) data = "" @@ -853,18 +825,14 @@ msgData = "" try: lenData = self.recvData( sock, MPLAY_LENSIZE ) - # Now, convert to a usable form - (length,) = unpack('!i', lenData) - # Read exactly the remaining amount of data - msgData = self.recvData( sock, length ) + (length,) = unpack('!i', lenData) # Now, convert to a usable form + msgData = self.recvData( sock, length ) # Read exactly the remaining amount of data try: if useCompression and cmpType != None: msgData = cmpType.decompress(msgData) except: traceback.print_exc() - except Exception, e: self.log_msg( "Exception: recvMsg(): " + str(e) ) return msgData - def kill_server(self): self.alive = 0 self.log_msg("Server stopping...") @@ -872,10 +840,8 @@ for p in self.players.itervalues(): p.disconnect() self.incoming.put("<system/>") - for g in self.groups.itervalues(): g.save_map() - try: ip = socket.gethostbyname(socket.gethostname()) kill = socket.socket(socket.AF_INET, socket.SOCK_STREAM) @@ -892,15 +858,10 @@ self.incoming_event.wait(10) self.log_msg("Server stopped!") - - def log_msg(self,msg): if self.log_to_console: - if self.log_console: - self.log_console(msg) - else: - print str(msg) - + if self.log_console: self.log_console(msg) + else: print str(msg) def print_help(self): print @@ -937,11 +898,9 @@ print "'help' or '?' or 'h' - for this help message" print - def broadcast(self,msg): self.send_to_all("0","<msg to='all' from='0' group_id='1'><font color='#FF0000'>" + msg + "</font>") - def console_log(self): if self.log_to_console == 1: print "console logging now off" @@ -950,7 +909,6 @@ print "console logging now on" self.log_to_console = 1 - def groups_list(self): self.p_lock.acquire() try: @@ -958,26 +916,23 @@ for k in keys: pw = "-" pr = " -" - if self.groups[k].pwd != "": - pw = "P" - if self.isPersistentRoom( k ): - pr = " S" #using S for static (P for persistant conflicts with password) + if self.groups[k].pwd != "": pw = "P" + if self.isPersistentRoom( k ): pr = " S" #using S for static (P for persistant conflicts with password) print "Group: " + k + pr + pw + ' Name: ' + self.groups[k].name print - except Exception, e: self.log_msg(str(e)) - self.p_lock.release() -#---------------------------------------------------------------- -# Monitor Function -- Added by snowdog 2/05 -#---------------------------------------------------------------- + """ + #---------------------------------------------------------------- + # Monitor Function -- Added by snowdog 2/05 + #---------------------------------------------------------------- + """ def monitor(self, pid, mode=1 ): "allows monitoring of a specific user(s) network i/o" #if mode is not set to 1 then monitor adds toggles the state #of monitoring on the given user - if (mode == 1): for p in self.players: try: p.monitor("off") @@ -989,44 +944,29 @@ self.log_msg("Monitor: Invalid Player ID") traceback.print_exc() - def search(self,patern): keys = self.groups.keys() print "Search results:" for k in keys: ids = self.groups[k].get_player_ids() for id in ids: - if self.players[id].id.find(patern)>-1: - self.print_player_info(self.players[id]) - - elif self.players[id].name.find(patern)>-1: - self.print_player_info(self.players[id]) - - elif self.players[id].ip.find(patern)>-1: - self.print_player_info(self.players[id]) - - elif self.players[id].group_id.find(patern)>-1: - self.print_player_info(self.players[id]) - - elif self.players[id].role.find(patern)>-1: - self.print_player_info(self.players[id]) - - elif self.players[id].version.find(patern)>-1: - self.print_player_info(self.players[id]) - - elif self.players[id].protocol_version.find(patern)>-1: - self.print_player_info(self.players[id]) - - elif self.players[id].client_string.find(patern)>-1: - self.print_player_info(self.players[id]) - + if self.players[id].id.find(patern)>-1: self.print_player_info(self.players[id]) + elif self.players[id].name.find(patern)>-1: self.print_player_info(self.players[id]) + elif self.players[id].ip.find(patern)>-1: self.print_player_info(self.players[id]) + elif self.players[id].group_id.find(patern)>-1: self.print_player_info(self.players[id]) + elif self.players[id].role.find(patern)>-1: self.print_player_info(self.players[id]) + elif self.players[id].version.find(patern)>-1: self.print_player_info(self.players[id]) + elif self.players[id].protocol_version.find(patern)>-1: self.print_player_info(self.players[id]) + elif self.players[id].client_string.find(patern)>-1: self.print_player_info(self.players[id]) def print_player_info(self,player): - print player.id,player.name,player.ip,player.group_id, player.role,player.version,player.protocol_version,player.client_string + print player.id, player.name, player.ip, player.group_id, player.role, player.version, player.protocol_version, player.client_string + """ #---------------------------------------------------------------- # Uptime Function -- Added by snowdog 4/03 #---------------------------------------------------------------- + """ def uptime(self , mode = 0): "returns string containing how long server has been in operation" ut = time.time() - self.server_start_time @@ -1038,9 +978,11 @@ if mode == 0: print uts else: return uts + """ #----------------------------------------------------- # Toggle Room Password Allow -- Added by Snowdog 11/03 #----------------------------------------------------- + """ def RoomPasswords(self): if self.allow_room_passwords != 0: self.allow_room_passwords = 0 @@ -1049,7 +991,6 @@ self.allow_room_passwords = 1 return "Client Created Room Passwords: Allowed" - def group_dump(self,k): self.p_lock.acquire() try: @@ -1065,9 +1006,11 @@ self.log_msg(str(e)) self.p_lock.release() + """ #---------------------------------------------------------------- # Player List -- Added by snowdog 4/03 #---------------------------------------------------------------- + """ def player_list(self): "display a condensed list of players on the server" self.p_lock.acquire() @@ -1102,56 +1045,46 @@ keys = self.groups.keys() for k in keys: print "Group: %s %s (pass: \"%s\")" % (str(k),self.groups[k].name, self.groups[k].pwd) - ids = self.groups[k].get_player_ids() for id in ids: - if self.players.has_key(id): - print str(self.players[id]) + if self.players.has_key(id): print str(self.players[id]) else: self.groups[k].remove_player(id) print "Bad Player Ref (#" + id + ") in group" except Exception, e: self.log_msg(str(e)) - self.p_lock.release() - def update_request(self,newsock,xml_dom): # handle reconnects - self.log_msg( "update_request() has been called." ) # get player id id = xml_dom.getAttribute("id") group_id = xml_dom.getAttribute("group_id") - self.p_lock.acquire() if self.players.has_key(id): - self.sendMsg( newsock, self.players[id].toxml("update"), self.players[id].useCompression, self.players[id].compressionType ) + self.sendMsg(newsock, self.players[id].toxml("update"), + self.players[id].useCompression, + self.players[id].compressionType ) self.players[id].reset(newsock) self.players[id].clear_timeout() need_new = 0 - else: - need_new = 1 + else: need_new = 1 self.p_lock.release() - - if need_new: - self.new_request(newsock,xml_dom) + if need_new: self.new_request(newsock,xml_dom) else: msg = self.groups[group_id].game_map.get_all_xml() self.send(msg,id,group_id) - def new_request(self,newsock,xml_dom,LOBBY_ID='0'): #build client stub props = {} # Don't trust what the client tells us...trust what they connected as! props['ip'] = socket.gethostbyname( newsock.getpeername()[0] ) - try: - props['role'] = xml_dom.getAttribute("role") - except: - props['role'] = "GM" + try: props['role'] = xml_dom.getAttribute("role") + except: props['role'] = "GM" props['name'] = xml_dom.getAttribute("name") props['group_id'] = LOBBY_ID @@ -1159,28 +1092,21 @@ props['version'] = xml_dom.getAttribute("version") props['protocol_version'] = xml_dom.getAttribute("protocol_version") props['client_string'] = xml_dom.getAttribute("client_string") + self.next_player_id += 1 new_stub = client_stub(self.incoming,newsock,props,self.log_console) if xml_dom.hasAttribute('useCompression'): new_stub.useCompression = True - if xml_dom.hasAttribute('cmpType'): cmpType = xml_dom.getAttribute('cmpType') - if cmpBZ2 and cmpType == 'bz2': - new_stub.compressionType = bz2 - elif cmpZLIB and cmpType == 'zlib': - new_stub.compressionType = zlib - else: - new_stub.compressionType = None - else: - new_stub.compressionType = bz2 - - else: - new_stub.useCompression = False + if cmpBZ2 and cmpType == 'bz2': new_stub.compressionType = bz2 + elif cmpZLIB and cmpType == 'zlib': new_stub.compressionType = zlib + else: new_stub.compressionType = None + else: new_stub.compressionType = bz2 + else: new_stub.useCompression = False #update newly create client stub with network logging state new_stub.EnableMessageLogging = self.log_network_messages - self.sendMsg(newsock, new_stub.toxml("new"), False, None) # try to remove circular refs @@ -1206,13 +1132,10 @@ print "Error in parse found from " + str(remote_host) + ". Disconnected." print " Offending data(" + str(len(data)) + "bytes)=" + data print "Exception=" + str(e) - - if xml_dom: - xml_dom.unlink() + if xml_dom: xml_dom.unlink() return #start threads and store player - allowed = 1 version_string = "" @@ -1222,12 +1145,16 @@ if not self.checkClientVersion(props['version']): version_string = "Sorry, your client is out of date. <br />" - version_string += "This server requires your client be version " + self.minClientVersion + " or higher to connect.<br />" + version_string += "This server requires your client be version " + version_string += "" + self.minClientVersion + " or higher to connect.<br />" allowed = 0 if not allowed: - version_string += ' Please go to <a href="http://openrpg.digitalxero.net">http://openrpg.digitalxero.net</a> to find a compatible client.<br />' - version_string += "If you can't find a compatible client on the website, chances are that the server is running an unreleased development version for testing purposes.<br />" + version_string += " Please go to <a href='http://www.assembla.com/traipse'>" + version_string += "http://www.assembla.com/traipse</a> to find a compatible client.<br />" + version_string += "If you can't find a compatible client on the website, " + version_string += "chances are that the server is running an unreleased development " + version_string += "version for testing purposes.<br />" self.sendMsg( newsock, "<msg to='" + props['id'] + "' from='0' group_id='0' />" + version_string, new_stub.useCompression, new_stub.compressionType) # Give messages time to flow @@ -1244,7 +1171,6 @@ cmsg = "Banned Client: (" + str(props['id']) + ") " + str(props['name']) + " [" + str(props['ip']) + "]" self.log_msg(cmsg) allowed = 0 - self.sendMsg( newsock, "<msg to='" + props['id'] + "' from='0' group_id='0' />" + banmsg, new_stub.useCompression, new_stub.compressionType) # Give messages time to flow time.sleep(1) @@ -1253,6 +1179,7 @@ xml_dom.unlink() return None + """ #---- Connection order changed by Snowdog 1/05 #---- Attempt to register player and send group data #---- before displaying lobby message @@ -1264,6 +1191,7 @@ #---- to clients. Not sure why the group messages were being sent to the #---- incomming message queue, when they should be sent directly to user #---- Does not solve the black hole bug totally -SD + """ try: if xml_dom.getAttribute("id") == props['id']: @@ -1274,7 +1202,6 @@ self.send_group_list(props['id']) self.send_player_list(props['id'],LOBBY_ID) self.p_lock.release() - msg = self.groups[LOBBY_ID].game_map.get_all_xml() self.send(msg,props['id'],LOBBY_ID) self.send_to_group(props['id'],LOBBY_ID,self.players[props['id']].toxml('new')) @@ -1282,7 +1209,6 @@ # Re-initialize the role for this player incase they came from a different server self.handle_role("set",props['id'], "GM",self.groups[LOBBY_ID].boot_pwd, LOBBY_ID) - cmsg = "Client Connect: (" + str(props['id']) + ") " + str(props['name']) + " [" + str(props['ip']) + "]" self.log_msg(cmsg) cmsg = ("connect", props) ################################################# @@ -1305,14 +1231,11 @@ time.sleep(2) newsock.close() - # Display the lobby message self.SendLobbyMessage(newsock,props['id']) - if xml_dom: xml_dom.unlink() - def checkClientVersion(self, clientversion): minv = self.minClientVersion.split('.') cver = clientversion.split('.') @@ -1320,53 +1243,47 @@ w=max(len(minv[i]),len(cver[i])) v1=minv[i].rjust(w); v2=cver[i].rjust(w); - if v1<v2: - return 1 - if v1>v2: - return 0 - - if len(minv)>len(cver): - return 0 + if v1<v2: return 1 + if v1>v2: return 0 + if len(minv)>len(cver): return 0 return 1 - - def SendLobbyMessage(self, socket, player_id): - ####################################################################### + """ # Display the lobby message # prepend this server's version string to the the lobby message + """ try: - lobbyMsg = "You have connected to an <a href=\"http://www.openrpg.com\">OpenRPG</a> server, version '" + VERSION + "'" + lobbyMsg = "You have connected to an <a href=\"http://www.openrpg.com\">OpenRPG</a> " + lobbyMsg += "server, version '" + VERSION + "'" # See if we have a server name to report! - if len(self.serverName): lobbyMsg += ", named '" + self.serverName + "'." - else: lobbyMsg += "." # Add extra line spacing lobbyMsg += "\n\n" - try: - self.validate.config_file("LobbyMessage.html","default_LobbyMessage.html") - except: - pass + try: validate.config_file("LobbyMessage.html","default_LobbyMessage.html") + except: pass else: open_msg = open( self.userPath + "LobbyMessage.html", "r" ) lobbyMsg += open_msg.read() open_msg.close() # Send the server's lobby message to the client no matter what - self.sendMsg(socket, "<msg to='" + player_id + "' from='0' group_id='0' />" + lobbyMsg, self.players[player_id].useCompression, self.players[player_id].compressionType) + self.sendMsg(socket, "<msg to='" + player_id + "' from='0' group_id='0' />" + lobbyMsg, + self.players[player_id].useCompression, self.players[player_id].compressionType) if self.sendLobbySound: - self.sendMsg(socket, '<sound url="' + self.lobbySound + '" group_id="0" from="0" loop="True" />', self.players[player_id].useCompression, self.players[player_id].compressionType) + self.sendMsg(socket, '<sound url="' + self.lobbySound + '" group_id="0" from="0" loop="True" />', + self.players[player_id].useCompression, self.players[player_id].compressionType) return - except: - traceback.print_exc() + except: traceback.print_exc() + """ # End of lobby message code - ####################################################################### + """ def listenAcceptThread(self,arg): @@ -1374,8 +1291,7 @@ try: self.log_msg("\nlisten thread running...") adder = "" - if self.server_address is not None: - adder = self.server_address + if self.server_address is not None: adder = self.server_address self.listen_sock.bind(('', self.server_port)) self.listen_sock.listen(5) @@ -1383,18 +1299,18 @@ self.log_msg(("Error binding request socket!", e)) self.alive = 0 - while self.alive: - # Block on the socket waiting for a new connection try: (newsock, addr) = self.listen_sock.accept() + """ ## self.log_msg("New connection from " + str(addr)+ ". Interfacing with server...") # Now that we've accepted a new connection, we must immediately spawn a new # thread to handle it...otherwise we run the risk of having a DoS shoved into # our face! :O After words, this thread is dead ready for another connection # accept to come in. + """ thread.start_new_thread(self.acceptedNewConnectionThread, ( newsock, addr )) except: @@ -1405,11 +1321,8 @@ self.log_msg("server socket listening thread exiting...") self.listen_event.set() - - def acceptedNewConnectionThread( self, newsock, addr ): """Once a new connection comes in and is accepted, this thread starts up to handle it.""" - # Initialize xml_dom xml_dom = None data = None @@ -1417,51 +1330,36 @@ # get client info and send othe client info # If this receive fails, this thread should exit without even attempting to process it self.log_msg("Connection from " + str(addr) + " has been accepted. Waiting for data...") - data = self.recvMsg( newsock ) - if data=="" or data == None: self.log_msg("Connection from " + str(addr) + " failed. Closing connection.") - try: - newsock.close() + try: newsock.close() except Exception, e: self.log_msg( str(e) ) print str(e) return #returning causes connection thread instance to terminate - - if data == "<system/>": - try: - newsock.close() - except: - pass + try: newsock.close() + except: pass return #returning causes connection thread instance to terminate - # Clear out the xml_dom in preparation for new stuff, if necessary try: - if xml_dom: - xml_dom.unlink() + if xml_dom: xml_dom.unlink() except: self.log_msg( "The following exception caught unlinking xml_dom:") self.log_msg("Continuing") - - try: - newsock.close() - except: - pass + try: newsock.close() + except: pass return #returning causes connection thread instance to terminate - # Parse the XML received from the connecting client try: xml_dom = parseXml(data) xml_dom = xml_dom._get_documentElement() except: - try: - newsock.close() - except: - pass + try: newsock.close() + except: pass self.log_msg( "Error in parse found from " + str(addr) + ". Disconnected.") self.log_msg(" Offending data(" + str(len(data)) + "bytes)=" + data) self.log_msg( "Exception:") @@ -1474,14 +1372,9 @@ action = xml_dom.getAttribute("action") # Figure out what type of connection we have going on now - if action == "new": - self.new_request(newsock,xml_dom) - - elif action == "update": - self.update_request(newsock,xml_dom) - - else: - self.log_msg("Unknown Join Request!") + if action == "new": self.new_request(newsock,xml_dom) + elif action == "update": self.update_request(newsock,xml_dom) + else: self.log_msg("Unknown Join Request!") except Exception, e: print "The following message: " + str(data) @@ -1491,15 +1384,13 @@ # Again attempt to clean out DOM stuff try: - if xml_dom: - xml_dom.unlink() + if xml_dom: xml_dom.unlink() except: print "The following exception caught unlinking xml_dom:" traceback.print_exc() return #returning causes connection thread instance to terminate - - + """ #======================================================== # # Message_handler @@ -1509,21 +1400,20 @@ # Changed thread organization from one continuous parsing/handling thread # to multiple expiring parsing/handling threads to improve server performance # and player load capacity -- Snowdog 3/04 + """ def message_handler(self,arg): xml_dom = None self.log_msg( "message handler thread running..." ) while self.alive: data = None - try: - data=self.incoming.get(0) + try: data=self.incoming.get(0) except Queue.Empty: time.sleep(0.5) #sleep 1/2 second continue bytes = len(data) - if bytes <= 0: - continue + if bytes <= 0: continue try: thread.start_new_thread(self.parse_incoming_dom,(str(data),)) #data has been passed... unlink from the variable references @@ -1551,20 +1441,15 @@ print "Error in parse of inbound message. Ignoring message." print " Offending data(" + str(len(data)) + "bytes)=" + data print "Exception=" + str(e) - if xml_dom: xml_dom.unlink() - def message_action(self, xml_dom, data): tag_name = xml_dom._get_tagName() - if self.svrcmds.has_key(tag_name): - self.svrcmds[tag_name]['function'](xml_dom,data) - else: - raise Exception, "Not a valid header!" + if self.svrcmds.has_key(tag_name): self.svrcmds[tag_name]['function'](xml_dom,data) + else: raise Exception, "Not a valid header!" #Message Action thread expires and closes here. return - def do_alter(self, xml_dom, data): target = xml_dom.getAttribute("key") value = xml_dom.getAttribute("val") @@ -1574,14 +1459,15 @@ actual_boot_pwd = self.groups[group_id].boot_pwd if self.allow_room_passwords == 0: - msg ="<msg to='" + player + "' from='0' group_id='0' /> Room passwords have been disabled by the server administrator." + msg ="<msg to='" + player + "' from='0' group_id='0' /> " + msg += "Room passwords have been disabled by the server administrator." self.players[player].outbox.put(msg) return elif boot_pwd == actual_boot_pwd: if target == "pwd": - lmessage = "Room password changed to from \"" + self.groups[group_id].pwd + "\" to \"" + value + "\" by " + player + lmessage = "Room password changed to from " + self.groups[group_id].pwd + " to " + value + " by " + player self.groups[group_id].pwd = value - msg ="<msg to='" + player + "' from='0' group_id='0' /> Room password changed to \"" + value + "\"." + msg ="<msg to='" + player + "' from='0' group_id='0' /> Room password changed to " + value + "." self.players[player].outbox.put(msg) self.log_msg(lmessage) self.send_to_all('0',self.groups[group_id].toxml('update')) @@ -1595,7 +1481,6 @@ msg ="<msg to='" + player + "' from='0' group_id='0'>Invalid Administrator Password." self.players[player].outbox.put(msg) - def do_role(self, xml_dom, data): role = "" boot_pwd = "" @@ -1615,17 +1500,12 @@ group_id = xml_dom.getAttribute("group_id") sent_time = "" msg = "" - try: - sent_time = xml_dom.getAttribute("time") - except: - pass - - if sent_time != "": - #because a time was sent return a ping response - msg ="<ping time='" + str(sent_time) + "' />" + try: sent_time = xml_dom.getAttribute("time") + except: pass + if sent_time != "": msg ="<ping time='" + str(sent_time) + "' />" #because a time was sent return a ping response else: - msg ="<msg to='" + player + "' from='" + player + "' group_id='" + group_id + "'><font color='#FF0000'>PONG!?!</font>" - + msg ="<msg to='" + player + "' from='" + player + "' group_id='" + group_id + "'>" + msg += "<font color='#FF0000'>PONG!?!</font>" self.players[player].outbox.put(msg) xml_dom.unlink() @@ -1636,65 +1516,43 @@ try: action = xml_dom.getAttribute("action") from_id = xml_dom.getAttribute("from") - if xml_dom.hasAttribute("pwd"): - pwd=xml_dom.getAttribute("pwd") - else: - pwd="" + if xml_dom.hasAttribute("pwd"): pwd=xml_dom.getAttribute("pwd") + else: pwd="" group_id=self.players[from_id].group_id - if action == "list": if (self.groups[group_id].moderated): msg = "" for i in self.groups[group_id].voice.keys(): - if msg != "": - msg +=", " - if self.players.has_key(i): - msg += '('+i+') '+self.players[i].name - else: - del self.groups[group_id].voice[i] - if (msg != ""): - msg = "The following users may speak in this room: " + msg - else: - msg = "No people are currently in this room with the ability to chat" + if msg != "": msg +=", " + if self.players.has_key(i): msg += '('+i+') '+self.players[i].name + else: del self.groups[group_id].voice[i] + if (msg != ""): msg = "The following users may speak in this room: " + msg + else: msg = "No people are currently in this room with the ability to chat" self.players[from_id].self_message(msg) - else: - self.players[from_id].self_message("This room is currently unmoderated") - elif action == "enable": - if not self.groups[group_id].check_boot_pwd(pwd): - self.players[from_id].self_message("Failed - incorrect admin password") - return - self.groups[group_id].moderated = 1 - self.players[from_id].self_message("This channel is now moderated") - elif action == "disable": + else: self.players[from_id].self_message("This room is currently unmoderated") + elif action == 'enable' or 'disable' or 'addvoice' or 'delvoice': + #condenses password check --TaS 2009 if not self.groups[group_id].check_boot_pwd(pwd): self.players[from_id].self_message("Failed - incorrect admin password") return - self.groups[group_id].moderated = 0 - self.players[from_id].self_message("This channel is now unmoderated") - elif action == "addvoice": - if not self.groups[group_id].check_boot_pwd(pwd): - self.players[from_id].self_message("Failed - incorrect admin password") - return - users = xml_dom.getAttribute("users").split(',') - for i in users: - self.groups[group_id].voice[i.strip()]=1 - elif action == "delvoice": - if not self.groups[group_id].check_boot_pwd(pwd): - self.players[from_id].self_message("Failed - incorrect admin password") - return - users = xml_dom.getAttribute("users").split(',') - for i in users: - if self.groups[group_id].voice.has_key(i.strip()): - del self.groups[group_id].voice[i.strip()] + if action == 'enable': + self.groups[group_id].moderated = 1 + self.players[from_id].self_message("This channel is now moderated") + if action == 'disable': + self.groups[group_id].moderated = 0 + self.players[from_id].self_message("This channel is now unmoderated") + if action == 'addvoice': + users = xml_dom.getAttribute("users").split(',') + for i in users: self.groups[group_id].voice[i.strip()]=1 + if action == 'delvoice': + users = xml_dom.getAttribute("users").split(',') + for i in users: + if self.groups[group_id].voice.has_key(i.strip()): del self.groups[group_id].voice[i.strip()] else: print "Bad input: " + data - except Exception,e: self.log_msg(str(e)) - - - def join_group(self,xml_dom,data): try: from_id = xml_dom.getAttribute("from") @@ -1713,7 +1571,6 @@ #tell the clients password manager the password failed -- SD 8/03 pm = "<password signal=\"fail\" type=\"room\" id=\"" + group_id + "\" data=\"\"/>" self.players[from_id].outbox.put(pm) - msg = 'failed - incorrect room password' if not allowed: @@ -1727,19 +1584,16 @@ #move the player into their new group. self.move_player(from_id, group_id) - except Exception, e: self.log_msg(str(e)) - - - - #---------------------------------------------------------------------------- + """ # move_player function -- added by Snowdog 4/03 # # Split join_group function in half. separating the player validation checks # from the actual group changing code. Done primarily to impliment # boot-from-room-to-lobby behavior in the server. + """ def move_player(self, from_id, group_id ): "move a player from one group to another" @@ -1758,19 +1612,20 @@ self.send_to_group(from_id,group_id,self.players[from_id].toxml('new')) self.check_group(from_id, old_group_id) + """ # Here, if we have a group specific lobby message to send, push it on # out the door! Make it put the message then announce the player...just # like in the lobby during a new connection. # -- only do this check if the room id is within range of known persistent id thresholds #also goes ahead if there is a defaultRoomMessage --akoman + """ if self.isPersistentRoom(group_id) or self.defaultMessageFile != None: try: if self.groups[group_id].messageFile[:4] == 'http': data = urllib.urlretrieve(self.groups[group_id].messageFile) roomMsgFile = open(data[0]) - else: - roomMsgFile = open(self.groups[group_id].messageFile, "r") + else: roomMsgFile = open(self.groups[group_id].messageFile, "r") roomMsg = roomMsgFile.read() roomMsgFile.close() urllib.urlcleanup() @@ -1781,24 +1636,18 @@ # Spit that darn message out now! self.players[from_id].outbox.put("<msg to='" + from_id + "' from='0' group_id='" + group_id + "' />" + roomMsg) - if self.sendLobbySound and group_id == '0': self.players[from_id].outbox.put('<sound url="' + self.lobbySound + '" group_id="0" from="0" loop="True" />') - # Now, tell everyone that we've arrived self.send_to_all('0', self.groups[group_id].toxml('update')) - # this line sends a handle role message to change the players role self.send_player_list(from_id,group_id) - #notify user about others in the room self.return_room_roles(from_id,group_id) self.log_msg(("join_group", (self.groups[group_id].name, group_id, from_id))) self.handle_role("set", from_id, self.players[from_id].role, self.groups[group_id].boot_pwd, group_id) - except Exception, e: self.log_msg(str(e)) - thread.start_new_thread(self.registerRooms,(0,)) def return_room_roles(self,from_id,group_id): @@ -1807,12 +1656,13 @@ msg = "<role action=\"update\" id=\"" + self.players[m].id + "\" role=\"" + self.players[m].role + "\" />" self.players[from_id].outbox.put(msg) - + """ # This is pretty much the same thing as the create_group method, however, # it's much more generic whereas the create_group method is tied to a specific # xml message. Ack! This version simply creates the groups, it does not # send them to players. Also note, both these methods have race # conditions written all over them. Ack! Ack! + """ def new_group( self, name, pwd, boot, minVersion, mapFile, messageFile, persist = 0, moderated=0 ): group_id = str( self.next_group_id ) self.next_group_id += 1 @@ -1824,7 +1674,6 @@ self.log_msg( lmsg ) self.log_msg(("create_group", (str(name), int(group_id), 0) )) ##-99 works, could be better. - def change_group_name(self,gid,name,pid): "Change the name of a group" # Check for & in name. We want to allow this because of its common @@ -1839,7 +1688,6 @@ e = name[loc+1:] value = b + "&" + e oldloc = loc+1 - loc = name.find("'") oldloc = 0 while loc > -1: @@ -1849,7 +1697,6 @@ e = name[loc+1:] name = b + "'" + e oldloc = loc+1 - loc = name.find('"') oldloc = 0 while loc > -1: @@ -1859,20 +1706,15 @@ e = name[loc+1:] name = b + """ + e oldloc = loc+1 - oldroomname = self.groups[gid].name self.groups[gid].name = str(name) lmessage = "Room name changed to from \"" + oldroomname + "\" to \"" + name + "\"" self.log_msg(lmessage + " by " + str(pid) ) self.send_to_all('0',self.groups[gid].toxml('update')) return lmessage - except: - return "An error occured during rename of room!" - + except: return "An error occured during rename of room!" thread.start_new_thread(self.registerRooms,(0,)) - - def create_group(self,xml_dom,data): try: from_id = xml_dom.getAttribute("from") @@ -1886,8 +1728,6 @@ # see if passwords are allowed on this server and null password if not if self.allow_room_passwords != 1: pwd = "" - - # # Check for & in name. We want to allow this because of its common # use in d&d games. @@ -1900,7 +1740,6 @@ e = name[loc+1:] name = b + "&" + e oldloc = loc+1 - loc = name.find("'") oldloc = 0 while loc > -1: @@ -1910,7 +1749,6 @@ e = name[loc+1:] name = b + "'" + e oldloc = loc+1 - loc = name.find('"') oldloc = 0 while loc > -1: @@ -1920,8 +1758,6 @@ e = name[loc+1:] name = b + """ + e oldloc = loc+1 - - group_id = str(self.next_group_id) self.next_group_id += 1 self.groups[group_id] = game_group(group_id,name,pwd,"",boot_pwd, minVersion, None, messageFile ) @@ -1945,20 +1781,14 @@ data = urllib.urlretrieve(self.defaultMessageFile) open_msg = open(data[0]) urllib.urlcleanup() - else: - open_msg = open( self.defaultMessageFile, "r" ) - + else: open_msg = open( self.defaultMessageFile, "r" ) roomMsg = open_msg.read() open_msg.close() # Send the rooms message to the client no matter what self.players[from_id].outbox.put( "<msg to='" + from_id + "' from='0' group_id='" + group_id + "' />" + roomMsg ) - - except Exception, e: - self.log_msg( "Exception: create_group(): " + str(e)) - + except Exception, e: self.log_msg( "Exception: create_group(): " + str(e)) thread.start_new_thread(self.registerRooms,(0,)) - def check_group(self, from_id, group_id): try: if group_id not in self.groups: return @@ -1969,15 +1799,12 @@ self.send_to_all("0",self.groups[group_id].toxml('del')) del self.groups[group_id] self.log_msg(("delete_group", (group_id, from_id))) - - else: - self.send_to_all("0",self.groups[group_id].toxml('update')) + else: self.send_to_all("0",self.groups[group_id].toxml('update')) #The register Rooms thread thread.start_new_thread(self.registerRooms,(0,)) - except Exception, e: - self.log_msg(str(e)) + except Exception, e: self.log_msg(str(e)) def del_player(self,id,group_id): try: @@ -1987,23 +1814,17 @@ del self.players[id] self.log_msg(dmsg) self.log_msg(("disconnect",id)) - - + """ # If already registered then re-register, thereby updating the Meta # on the number of players # Note: Upon server shutdown, the server is first unregistered, so # this code won't be repeated for each player being deleted. + """ if self.be_registered: self.register() - - - except Exception, e: - self.log_msg(str(e)) - + except Exception, e: self.log_msg(str(e)) self.log_msg("Explicit garbage collection shows %s undeletable items." % str(gc.collect())) - - def incoming_player_handler(self,xml_dom,data): id = xml_dom.getAttribute("id") act = xml_dom.getAttribute("action") @@ -2011,16 +1832,13 @@ group_id = self.players[id].group_id ip = self.players[id].ip self.log_msg("Player with IP: " + str(ip) + " joined.") - ServerPlugins.setPlayer(self.players[id]) - self.send_to_group(id,group_id,data) if act=="new": try: self.send_player_list(id,group_id) self.send_group_list(id) - except Exception, e: - traceback.print_exc() + except Exception, e: traceback.print_exc() elif act=="del": #print "del player" self.del_player(id,group_id) @@ -2039,31 +1857,26 @@ "ping": xml_dom.getAttribute("time") \ })) - def strip_cheat_roll(self, string): try: cheat_regex = re.compile('&#91;(.*?)&#93;') string = cheat_regex.sub( r'[ ' + self.cheat_msg + " \\1 " + self.cheat_msg + ' ]', string) - except: - pass + except: pass return string def strip_body_tags(self, string): try: bodytag_regex = re.compile('<\/?body(.*?)>') string = bodytag_regex.sub('', string) - except: - pass + except: pass return string def msgTooLong(self, length): - if length > self.maxSendSize and not self.maxSendSize == 0: - return True + if length > self.maxSendSize and not self.maxSendSize == 0: return True return False def incoming_msg_handler(self,xml_dom,data): xml_dom, data = ServerPlugins.preParseIncoming(xml_dom, data) - to_id = xml_dom.getAttribute("to") from_id = xml_dom.getAttribute("from") group_id = xml_dom.getAttribute("group_id") @@ -2074,15 +1887,10 @@ print "WARNING!! Message received with an invalid from_id. Message dropped." return None - # - # check for < body to prevent someone from changing the background - # - + """ check for < body to prevent someone from changing the background""" data = self.strip_body_tags(data) - # - # check for [ and ] codes which are often used to cheat with dice. - # + """check for [ and ] codes which are often used to cheat with dice.""" if self.players[from_id].role != "GM": data = self.strip_cheat_roll(data) @@ -2110,19 +1918,15 @@ if to_id == 'all': if self.groups[group_id].moderated and not self.groups[group_id].voice.has_key(from_id): self.players[from_id].self_message('This room is moderated - message not sent to others') - else: - self.send_to_group(from_id,group_id,data) - else: - self.players[to_id].outbox.put(data) - + else: self.send_to_group(from_id,group_id,data) + else: self.players[to_id].outbox.put(data) self.check_group_members(group_id) return def sound_msg_handler(self, xml_dom, data): from_id = xml_dom.getAttribute("from") group_id = xml_dom.getAttribute("group_id") - if group_id != 0: - self.send_to_group(from_id, group_id, data) + if group_id != 0: self.send_to_group(from_id, group_id, data) def plugin_msg_handler(self,xml_dom,data): to_id = xml_dom.getAttribute("to") @@ -2134,16 +1938,11 @@ if from_id == "0" or len(from_id) == 0: print "WARNING!! Message received with an invalid from_id. Message dropped." return None - - if to_id == 'all': if self.groups[group_id].moderated and not self.groups[group_id].voice.has_key(from_id): self.players[from_id].self_message('This room is moderated - message not sent to others') - else: - self.send_to_group(from_id, group_id, msg) - else: - self.players[to_id].outbox.put(msg) - + else: self.send_to_group(from_id, group_id, msg) + else: self.players[to_id].outbox.put(msg) self.check_group_members(group_id) return @@ -2153,8 +1952,7 @@ msg += "Displaying Roles<br /><br /><u>Role</u>   <u>Player</u><br />" keys = self.players.keys() for m in keys: - if self.players[m].group_id == group_id: - msg += self.players[m].role + " " + self.players[m].name + "<br />" + if self.players[m].group_id == group_id: msg += self.players[m].role + " " + self.players[m].name + "<br />" self.send(msg,player,group_id) elif act == "set": try: @@ -2167,8 +1965,7 @@ msg = "<role action=\"update\" id=\"" + player + "\" role=\"" + role + "\" />" self.send_to_group("0", group_id, msg) self.players[player].role = role - if (role.lower() == "gm" or role.lower() == "player"): - self.groups[group_id].voice[player]=1 + if (role.lower() == "gm" or role.lower() == "player"): self.groups[group_id].voice[player]=1 else: #tell the clients password manager the password failed -- SD 8/03 pm = "<password signal=\"fail\" type=\"admin\" id=\"" + group_id + "\" data=\"\"/>" @@ -2198,25 +1995,22 @@ try: actual_boot_pwd = self.groups[group_id].boot_pwd server_admin_pwd = self.groups["0"].boot_pwd - self.log_msg("Actual boot pwd = " + actual_boot_pwd) self.log_msg("Given boot pwd = " + given_boot_pwd) if self.players[to_id].group_id == group_id: - + """ ### ---CHANGES BY SNOWDOG 4/03 --- ### added boot to lobby code. ### if boot comes from lobby dump player from the server ### any user in-room boot will dump to lobby instead + """ if given_boot_pwd == server_admin_pwd: # Send a message to everyone in the room, letting them know someone has been booted boot_msg = "<msg to='all' from='%s' group_id='%s'/><font color='#FF0000'>Booting '(%s) %s' from server...</font>" % (from_id, group_id, to_id, self.players[to_id].name) - self.log_msg("boot_msg:" + boot_msg) - self.send_to_group( "0", group_id, boot_msg ) time.sleep( 1 ) - self.log_msg("Booting player " + str(to_id) + " from server.") # Send delete player event to all @@ -2231,9 +2025,7 @@ elif actual_boot_pwd == given_boot_pwd: # Send a message to everyone in the room, letting them know someone has been booted boot_msg = "<msg to='all' from='%s' group_id='%s'/><font color='#FF0000'>Booting '(%s) %s' from room...</font>" % (from_id, group_id, to_id, self.players[to_id].name) - self.log_msg("boot_msg:" + boot_msg) - self.send_to_group( "0", group_id, boot_msg ) time.sleep( 1 ) @@ -2254,17 +2046,15 @@ finally: try: - if xml_dom: - xml_dom.unlink() + if xml_dom: xml_dom.unlink() except Exception, e: traceback.print_exc() self.log_msg('Exception in xml_dom.unlink() ' + str(e)) - - #--------------------------------------------------------------- + """ # admin_kick function -- by Snowdog 4/03 # 9/17/05 updated to allow stealth boots (no client chat announce) -SD - #--------------------------------------------------------------- + """ def admin_kick(self, id, message="", silent = 0 ): "Kick a player from a server from the console" @@ -2273,8 +2063,7 @@ # Send a message to everyone in the victim's room, letting them know someone has been booted boot_msg = "<msg to='all' from='0' group_id='%s'/><font color='#FF0000'>Kicking '(%s) %s' from server... %s</font>" % ( group_id, id, self.players[id].name, str(message)) self.log_msg("boot_msg:" + boot_msg) - if (silent == 0): - self.send_to_group( "0", group_id, boot_msg ) + if (silent == 0): self.send_to_group( "0", group_id, boot_msg ) time.sleep( 1 ) self.log_msg("kicking player " + str(id) + " from server.") @@ -2291,7 +2080,6 @@ traceback.print_exc() self.log_msg('Exception in admin_kick() ' + str(e)) - def admin_banip(self, ip, name="", silent = 0): "Ban a player from a server from the console" try: @@ -2338,9 +2126,7 @@ def admin_unban(self, ip): try: - if self.ban_list.has_key(ip): - del self.ban_list[ip] - + if self.ban_list.has_key(ip): del self.ban_list[ip] self.saveBanList() except Exception, e: @@ -2357,15 +2143,11 @@ msg.append(self.ban_list[ip]['ip']) msg.append("</td></tr>") msg.append("</table>") - return "".join(msg) def admin_toggleSound(self): - if self.sendLobbySound: - self.sendLobbySound = False - else: - self.sendLobbySound = True - + if self.sendLobbySound: self.sendLobbySound = False + else: self.sendLobbySound = True return self.sendLobbySound def admin_soundFile(self, file): @@ -2384,16 +2166,13 @@ self.groups[group].persistant = 0 try: keys = self.groups[group].get_player_ids() - for k in keys: - self.del_player(k, str(group)) + for k in keys: self.del_player(k, str(group)) self.check_group("0", str(group)) - except: - pass + except: pass def send(self,msg,player,group): self.players[player].send(msg,player,group) - def send_to_all(self,from_id,data): try: print data @@ -2401,8 +2180,7 @@ keys = self.players.keys() self.p_lock.release() for k in keys: - if k != from_id: - self.players[k].outbox.put(data) + if k != from_id: self.players[k].outbox.put(data) except Exception, e: traceback.print_exc() self.log_msg("Exception: send_to_all(): " + str(e)) @@ -2415,8 +2193,7 @@ keys = self.groups[group_id].get_player_ids() self.p_lock.release() for k in keys: - if k != from_id: - self.players[k].outbox.put(data) + if k != from_id: self.players[k].outbox.put(data) except Exception, e: traceback.print_exc() self.log_msg("Exception: send_to_group(): " + str(e)) @@ -2441,24 +2218,24 @@ self.log_msg("Exception: send_group_list(): (client #"+to_id+") : " + str(e)) traceback.print_exc() - #-------------------------------------------------------------------------- + """ # KICK_ALL_CLIENTS() # # Convience method for booting all clients off the server at once. # used while troubleshooting mysterious "black hole" server bug # Added by Snowdog 11-19-04 + """ def kick_all_clients(self): try: keys = self.groups.keys() for k in keys: pl = self.groups[k].get_player_ids() - for p in pl: - self.admin_kick(p,"Purged from server") + for p in pl: self.admin_kick(p,"Purged from server") except Exception, e: traceback.print_exc() self.log_msg("Exception: kick_all_clients(): " + str(e)) - + """ # This really has little value as it will only catch people that are hung # on a disconnect which didn't complete. Other idle connections which are # really dead go undeterred. @@ -2466,6 +2243,7 @@ # UPDATED 11-29-04: Changed remove XML send to forced admin_kick for 'dead clients' # Dead clients now removed more effeciently as soon as they are detected # --Snowdog + """ def check_group_members(self, group_id): try: keys = self.groups[group_id].get_player_ids() @@ -2474,8 +2252,7 @@ #as these are likely dead clients idlemins = self.players[k].idle_time() idlemins = idlemins/60 - if (idlemins > self.zombie_time): - self.admin_kick(k,"Removing zombie client", self.silent_auto_kick) + if (idlemins > self.zombie_time): self.admin_kick(k,"Removing zombie client", self.silent_auto_kick) elif self.players[k].get_status() != MPLAY_CONNECTED: if self.players[k].check_time_out(): self.log_msg("Player #" + k + " Lost connection!") @@ -2485,13 +2262,12 @@ def remote_admin_handler(self,xml_dom,data): + """ # handle incoming remove server admin messages # (allows basic administration of server from a remote client) # base message format: <admin id="" pwd="" cmd="" [data for command]> - - if not self.allowRemoteAdmin: - return - + """ + if not self.allowRemoteAdmin: return try: pid = xml_dom.getAttribute("id") gid = "" @@ -2502,7 +2278,6 @@ p_name= "" p_ip = "" - #verify that the message came from the proper ID/Socket and get IP address for logging if self.players.has_key(pid): p_name=(self.players[pid]).name @@ -2524,44 +2299,40 @@ #tell the clients password manager the password failed -- SD 8/03 pm = "<password signal=\"fail\" type=\"server\" id=\"" + str(self.players[pid].group_id) + "\" data=\"\"/>" self.players[pid].outbox.put(pm) - m = "Invalid Remote Server Control Message (bad password) from #" + str(pid) + " (" + str(p_name) + ") " + str(p_ip) + m = "Invalid Remote Server Control Message (bad password) from " + m += "#" + str(pid) + " (" + str(p_name) + ") " + str(p_ip) self.log_msg( m ) return #message now deemed 'authentic' #determine action to take based on command (cmd) - if cmd == "list": #return player list to this user. msg ="<msg to='" + pid + "' from='0' group_id='" + gid + "'>" + self.player_list_remote() self.players[pid].outbox.put(msg) - elif cmd == "banip": ip = xml_dom.getAttribute("bip") name = xml_dom.getAttribute("bname") msg = "<msg to='" + pid + "' from='0' group_id='" + gid + "'> Banned: " + str(ip) self.admin_banip(ip, name) - elif cmd == "ban": id = xml_dom.getAttribute("bid") msg = "<msg to='" + id + "' from='0' group_id='" + gid + "'> Banned!" self.players[pid].outbox.put(msg) self.admin_ban(id, "") - elif cmd == "unban": ip = xml_dom.getAttribute("ip") self.admin_unban(ip) msg = "<msg to='" + pid + "' from='0' group_id='" + gid + "'> Unbaned: " + str(ip) self.players[pid].outbox.put(msg) - elif cmd == "banlist": msg = "<msg to='" + pid + "' from='0' group_id='" + gid + "'>" + self.admin_banlist() self.players[pid].outbox.put(msg) - elif cmd == "killgroup": ugid = xml_dom.getAttribute("gid") if ugid == "0": - m = "<msg to='" + pid + "' from='0' group_id='" + gid + "'>Cannot Remove Lobby! Remote administrator request denied!" + m = "<msg to='" + pid + "' from='0' group_id='" + gid + "'>" + m += "Cannot Remove Lobby! Remote administrator request denied!" self.players[pid].outbox.put(m) else: result = self.prune_room(ugid) @@ -2576,30 +2347,24 @@ except: msg = "<msg to='" + pid + "' from='0' group_id='" + gid + ">Unknown Player ID: No message sent." self.players[pid].outbox.put(msg) - elif cmd == "broadcast": bmsg = xml_dom.getAttribute("msg") self.broadcast(bmsg) - elif cmd == "killserver" and self.allowRemoteKill: #dangerous command..once server stopped it must be restarted manually self.kill_server() - elif cmd == "uptime": msg ="<msg to='" + pid + "' from='0' group_id='" + gid + "'>" + self.uptime(1) self.players[pid].outbox.put(msg) - elif cmd == "help": msg = "<msg to='" + pid + "' from='0' group_id='" + gid + "'>" msg += self.AdminHelpMessage() self.players[pid].outbox.put( msg) - elif cmd == "roompasswords": # Toggle if room passwords are allowed on this server msg = "<msg to='" + pid + "' from='0' group_id='" + gid + "'>" msg += self.RoomPasswords() self.players[pid].outbox.put( msg) - elif cmd == "createroom": rm_name = xml_dom.getAttribute("name") rm_pass = xml_dom.getAttribute("pass") @@ -2607,19 +2372,18 @@ result = self.create_temporary_persistant_room(rm_name, rm_boot, rm_pass) msg = "<msg to='" + pid + "' from='0' group_id='" + gid + "'>" + result self.players[pid].outbox.put(msg) - elif cmd == "nameroom": rm_id = xml_dom.getAttribute("rmid") rm_name = xml_dom.getAttribute("name") result = self.change_group_name(rm_id,rm_name,pid) msg ="<msg to='" + pid + "' from='0' group_id='" + gid + "'/>" + result self.players[pid].outbox.put(msg) - elif cmd == "passwd": tgid = xml_dom.getAttribute("gid") npwd = xml_dom.getAttribute("pass") if tgid == "0": - msg ="<msg to='" + pid + "' from='0' group_id='" + gid + "'>Server password may not be changed remotely!" + msg ="<msg to='" + pid + "' from='0' group_id='" + gid + "'>" + msg += "Server password may not be changed remotely!" self.players[pid].outbox.put(msg) else: try: @@ -2627,81 +2391,72 @@ msg ="<msg to='" + pid + "' from='0' group_id='" + gid + "'>Password changed for room " + tgid self.players[pid].outbox.put(msg) except: pass - elif cmd == "savemaps": for g in self.groups.itervalues(): g.save_map() - msg ="<msg to='" + pid + "' from='0' group_id='" + gid + "'>Persistent room maps saved" self.players[pid].outbox.put(msg) - - else: msg ="<msg to='" + pid + "' from='0' group_id='" + gid + "'><i>[Unknown Remote Administration Command]</i>" self.players[pid].outbox.put(msg) - - except Exception, e: self.log_msg("Exception: Remote Admin Handler Error: " + str(e)) traceback.print_exc() - def toggleRemoteKill(self): - if self.allowRemoteKill: - self.allowRemoteKill = False - else: - self.allowRemoteKill = True - + if self.allowRemoteKill: self.allowRemoteKill = False + else: self.allowRemoteKill = True return self.allowRemoteKill def toggleRemoteAdmin(self): - if self.allowRemoteAdmin: - self.allowRemoteAdmin = False - else: - self.allowRemoteAdmin = True - + if self.allowRemoteAdmin: self.allowRemoteAdmin = False + else: self.allowRemoteAdmin = True return self.allowRemoteAdmin -#----------------------------------------------------------------- -# Remote Administrator Help (returns from server not client) -#----------------------------------------------------------------- + """ + # Remote Administrator Help (returns from server not client) + """ def AdminHelpMessage(self): "returns a string to be sent as a message to a remote admin" - #define the help command list information info = [] info.append( ['list', '/admin list', 'Displays information about rooms and players on the server'] ) info.append( ['uptime', '/admin uptime', 'Information on how long server has been running'] ) info.append( ['help', '/admin help', 'This help message']) - info.append( ['passwd', '/admin passwd <group id> <new password>', 'Changes a rooms bootpassword. Server(lobby) password may not be changed']) + info.append( ['passwd', '/admin passwd <group id> <new password>', + 'Changes a rooms bootpassword. Server(lobby) password may not be changed']) info.append( ['roompasswords', '/admin roompasswords', 'Allow/Disallow Room Passwords on the server (toggles)']) - info.append( ['message', '/admin message <user id> <message>', 'Send a message to a specific user on the server']) + info.append( ['message', '/admin message <user id> <message>', + 'Send a message to a specific user on the server']) info.append( ['broadcast', '/admin broadcast <message>', 'Broadcast message to all players on server']) - info.append( ['createroom', '/admin createroom <room name> <boot password> [password]', 'Creates a temporary persistant room if possible.<i>Rooms created this way are lost on server restarts']) + info.append( ['createroom', '/admin createroom <room name> <boot password> [password]', + 'Creates a temporary persistant room if possible.<i>Rooms created this way are lost on server restarts']) info.append( ['nameroom', '/admin nameroom <group id> <new name>', 'Rename a room']) - info.append( ['killgroup', '/admin killgroup <room id>', 'Remove a room from the server and kick everyone in it.']) + info.append( ['killgroup', '/admin killgroup <room id>', + 'Remove a room from the server and kick everyone in it.']) if self.allowRemoteKill: - info.append( ['killserver', '/admin killserver', 'Shuts down the server. <b>WARNING: Server cannot be restarted remotely via OpenRPG</b>']) + info.append( ['killserver', '/admin killserver', + 'Shuts down the server. <b>WARNING: Server cannot be restarted remotely via OpenRPG</b>']) info.append( ['ban', '/admin ban {playerId}', 'Ban a player from the server.']) info.append( ['unban', '/admin unban {bannedIP}', 'UnBan a player from the server.']) info.append( ['banlist', '/admin banlist', 'List Banned IPs and the Names associated with them']) - info.append( ['savemaps', '/admin savemaps', 'Save all persistent room maps that are not using the default map file.']) - + info.append( ['savemaps', '/admin savemaps', + 'Save all persistent room maps that are not using the default map file.']) #define the HTML for the help display FS = "<font size='-1'>" FE = "<font>" - help = "<hr><B>REMOTE ADMINISTRATOR COMMANDS SUPPORTED</b><br /><br />" help += "<table border='1' cellpadding='2'>" - help += "<tr><td width='15%'><b>Command</b></td><td width='25%'><b>Format</b></td><td width='60%'><b>Description</b></td></tr>" + help += "<tr><td width='15%'><b>Command</b></td><td width='25%'><b>Format</b>" + help += "</td><td width='60%'><b>Description</b></td></tr>" for n in info: - help += "<tr><td>" + FS + n[0] + FE + "</td><td><nobr>" + FS + n[1] + FE + "</nobr></td><td>" + FS + n[2] + FE + "</td></tr>" + help += "<tr><td>" + FS + n[0] + FE + "</td><td><nobr>" + FS + n[1] + FE + "</nobr>" + help += "</td><td>" + FS + n[2] + FE + "</td></tr>" help += "</table>" return help - - #---------------------------------------------------------------- + """ # Create Persistant Group -- Added by Snowdog 6/03 # # Allows persistant groups to be created on the fly. @@ -2710,11 +2465,11 @@ # # Updated function code to use per-group based persistance and # removed references to outdated persistRoomIdThreshold - #---------------------------------------------------------------- + """ def create_temporary_persistant_room(self, roomname, bootpass, password=""): # if the room id just above the persistant room limit is available (not in use) - # then it will be assigned as a persistant room on the server + # then it will be assigned as a persistant room on the server "create a temporary persistant room" group_id = str(self.next_group_id) @@ -2726,7 +2481,7 @@ self.send_to_all('0',self.groups[group_id].toxml('update')) return str("Persistant room created (group " + group_id + ").") - #---------------------------------------------------------------- + """ # Prune Room -- Added by Snowdog 6/03 # # similar to remove_room() except rooms are removed regardless @@ -2734,39 +2489,34 @@ # # Added some error checking and updated room removal for per-room # based persistance -- Snowdog 4/04 - #---------------------------------------------------------------- + """ def prune_room(self,group): #don't allow lobby to be removed if group == '0': return "Lobby is required to exist and cannot be removed." #check that group id exists - if group not in self.groups: - return "Invalid Room Id. Ignoring remove request." + if group not in self.groups: return "Invalid Room Id. Ignoring remove request." try: keys = self.groups[group].get_player_ids() - for k in keys: - self.move_player(k,'0') - + for k in keys: self.move_player(k,'0') ins = "Room" if self.isPersistentRoom(group) : ins="Persistant room" self.send_to_all("0",self.groups[group].toxml('del')) del self.groups[group] self.log_msg(("delete_group", ('0',group))) return ins + " removed." - except: traceback.print_exc() return "An Error occured on the server during room removal!" - -#---------------------------------------------------------------- -# Remote Player List -- Added by snowdog 6/03 -# -# Similar to console listing except formated for web display -# in chat window on remote client -#---------------------------------------------------------------- + """ + # Remote Player List -- Added by snowdog 6/03 + # + # Similar to console listing except formated for web display + # in chat window on remote client + """ def player_list_remote(self): COLOR1 = "\"#004080\"" #header/footer background color COLOR2 = "\"#DDDDDD\"" #group line background color @@ -2778,18 +2528,19 @@ SIZE = "size=\"-1\"" #player info text size FG = PCOLOR - "display a condensed list of players on the server" self.p_lock.acquire() pl = "<br /><table border=\"0\" cellpadding=\"1\" cellspacing=\"2\">" - pl += "<tr><td colspan='4' bgcolor=" + COLOR1 + "><font color=" + COLOR4 + "><b>GROUP & PLAYER LIST</b></font></td></tr>" + pl += "<tr><td colspan='4' bgcolor=" + COLOR1 + "><font color=" + COLOR4 + ">" + pl += "<b>GROUP & PLAYER LIST</b></font></td></tr>" try: - keys = self.groups.keys() keys.sort(id_compare) for k in keys: - groupstring = "<tr><td bgcolor=" + COLOR2 + " colspan='2'><b>Group " + str(k) + ": " + self.groups[k].name + "</b>" - groupstring += "</td><td bgcolor=" + COLOR2 + " > <i>Password: \"" + self.groups[k].pwd + "\"</td><td bgcolor=" + COLOR2 + " > Boot: \"" + self.groups[k].boot_pwd + "\"</i></td></tr>" + groupstring = "<tr><td bgcolor=" + COLOR2 + " colspan='2'>" + groutstring += "<b>Group " + str(k) + ": " + self.groups[k].name + "</b>" + groupstring += "</td><td bgcolor=" + COLOR2 + " > <i>Password: \"" + self.groups[k].pwd + "\"</td>" + groupstring += "<td bgcolor=" + COLOR2 + " > Boot: \"" + self.groups[k].boot_pwd + "\"</i></td></tr>" pl += groupstring ids = self.groups[k].get_player_ids() ids.sort(id_compare) @@ -2803,18 +2554,20 @@ pl += "<tr><td bgcolor=" + COLOR3 + ">" pl += "<font color=" + FG + " " + SIZE + "> (" + (self.players[id]).id + ") " pl += (self.players[id]).name - pl += "</font></td><td bgcolor=" + COLOR3 + " ><font color=" + FG + " " + SIZE + ">[IP: " + (self.players[id]).ip + "]</font></td><td bgcolor=" + COLOR3 + " ><font color=" + FG + " " + SIZE + "> " + pl += "</font></td><td bgcolor=" + COLOR3 + " >" + pl += "<font color=" + FG + " " + SIZE + ">[IP: " + (self.players[id]).ip + "]</font>" + pl += "</td><td bgcolor=" + COLOR3 + " ><font color=" + FG + " " + SIZE + "> " pl += (self.players[id]).idle_status() pl += "</font></td><td><font color=" + FG + " " + SIZE + ">" pl += (self.players[id]).connected_time_string() pl += "</font>" - else: self.groups[k].remove_player(id) pl +="<tr><td colspan='4' bgcolor=" + COLOR3 + " >Bad Player Ref (#" + id + ") in group" pl+="</td></tr>" - pl += "<tr><td colspan='4' bgcolor=" + COLOR1 + "><font color=" + COLOR4 + "><b><i>Statistics: groups: " + str(len(self.groups)) + " players: " + str(len(self.players)) + "</i></b></font></td></tr></table>" - except Exception, e: - self.log_msg(str(e)) + pl += "<tr><td colspan='4' bgcolor=" + COLOR1 + ">" + pl += "<font color=" + COLOR4 + "><b><i>Statistics: groups: " + str(len(self.groups)) + " " + pl += "players: " + str(len(self.players)) + "</i></b></font></td></tr></table>" + except Exception, e: self.log_msg(str(e)) self.p_lock.release() return pl
--- a/orpg/networking/mplay_server_gui.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/networking/mplay_server_gui.py Thu Aug 20 03:00:39 2009 -0500 @@ -14,7 +14,8 @@ import time import types from orpg.dirpath import dir_struct -import orpg.systempath +#import orpg.systempath looks old +from orpg.tools.validate import Validate from orpg.orpg_wx import * import webbrowser from threading import Thread @@ -57,10 +58,8 @@ f = ['b', 'Kb', 'Mb', 'Gb'] i = 0 while i < 3: - if b < 1024: - return str(b) + f[i] - else: - b = b/1024 + if b < 1024: return str(b) + f[i] + else: b = b/1024 i += 1 return str(b) + f[3] @@ -89,10 +88,8 @@ def __init__(self, owner ): """ Loads default configuration settings.""" - userPath = dir_struct["user"] - validate = orpg.tools.validate.Validate(userPath) - validate.config_file( "server_ini.xml", "default_server_ini.xml" ) - configDom = minidom.parse(userPath + 'server_ini.xml') + Validate(dir_struct["user"]).config_file("server_ini.xml", "default_server_ini.xml" ) + configDom = minidom.parse(dir_struct["user"] + 'server_ini.xml') port = configDom.childNodes[0].childNodes[1].getAttribute('port') OPENRPG_PORT = 6774 if port == '' else int(port) #Pretty ugly, but I couldn't find the tag any other way. self.owner = owner @@ -146,7 +143,8 @@ # Main = GUI class Connections(wx.ListCtrl): def __init__( self, parent, main ): - wx.ListCtrl.__init__( self, parent, -1, wx.DefaultPosition, wx.DefaultSize, wx.LC_REPORT|wx.SUNKEN_BORDER|wx.EXPAND|wx.LC_HRULES ) + wx.ListCtrl.__init__( self, parent, -1, wx.DefaultPosition, + wx.DefaultSize, wx.LC_REPORT|wx.SUNKEN_BORDER|wx.EXPAND|wx.LC_HRULES ) self.main = main self.roomList = { 0 : "Lobby" } self._imageList = wx.ImageList( 16, 16, False ) @@ -276,13 +274,11 @@ print "Send message to room..." msg = self.GetMessageInput( "Send message to room of this player") if len(msg): self.main.server.server.send_to_group('0', str(groupID), msg ) - elif menuItem == MENU_PLAYER_SEND_SERVER_MESSAGE: print "broadcast a message..." msg = self.GetMessageInput( "Broadcast Server Message" ) # If we got a message back, send it - if len(msg): - self.main.server.server.broadcast( msg ) + if len(msg): self.main.server.server.broadcast( msg ) def GetMessageInput( self, title ): prompt = "Please enter the message you wish to send:" @@ -293,7 +289,6 @@ class ServerGUI(wx.Frame): STATUS = SERVER_STOPPED - def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size = (760, 560) ) if wx.Platform == '__WXMSW__': icon = wx.Icon( dir_struct["icon"]+'WAmisc9.ico', wx.BITMAP_TYPE_ICO ) @@ -333,52 +328,47 @@ self.total_messages_sent = 0 self.total_data_sent = 0 - ### Build GUI ############################################ + """ Build GUI """ def build_menu(self): """ Build the GUI menu. """ self.mainMenu = wx.MenuBar() + # File Menu menu = wx.Menu() - # Start menu.Append( MENU_START_SERVER, 'Start', 'Start server.') self.Bind(wx.EVT_MENU, self.OnStart, id=MENU_START_SERVER) - # Stop menu.Append( MENU_STOP_SERVER, 'Stop', 'Shutdown server.') self.Bind(wx.EVT_MENU, self.OnStop, id=MENU_STOP_SERVER) - # Exit menu.AppendSeparator() menu.Append( MENU_EXIT, 'E&xit', 'Exit application.') self.Bind(wx.EVT_MENU, self.OnExit, id=MENU_EXIT) self.mainMenu.Append(menu, '&Server') + # Registration Menu menu = wx.Menu() - # Register menu.Append( MENU_REGISTER_SERVER, 'Register', 'Register with OpenRPG server directory.') self.Bind(wx.EVT_MENU, self.OnRegister, id=MENU_REGISTER_SERVER) - # Unregister menu.Append( MENU_UNREGISTER_SERVER, 'Unregister', 'Unregister from OpenRPG server directory.') self.Bind(wx.EVT_MENU, self.OnUnregister, id=MENU_UNREGISTER_SERVER) - # Add the registration menu self.mainMenu.Append( menu, '&Registration' ) + # Server Configuration Menu menu = wx.Menu() - # Ping Connected Players menu.Append( MENU_START_PING_PLAYERS, 'Start Ping', 'Ping players to validate remote connection.' ) self.Bind(wx.EVT_MENU, self.PingPlayers, id=MENU_START_PING_PLAYERS) - # Stop Pinging Connected Players menu.Append( MENU_STOP_PING_PLAYERS, 'Stop Ping', 'Stop validating player connections.' ) self.Bind(wx.EVT_MENU, self.StopPingPlayers, id=MENU_STOP_PING_PLAYERS) - # Set Ping Interval menu.Append( MENU_PING_INTERVAL, 'Ping Interval', 'Change the ping interval.' ) self.Bind(wx.EVT_MENU, self.ConfigPingInterval, id=MENU_PING_INTERVAL) self.mainMenu.Append( menu, '&Configuration' ) - # Add the menus to the main menu bar + self.SetMenuBar( self.mainMenu ) - # Disable register, unregister & stop server by default + self.mainMenu.Enable( MENU_STOP_SERVER, False ) self.mainMenu.Enable( MENU_REGISTER_SERVER, False ) self.mainMenu.Enable( MENU_UNREGISTER_SERVER, False ) + # Disable the ping menu items self.mainMenu.Enable( MENU_START_PING_PLAYERS, False ) self.mainMenu.Enable( MENU_STOP_PING_PLAYERS, False ) @@ -480,10 +470,8 @@ if self.STATUS == SERVER_STOPPED: # see if we already have name specified try: - userPath = dir_struct["user"] - validate = orpg.tools.validate.Validate(userPath) - validate.config_file( "server_ini.xml", "default_server_ini.xml" ) - configDom = minidom.parse(userPath + 'server_ini.xml') + Validate(dir_struct["user"]).config_file( "server_ini.xml", "default_server_ini.xml" ) + configDom = minidom.parse(dir_struct["user"] + 'server_ini.xml') configDom.normalize() configDoc = configDom.documentElement if configDoc.hasAttribute("name"): self.serverName = configDoc.getAttribute("name") @@ -494,19 +482,18 @@ if serverNameEntry.ShowModal() == wx.ID_OK: self.serverName = serverNameEntry.GetValue() # see if we already have password specified try: - userPath = dir_struct["user"] - validate = orpg.tools.validate.Validate(userPath) - validate.config_file( "server_ini.xml", "default_server_ini.xml" ) - configDom = minidom.parse(userPath + 'server_ini.xml') + Validate(dir_struct["user"]).config_file( "server_ini.xml", "default_server_ini.xml" ) + configDom = minidom.parse(dir_struct["user"] + 'server_ini.xml') configDom.normalize() configDoc = configDom.documentElement if configDoc.hasAttribute("admin"): self.bootPwd = configDoc.getAttribute("admin") elif configDoc.hasAttribute("boot"): self.bootPwd = configDoc.getAttribute("boot") except: pass if self.bootPwd == '': - serverPasswordEntry = wx.TextEntryDialog(self, "Please Enter The Server Admin Password:", "Server's Password", self.bootPwd, wx.OK|wx.CANCEL|wx.CENTRE) + serverPasswordEntry = wx.TextEntryDialog(self, + "Please Enter The Server Admin Password:", "Server's Password", + self.bootPwd, wx.OK|wx.CANCEL|wx.CENTRE) if serverPasswordEntry.ShowModal() == wx.ID_OK: self.bootPwd = serverPasswordEntry.GetValue() - if len(self.serverName): wx.BeginBusyCursor() self.server = ServerMonitor(self.callbacks, self.conf, self.serverName, self.bootPwd) @@ -532,7 +519,6 @@ self.mainMenu.Enable( MENU_START_SERVER, True ) self.mainMenu.Enable( MENU_REGISTER_SERVER, False ) self.mainMenu.Enable( MENU_UNREGISTER_SERVER, False ) - # Delete any items that are still in the player list self.conns.DeleteAllItems() def OnRegister(self, event = None): @@ -604,7 +590,6 @@ class HTMLMessageWindow(wx.html.HtmlWindow): "Widget used to present user to admin messages, in HTML format, to the server administrator" - # Init using the derived from class def __init__( self, parent ): wx.html.HtmlWindow.__init__( self, parent )
--- a/orpg/networking/server_plugins.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/networking/server_plugins.py Thu Aug 20 03:00:39 2009 -0500 @@ -25,7 +25,6 @@ def initBase(self): self._startPlugins() - #Methods def _startPlugins(self): autoload = [] @@ -60,7 +59,6 @@ self._load(pluginData) #Write to the autoload file for this plugin - self.__plugins[pluginName].Activated = True self.__plugins[pluginName].start() @@ -68,13 +66,12 @@ if not self.__plugins.has_key(pluginName): #Print some error about invalid plugin return + pluginData = self.__plugins[pluginName] - self.__plugins[pluginName].stop() #Unload it self._unload(pluginData) - #Remove this plugin from the autoload file #Private Methods @@ -84,7 +81,10 @@ return ('plugins.' + self.__ptype + '.' + s2[0], s2[0]) def _unload(self, pluginData): - self.__plugins[pluginData.Name] = PluginData(pluginData.Name, pluginData.File, pluginData.Author, pluginData.Help) + self.__plugins[pluginData.Name] = PluginData(pluginData.Name, + pluginData.File, + pluginData.Author, + pluginData.Help) unload = [] mod = self._findModule(pluginData.File)[0] for key, module in sys.modules.iteritems(): @@ -115,8 +115,6 @@ def _getType(self): return self.__ptype - - #Properties Plugins = property(_getPlugins, None) Type = property(_getType, None) @@ -132,18 +130,15 @@ def preParseIncoming(self, xml_dom, data): sent = True errmsg = "" - for pluginName, pluginData in self.Plugins.iteritems(): if pluginData.Activated: xml_dom, data = pluginData.preParseIncoming(xml_dom, data) - return xml_dom, data def postParseIncoming(self, data): for pluginName, pluginData in self.Plugins.iteritems(): if pluginData.Activated: data = pluginData.postParseIncoming(data) - return data def getPlayer(self): @@ -152,7 +147,6 @@ if pluginData.Activated: playerName = pluginData.addPlayer(data) players.append(playerName) - return players def setPlayer(self, playerData): @@ -161,7 +155,6 @@ if pluginData.Activated: playerName = pluginData.addPlayer(data) players.append(playerName) - return def preParseOutgoing(self): @@ -171,7 +164,6 @@ xml = pluginData.preParseOutgoing() for msg in xml: data.append(msg) - return data def postParseOutgoing(self): @@ -181,7 +173,6 @@ xml = pluginData.postParseOutgoing() for msg in xml: data.append(msg) - return data __key = _SingletonKey()
--- a/orpg/orpg_version.py Tue Aug 18 20:48:36 2009 -0500 +++ b/orpg/orpg_version.py Thu Aug 20 03:00:39 2009 -0500 @@ -4,7 +4,7 @@ #BUILD NUMBER FORMAT: "YYMMDD-##" where ## is the incremental daily build index (if needed) DISTRO = "Traipse Dev" DIS_VER = "Ornery Orc" -BUILD = "090818-04" +BUILD = "090820" # This version is for network capability. PROTOCOL_VERSION = "1.2"