Ejemplo n.º 1
0
	def collides(self):

		self.cHandler.addInPattern('%fn-into-%in')
		self.cHandler.addOutPattern('%fn-out-%in')

		DO=DirectObject()

		DO.accept("playerCollider-into-npcCollider", self.collideEventIn)
		DO.accept("playerCollider-out-npcCollider", self.collideEventOut)
Ejemplo n.º 2
0
 def __init__(self, numShown, parent, title = None, height = 0.59999999999999998, memberHeight = 0.065000000000000002, memberOffset = 0.021000000000000001, memberWidth = 0.45000000000000001, bottom = 0, hud = False, width = 0.47999999999999998, sort = 0):
     if hasattr(self, 'initialized'):
         self.arrangeMembers()
         return None
     
     self.shown = numShown
     self.memberHeight = memberHeight
     self.memberWidth = memberWidth
     self.memberOffset = memberOffset
     self.title = title
     self.wantSortButtons = sort
     self.width = width
     self.bottom = bottom
     self.height = height
     self.hud = hud
     self.baseFrame = DirectFrame(relief = None, parent = parent)
     if self.hud:
         self.baseFrame['state'] = DGG.DISABLED
     
     self.members = []
     self.memberAvatarDict = { }
     self.memberPlayerDict = { }
     self.onlineCheckTaskName = base.cr.specialName('memberList_checkLastOnline')
     self.prearrangeTaskName = base.cr.specialName('memberList_prearrangeMembers')
     self.onlineChangeEvent = base.cr.specialName('memberList_onlineChange')
     self.setup()
     self.arrangeMembers()
     self.initialized = 1
     self.show()
     self.sortMode = 'Name'
     self.onlineDataProbe = DirectObject()
     self.onlineCount = 0
Ejemplo n.º 3
0
    def init_collisions(self):
        base.cTrav = CollisionTraverser()
        self.cHandler = CollisionHandlerEvent()

        pickerNode = CollisionNode("mouseRayNode")
        pickerNPos = base.camera.attachNewNode(pickerNode)
        self.pickerRay = CollisionRay()
        pickerNode.addSolid(self.pickerRay)

        pickerNode.setTag("rays","ray1")
        base.cTrav.addCollider(pickerNPos, self.cHandler)

        self.cHandler.addInPattern("%(rays)ft-into-%(prov)it")
        self.cHandler.addOutPattern("%(rays)ft-out-%(prov)it")

        self.cHandler.addAgainPattern("ray_again_all%(""rays"")fh%(""prov"")ih")

        self.DO=DirectObject()

        self.DO.accept('ray1-into-city', self.collideInBuilding)
        self.DO.accept('ray1-out-city', self.collideOutBuilding)

        self.DO.accept('ray_again_all', self.collideAgainstBuilds)

        self.pickingEnabledOject=None

        self.DO.accept('mouse1', self.mouseClick, ["down"])
        self.DO.accept('mouse1-up', self.mouseClick, ["up"])

        taskMgr.add(self.rayUpdate, "updatePicker")
Ejemplo n.º 4
0
    def setup_collision_calcs(self):
        self.cHandler.addInPattern("%(rays)ft-into-%(prov)it")
        self.cHandler.addOutPattern("%(rays)ft-out-%(prov)it")

        self.cHandler.addAgainPattern("ray_again_all%(""rays"")fh%(""prov"")ih")

        self.DO=DirectObject()

        self.DO.accept('ray1-into-city', self.collideInBuilding)
        self.DO.accept('ray1-out-city', self.collideOutBuilding)

        self.DO.accept('ray_again_all', self.collideAgainstBuilds)

        self.pickingEnabledOject=None

        self.DO.accept('mouse1', self.mouseClick, ["down"])
        self.DO.accept('mouse1-up', self.mouseClick, ["up"])
Ejemplo n.º 5
0
class PirateMemberList(DirectObject):
    
    def __init__(self, numShown, parent, title = None, height = 0.59999999999999998, memberHeight = 0.065000000000000002, memberOffset = 0.021000000000000001, memberWidth = 0.45000000000000001, bottom = 0, hud = False, width = 0.47999999999999998, sort = 0):
        if hasattr(self, 'initialized'):
            self.arrangeMembers()
            return None
        
        self.shown = numShown
        self.memberHeight = memberHeight
        self.memberWidth = memberWidth
        self.memberOffset = memberOffset
        self.title = title
        self.wantSortButtons = sort
        self.width = width
        self.bottom = bottom
        self.height = height
        self.hud = hud
        self.baseFrame = DirectFrame(relief = None, parent = parent)
        if self.hud:
            self.baseFrame['state'] = DGG.DISABLED
        
        self.members = []
        self.memberAvatarDict = { }
        self.memberPlayerDict = { }
        self.onlineCheckTaskName = base.cr.specialName('memberList_checkLastOnline')
        self.prearrangeTaskName = base.cr.specialName('memberList_prearrangeMembers')
        self.onlineChangeEvent = base.cr.specialName('memberList_onlineChange')
        self.setup()
        self.arrangeMembers()
        self.initialized = 1
        self.show()
        self.sortMode = 'Name'
        self.onlineDataProbe = DirectObject()
        self.onlineCount = 0

    
    def mouseWheelUp(self, task = None):
        if len(self.members) > self.shown:
            amountScroll = self.shown / 1.0 * len(self.members)
            self.memberFrame.verticalScroll['value'] -= amountScroll
        

    
    def mouseWheelDown(self, task = None):
        if len(self.members) > self.shown:
            amountScroll = self.shown / 1.0 * len(self.members)
            self.memberFrame.verticalScroll['value'] += amountScroll
        

    
    def countMembers(self):
        return len(self.members)

    
    def show(self):
        self.baseFrame.show()
        self.accept('press-wheel_up-%s' % self.memberFrame.guiId, self.mouseWheelUp)
        self.accept('press-wheel_down-%s' % self.memberFrame.guiId, self.mouseWheelDown)
        self.accept('press-wheel_up-%s' % self.memberFrame.verticalScroll.guiId, self.mouseWheelUp)
        self.accept('press-wheel_down-%s' % self.memberFrame.verticalScroll.guiId, self.mouseWheelDown)
        self.accept('press-wheel_up-%s' % self.memberFrame.verticalScroll.thumb.guiId, self.mouseWheelUp)
        self.accept('press-wheel_down-%s' % self.memberFrame.verticalScroll.thumb.guiId, self.mouseWheelDown)
        self.accept('press-wheel_up-%s' % self.memberFrame.verticalScroll.incButton.guiId, self.mouseWheelUp)
        self.accept('press-wheel_down-%s' % self.memberFrame.verticalScroll.incButton.guiId, self.mouseWheelDown)
        self.accept('press-wheel_up-%s' % self.memberFrame.verticalScroll.decButton.guiId, self.mouseWheelUp)
        self.accept('press-wheel_down-%s' % self.memberFrame.verticalScroll.decButton.guiId, self.mouseWheelDown)
        self.accept('socailPanelWheelUp', self.mouseWheelUp)
        self.accept('socailPanelWheelDown', self.mouseWheelDown)

    
    def hide(self):
        self.baseFrame.hide()
        self.ignoreAll()

    
    def destroy(self):
        taskMgr.remove(self.onlineCheckTaskName)
        taskMgr.remove(self.prearrangeTaskName)
        self.onlineDataProbe.ignore(base.cr.statusDatabase.avatarDoneTaskName)
        self.ignoreAll()
        for member in self.members:
            member.detachNode()
            member.destroy()
        
        self.memberAvatarDict = { }
        self.memberPlayerDict = { }
        self.members = []
        self.baseFrame.destroy()

    
    def setPos(self, x, y, z):
        self.baseFrame.setPos(x, y, z)

    
    def setup(self):
        charGui = loader.loadModel('models/gui/char_gui')
        knob = (charGui.find('**/chargui_slider_node'), charGui.find('**/chargui_slider_node_down'), charGui.find('**/chargui_slider_node_over'))
        self.memberFrame = DirectScrolledFrame(parent = self.baseFrame, relief = None, state = DGG.NORMAL, manageScrollBars = 0, autoHideScrollBars = 1, frameSize = (0, self.width, self.bottom, self.height), canvasSize = (0, self.width - 0.050000000000000003, self.bottom + 0.025000000000000001, self.height - 0.025000000000000001), verticalScroll_relief = None, verticalScroll_frameSize = (0, PiratesGuiGlobals.ScrollbarSize, self.bottom, self.height), verticalScroll_image = charGui.find('**/chargui_slider_small'), verticalScroll_image_scale = ((self.height - self.bottom) + 0.050000000000000003, 1, 0.75), verticalScroll_image_hpr = (0, 0, 90), verticalScroll_image_pos = (self.width - PiratesGuiGlobals.ScrollbarSize * 0.5 - 0.0, 0, (self.bottom + self.height) * 0.5), verticalScroll_image_color = (0.60999999999999999, 0.59999999999999998, 0.59999999999999998, 1), verticalScroll_thumb_image = knob, verticalScroll_thumb_relief = None, verticalScroll_thumb_image_scale = 0.29999999999999999, verticalScroll_resizeThumb = 0, horizontalScroll_relief = None, sortOrder = 5)
        if self.hud:
            self.memberFrame['state'] = DGG.DISABLED
        
        self.memberFrame.verticalScroll.incButton.destroy()
        self.memberFrame.verticalScroll.decButton.destroy()
        self.memberFrame.horizontalScroll.incButton.destroy()
        self.memberFrame.horizontalScroll.decButton.destroy()
        self.memberFrame.horizontalScroll.hide()
        self.memberFrame.show()
        charGui = loader.loadModel('models/gui/toplevel_gui')
        buttonImage = (charGui.find('**/generic_button'), charGui.find('**/generic_button_down'), charGui.find('**/generic_button_over'), charGui.find('**/generic_button_disabled'))
        if self.wantSortButtons:
            sortButtonWidth = self.memberWidth
            nameProp = 0.75
            nameSize = nameProp * sortButtonWidth
            onlineProp = 0.25
            onlineSize = onlineProp * sortButtonWidth
            levelSize = 0.0
            sortNameButton = DirectButton(parent = self.memberFrame, relief = None, image = buttonImage, image_scale = (nameSize, 1.0, 0.14999999999999999), image0_color = VBase4(0.65000000000000002, 0.65000000000000002, 0.65000000000000002, 1), image1_color = VBase4(0.40000000000000002, 0.40000000000000002, 0.40000000000000002, 1), image2_color = VBase4(0.90000000000000002, 0.90000000000000002, 0.90000000000000002, 1), image3_color = VBase4(0.40999999999999998, 0.40000000000000002, 0.40000000000000002, 1), text = 'Name', text_align = TextNode.ACenter, text_pos = (0, -0.01), text_scale = PiratesGuiGlobals.TextScaleMed, text_fg = PiratesGuiGlobals.TextFG2, text_shadow = PiratesGuiGlobals.TextShadow, pos = (nameSize * 0.5, 0, self.height + 0.040000000000000001), command = self.sortByName)
            sortNameButton.show()
            sortOnlineButton = DirectButton(parent = self.memberFrame, relief = None, image = buttonImage, image_scale = (onlineSize, 1.0, 0.14999999999999999), image0_color = VBase4(0.65000000000000002, 0.65000000000000002, 0.65000000000000002, 1), image1_color = VBase4(0.40000000000000002, 0.40000000000000002, 0.40000000000000002, 1), image2_color = VBase4(0.90000000000000002, 0.90000000000000002, 0.90000000000000002, 1), image3_color = VBase4(0.40999999999999998, 0.40000000000000002, 0.40000000000000002, 1), text = 'Online', text_align = TextNode.ACenter, text_pos = (0, -0.01), text_scale = PiratesGuiGlobals.TextScaleMed, text_fg = PiratesGuiGlobals.TextFG2, text_shadow = PiratesGuiGlobals.TextShadow, pos = (onlineSize * 0.5 + nameSize + levelSize, 0, self.height + 0.040000000000000001), command = self.sortByOnline)
            sortOnlineButton.show()
        
        charGui.removeNode()

    
    def sortByName(self):
        self.sortMode = 'Name'
        self.arrangeMembers()

    
    def sortByOnline(self):
        self.sortMode = 'Online'
        self.arrangeMembers()

    
    def getMemberByAvId(self, avId):
        for member in self.members:
            if avId and member.avId == avId:
                return member
                continue
        

    
    def getMemberByPlayerId(self, playerId):
        for member in self.members:
            if playerId and member.playerId == playerId:
                return member
                continue
        

    
    def removeNotOnAvList(self, cullAvList):
        for member in self.members:
            if member.avId not in cullAvList:
                self.removeMember(member.avId, member.playerId, member.mode)
                continue
        

    
    def updateOrAddMember(self, avId, playerId, mode, modeInfo = None):
        tryAv = self.memberAvatarDict.get(avId)
        tryPlayer = self.memberPlayerDict.get(playerId)
        if tryAv and tryAv.isEmpty():
            if tryAv in self.members:
                self.members.remove(tryAv)
            
            tryAv = None
            del self.memberAvatarDict[avId]
        
        if tryPlayer and tryPlayer.isEmpty():
            if tryPlayer in self.members:
                self.members.remove(tryPlayer)
            
            tryPlayer = None
            del self.memberPlayerDict[playerId]
        
        if tryAv:
            if tryAv.mode == mode:
                self.updateMemberInfo(avId, playerId, mode, modeInfo)
            elif mode == MODE_FRIEND_AVATAR and tryAv.mode == MODE_FRIEND_PLAYER_AVATAR:
                self.addMember(avId, playerId, mode, modeInfo)
            elif mode == MODE_FRIEND_PLAYER_AVATAR and tryAv.mode == MODE_FRIEND_AVATAR:
                return None
            
        elif tryPlayer and tryPlayer.mode == mode:
            self.updateMemberInfo(avId, playerId, mode, modeInfo)
        else:
            self.addMember(avId, playerId, mode, modeInfo)

    
    def updateMemberInfo(self, avId, playerId, mode, modeInfo = None):
        tryAv = self.memberAvatarDict.get(avId)
        tryPlayer = self.memberPlayerDict.get(playerId)
        member = None
        if tryAv and tryAv.mode == mode:
            member = tryAv
        elif tryPlayer and tryPlayer.mode == mode:
            member = tryPlayer
        
        if member:
            member.update(modeInfo)
            self.prearrangeMembers()
        

    
    def addMember(self, avId, playerId, mode, modeInfo = None, fromClearList = 0):
        if mode == MODE_FRIEND_AVATAR:
            someMember = self.getMemberByPlayerId(playerId)
            if someMember:
                playerId = someMember.playerId
            
        
        if mode == MODE_FRIEND_PLAYER_AVATAR:
            avId = base.cr.playerFriendsManager.findAvIdFromPlayerId(playerId)
        
        if self.memberAvatarDict.get(avId) or self.memberPlayerDict.get(playerId):
            self.removeMember(avId, playerId, mode)
        
        texcolor = (0.90000000000000002, 1, 0.90000000000000002, 1)
        fcolor = PiratesGuiGlobals.ButtonColor5
        addMe = PirateMemberButton(self, avId, playerId, mode, modeInfo)
        self.members.append(addMe)
        if avId:
            self.memberAvatarDict[avId] = addMe
        
        if playerId:
            self.memberPlayerDict[playerId] = addMe
        
        if mode == MODE_GUILD and len(self.members) > 0:
            self.accept('guildMemberOnlineStatus', self.updateGuildMemberOnline)
        
        taskMgr.remove(self.onlineCheckTaskName)
        task = taskMgr.doMethodLater(1.0, self.requestLastOnlineTimes, self.onlineCheckTaskName)
        self.onlineDataProbe.ignore(base.cr.statusDatabase.avatarDoneTaskName)
        self.onlineDataProbe.accept(base.cr.statusDatabase.avatarDoneTaskName, self.updateOnlineData)
        self.prearrangeMembers()
        return addMe

    
    def addPotentialMember(self, avId, avName, mode):
        self.removeMember(avId, None, mode)
        texcolor = (0.90000000000000002, 1, 0.90000000000000002, 1)
        fcolor = PiratesGuiGlobals.ButtonColor5
        addMe = PirateMemberButton(self, avId, None, mode, name = avName)
        self.members.append(addMe)
        self.memberAvatarDict[avId] = addMe
        self.prearrangeMembers()
        if mode == MODE_GUILD and len(self.members) > 0:
            self.accept('guildMemberOnlineStatus', self.updateGuildMemberOnline)
        
        taskMgr.remove(self.onlineCheckTaskName)
        task = taskMgr.doMethodLater(1.0, self.requestLastOnlineTimes, self.onlineCheckTaskName)
        self.onlineDataProbe.ignore(base.cr.statusDatabase.avatarDoneTaskName)
        self.onlineDataProbe.accept(base.cr.statusDatabase.avatarDoneTaskName, self.updateOnlineData)
        return addMe

    
    def removeMember(self, avId, playerId, mode):
        removedAvId = None
        removedPlayerId = None
        if not playerId and avId:
            avMemeber = self.memberAvatarDict.get(avId)
            if avMemeber:
                playerId = avMemeber.playerId
            
        elif playerId and not avId:
            playerMemeber = self.memberPlayerDict.get(avId)
            if playerMemeber:
                avId = playerMemeber.playerId
            
        
        if avId:
            removeMe = self.memberAvatarDict.get(avId)
            removedAvId = avId
            if removeMe:
                removedPlayerId = removeMe.playerId
                if removeMe in self.members:
                    self.members.remove(removeMe)
                
                removeMe.detachNode()
                removeMe.destroy()
                del self.memberAvatarDict[avId]
            
        
        if playerId:
            removeMe = self.memberPlayerDict.get(playerId)
            removedPlayerId = playerId
            if removeMe:
                removedAvId = removeMe.avId
                if removeMe in self.members:
                    self.members.remove(removeMe)
                
                removeMe.detachNode()
                removeMe.destroy()
                del self.memberPlayerDict[playerId]
            
        
        if mode == MODE_GUILD and len(self.members) == 0:
            self.ignore('guildMemberOnlineStatus')
        
        self.prearrangeMembers()
        return (removedAvId, removedPlayerId)

    
    def removeMemberWithRefill(self, avId, playerId, mode):
        self.removeMember(avId, playerId, mode)
        if mode in (MODE_FRIEND_AVATAR, MODE_FRIEND_PLAYER_AVATAR):
            self.refillMember(avId, playerId, mode)
        

    
    def refillMember(self, avId, playerId, mode):
        if mode == MODE_FRIEND_AVATAR:
            if playerId and base.cr.playerFriendsManager.isFriend(playerId):
                info = base.cr.playerFriendsManager.getFriendInfo(playerId)
                self.updateOrAddMember(None, playerId, MODE_FRIEND_PLAYER_AVATAR, info)
            
        elif mode == MODE_FRIEND_PLAYER_AVATAR:
            if avId and base.cr.avatarFriendsManager.isFriend(avId):
                info = base.cr.avatarFriendsManager.getFriendInfo(avId)
                self.updateOrAddMember(avId, None, MODE_FRIEND_AVATAR, info)
            
        

    
    def requestLastOnlineTimes(self, task):
        memberIds = []
        for member in self.members:
            if member.avId:
                memberIds.append(member.avId)
                continue
        
        base.cr.statusDatabase.queueOfflineAvatarStatus(memberIds)
        self.accept(base.cr.statusDatabase.avatarDoneTaskName, self.updateOnlineData)
        return task.done

    
    def updateOnlineData(self):
        for member in self.members:
            if member.avId:
                onlineTime = base.cr.statusDatabase.avatarData.get(member.avId)
                if onlineTime:
                    member.updateOnlineTime(onlineTime)
                
        

    
    def updateGuildMemberOnline(self, avId, onlineStatus):
        for member in self.members:
            if member.avId == avId:
                member.modeInfo[3] = onlineStatus
                member.update()
                continue
        

    
    def updateGuildMemberRank(self, avId, rank):
        for member in self.members:
            if member.avId == avId:
                member.updateGuildRank(rank)
                continue
        

    
    def updateAll(self):
        for member in self.members:
            member.update()
        

    
    def updateAv(self, avId):
        member = self.memberAvatarDict.get(avId)
        if member:
            member.update()
        

    
    def prearrangeMembers(self):
        taskMgr.remove(self.prearrangeTaskName)
        taskMgr.doMethodLater(0.10000000000000001, self.arrangeMembers, self.prearrangeTaskName)

    
    def arrangeMembers(self, task = None):
        numMembers = len(self.members)
        if numMembers == 0:
            return None
        
        self.members.sort(self.compareMembers)
        self.memberFrame['canvasSize'] = (0, 0.0, 0, numMembers * self.memberHeight)
        self.placement = self.memberHeight * numMembers
        for index in range(numMembers):
            self.placement -= self.memberHeight
            self.members[index].setPos(self.memberWidth * 0.5 - 0.0, 0, self.placement)
        
        self.updateAll()
        taskMgr.remove(self.prearrangeTaskName)
        if task:
            return task.done
        

    
    def getSize(self):
        return len(self.members)

    
    def clearMembers(self):
        for member in self.members:
            member.detachNode()
            member.destroy()
        
        self.members = []
        self.memberAvatarDict = { }
        self.memberPlayerDict = { }
        self.onlineCount = 0

    
    def compareMembers(self, first, other):
        if other is None:
            return -1
        
        if first.online and not (other.online):
            return -1
        elif not (first.online) and other.online:
            return 1
        
        if first.mode == MODE_CREW and first.mode == MODE_CREW_HUD or first.mode == MODE_CREW_HUD_SEA:
            if not hasattr(other, 'modeInfo') or not (other.modeInfo):
                return 1
            elif first.modeInfo:
                if first.modeInfo.isManager:
                    return -1
                elif other.modeInfo.isManager:
                    return 1
                
            
        
        if first.mode == MODE_GUILD:
            if not hasattr(other, 'modeInfo') or not (other.modeInfo):
                return 1
            elif first.modeInfo:
                if first.modeInfo[2] in (2, 3) and other.modeInfo[2] == 4:
                    return -1
                elif first.modeInfo[2] == 4 and other.modeInfo[2] in (2, 3):
                    return 1
                elif first.modeInfo[2] > other.modeInfo[2]:
                    return -1
                elif first.modeInfo[2] < other.modeInfo[2]:
                    return 1
                
            
        
        if (first.mode == MODE_FRIEND_PLAYER or first.mode == MODE_FRIEND_PLAYER_AVATAR) and first.mode == MODE_FRIEND_AVATAR:
            return -1
        elif first.mode == MODE_FRIEND_AVATAR:
            if first.mode == MODE_FRIEND_PLAYER or first.mode == MODE_FRIEND_PLAYER_AVATAR:
                return 1
            elif self.sortMode == 'Online':
                if first.lastOnline == None:
                    return 1
                elif other.lastOnline == None:
                    return -1
                elif first.lastOnline > other.lastOnline:
                    return -1
                
                return 1
            elif first.mode == MODE_FRIEND_PLAYER_AVATAR:
                text1 = first['text'][0]
            else:
                text1 = first['text']
        if other.mode == MODE_FRIEND_PLAYER_AVATAR:
            text2 = other['text'][0]
        else:
            text2 = other['text']
        return cmp(text1.lower(), text2.lower())
Ejemplo n.º 6
0
class StrategyGame(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)

        self.camera_control()



        self.REGION_MAP = "maps/italy_provs.png"
        self.TEXTURE_MAP = "maps/italy_terrain2.png"
        self.WORLD_MAP = "maps/italy_map.xml"
        self.SCENARIO_MAP = "scenarios/italy_scen.xml"

        self.terrainScale = 1 # Currently Broken

        self.keyboard_setup()

        self.drawTerrain()



        self.xml_load_map(self.WORLD_MAP,"WorldMap")
        self.xml_load_map(self.SCENARIO_MAP,"Scenario")
        self.init_collisions()
        self.pickingEnabledObject = None

        self.taskMgr.add(self.camera_update, "UpdateCameraTask")

        self.generate_models()
        self.txtBox = OnscreenText("<No province>")
        self.setup_collision_calcs()
        taskMgr.add(self.rayUpdate, "updatePicker")
        taskMgr.doMethodLater(0.2,self.task_calendar, "calendar")
        self.init_variables()
        self.interface()

    def init_variables(self):
        self.armies = [[],[]]
        for n in range(len(self.nations)):
            self.armies.append(n)
        self.target = 0
        self.army_count = 0
        self.selected_prov = -1
        self.months = ["January","February","March","April","May","June",
                       "July","August","September","October","November","December"]
        self.adce = "AD"
        self.player = 1
        self.money_inc = 0
        for p in range(len(self.provs)):
            if self.provs_owner[p] == self.player:
                self.money_inc += self.provs_money[p]
        self.men_inc = 0
        for p in range(len(self.provs)):
            if self.provs_owner[p] == self.player:
                self.men_inc += self.provs_men[p]

    def draw_card(self,x,y,width,height,colour):

        cm = CardMaker("CardMaker")
        cm.setFrame(x, x+width,y+height, y)
        card = render2d.attachNewNode(cm.generate())
        card.setColor(colour)
        return (card)

    def interface(self):
        self.interface_back = self.draw_card(-0.8,-1,1.6,0.4,(100,100,100,100))

        self.txt_name = OnscreenText(text = "", pos = (-0.8,-0.7,-0.8))
        self.txt_money = OnscreenText(text = "", pos = (-0.8,-0.8,-0.8))
        self.txt_men = OnscreenText(text = "", pos = (-0.8,-0.9,-0.8))
        self.txt_nation = OnscreenText(text = self.nations[self.player-1], pos = (-1.2,0.9,-0.8))
        self.txt_nation_money = OnscreenText(text = "Coin: " + str(self.nations_money[self.player-1])+" +"+str(self.money_inc), pos = (-0.4,0.9,-0.8))
        self.txt_nation_men = OnscreenText(text = "Manpower: " + str(self.nations_men[self.player-1])+" +"+str(self.men_inc), pos = (0.4,0.9,-0.8))
        self.txt_date = OnscreenText(text = str(self.day)+" of "+self.months[self.month-1]+" "+str(self.year)+self.adce, pos = (-1.0,0.8,-0.8))

    def task_calendar(self,task):
        #task.delayTime = 5
        if (self.month == 1 or self.month == 3 or self.month == 5 or
            self.month == 7 or self.month == 8 or self.month == 10 or self.month == 12):
                if self.day == 31 and self.month == 12:
                    self.day = 1
                    self.month = 1
                    self.year += 1
                elif self.day == 31:
                    self.day = 1
                    self.month += 1
                else:
                    self.day += 1
        elif (self.month == 4 or self.month == 6 or self.month == 9 or self.month == 11):
            if self.day == 30:
                self.day = 1
                self.month += 1
            else:
                self.day += 1
        elif (self.month == 2):
#            if isleap:
#                print self.year/4
#                print "LEAP YEAR"
#                if self.day == 29:
#                    self.day = 1
#                    self.month = 3
#                else:
#                    self.day += 1
#            else:
            print "IS NOT A LEAP YEAR"
            if self.day == 28:
                self.day = 1
                self.month = 3
            else:
                self.day += 1
        self.daypass()
        return Task.again

    def daypass(self):
        self.nations_money[self.player-1] += self.money_inc
        self.nations_men[self.player-1] += self.men_inc
        self.update_interface()

    def update_interface(self):
        self.txt_date.setText(str(self.day)+" of "+self.months[self.month-1]+" "+str(self.year)+self.adce)
        self.txt_nation_money.setText("Coin: " + str(self.nations_money[self.player-1])+" +"+str(self.money_inc))
        self.txt_nation_men.setText("Manpower: " + str(self.nations_men[self.player-1])+" +"+str(self.men_inc))
        if self.selected_prov != -1:
            self.txt_name.setText("Province: "+self.provs[self.selected_prov])
            self.txt_money.setText("Income: "+str(self.provs_money[self.selected_prov]))
            self.txt_men.setText("Manpower: "+str(self.provs_men[self.selected_prov]))
            self.interface_back.setColor(self.format_colour_tuple(self.nations_rgb[self.provs_owner[self.selected_prov]-1]))
        else:
            self.txt_name.setText("")
            self.txt_money.setText("")
            self.txt_men.setText("")
            self.interface_back.setColor((255,255,255,255))

    def army_create(self):
        id = self.army_count+1
        army = self.loader.loadModel("models/man.x")
        self.armies[0].append(id)
        army.reparentTo(self.render)
        army.setName(str(id))
        army.setScale(1, 1, 1)
        x = 50
        y = 50
        target = self.target
        target_x = float(self.provs_x[target])
        target_y = 257-float(self.provs_y[target])
        target_z = float(self.getObjectZ(target_x,target_y)-1)
        oArmyCol = army.attachNewNode(CollisionNode("BuildingCNode%d"%id))
        oArmyCol.setScale((2,2,2))
        oArmyCol.node().addSolid(CollisionSphere(0,0,0,1))
        oArmyCol.setTag("unit","army")
        oArmyCol.show()
        point1 = Point3(x,y,0)
        point2 = Point3(target_x,target_y,target_z)
        distance = (point1.getXy() - point2.getXy()).length()
        myInterval = army.posInterval(distance/10, Point3(target_x,target_y, target_z))
        mySequence = Sequence(myInterval)
        mySequence.start()
        army.setPos(x, y, self.getObjectZ(x,y)-1)
        army.setTag("target",str(target))
        self.army_count += 1
        if (self.target<len(self.provs)-1):
            self.target += 1
        else:
            self.target = 0
        #taskMgr.add()

    def army_update(self,id):
        point1 = self.armies[0][id-1].getPos()
        point2 = Point3(target_x,target_y,target_z)
        distance = (point1.getXy() - point2.getXy()).length()

    def init_collisions(self):
        base.cTrav = CollisionTraverser()
        self.cHandler = CollisionHandlerEvent()

        pickerNode = CollisionNode("mouseRayNode")
        pickerNPos = base.camera.attachNewNode(pickerNode)
        self.pickerRay = CollisionRay()
        pickerNode.addSolid(self.pickerRay)

        pickerNode.setTag("rays","ray1")
        base.cTrav.addCollider(pickerNPos, self.cHandler)

    def setup_collision_calcs(self):
        self.cHandler.addInPattern("%(rays)ft-into-%(prov)it")
        self.cHandler.addOutPattern("%(rays)ft-out-%(prov)it")

        self.cHandler.addAgainPattern("ray_again_all%(""rays"")fh%(""prov"")ih")

        self.DO=DirectObject()

        self.DO.accept('ray1-into-city', self.collideInBuilding)
        self.DO.accept('ray1-out-city', self.collideOutBuilding)

        self.DO.accept('ray_again_all', self.collideAgainstBuilds)

        self.pickingEnabledOject=None

        self.DO.accept('mouse1', self.mouseClick, ["down"])
        self.DO.accept('mouse1-up', self.mouseClick, ["up"])

    def camera_control(self):
        base.disableMouse()

        self.camera = base.camera

        self.cam_speed = 3
        self.cam_drag = 0.01

        self.cam_x_moving = False
        self.cam_y_moving = False
        self.cam_z_moving = False

        self.cam_x_inc = 0
        self.cam_y_inc = 0
        self.cam_z_inc = 0

        self.cameraDistance = -50
        self.camHeight = 25


        self.camXAngle = 0
        self.camYAngle = -25
        self.camZAngle = 0

        self.camX = 0
        self.camY = 0
        self.camZ = 100

    def camera_update(self,task):

        if self.cam_x_moving:
            self.camX+=self.cam_x_inc
        elif self.cam_x_inc != 0:
            if (self.cam_x_inc > 0 and self.cam_x_inc-self.cam_drag <= 0) or (self.cam_x_inc < 0 and self.cam_x_inc+self.cam_drag >= 0):
                self.cam_x_inc = 0
            elif self.cam_x_inc > 0:
                self.cam_x_inc -= self.cam_drag
            elif self.cam_x_inc < 0:
                self.cam_x_inc -= self.cam_drag
            else:
                print "FUCKUP WITH CAM X INC"

        if self.cam_y_moving:
            self.camY+=self.cam_y_inc
        elif self.cam_y_inc != 0:
            if (self.cam_y_inc > 0 and self.cam_y_inc-self.cam_drag <= 0) or (self.cam_y_inc < 0 and self.cam_y_inc+self.cam_drag >= 0):
                self.cam_y_inc = 0
            elif self.cam_y_inc > 0:
                self.cam_y_inc -= self.cam_drag
            elif self.cam_y_inc < 0:
                self.cam_y_inc -= self.cam_drag
            else:
                print "FUCKUP WITH CAM Y INC"

        if self.cam_z_moving:
            self.camZ+=self.cam_z_inc
        elif self.cam_z_inc != 0:
            if (self.cam_z_inc > 0 and self.cam_z_inc-self.cam_drag <= 0) or (self.cam_z_inc < 0 and self.cam_z_inc+self.cam_drag >= 0):
                self.cam_z_inc = 0
            elif self.cam_z_inc > 0:
                self.cam_z_inc -= self.cam_drag
            elif self.cam_z_inc < 0:
                self.cam_z_inc -= self.cam_drag
            else:
                print "FUCKUP WITH CAM Z INC"

        self.camera.setPos(self.camX, self.camY, self.camZ)
        self.camera.setHpr(self.camXAngle, self.camYAngle, self.camZAngle)

        return Task.cont

    def camera_move(self, status):
        if status == "up":
            self.cam_y_moving = True
            self.cam_y_inc = self.cam_speed
        if status == "down":
            self.cam_y_moving = True
            self.cam_y_inc = -self.cam_speed
        if status == "left":
            self.cam_x_moving = True
            self.cam_x_inc = -self.cam_speed
        if status == "right":
            self.cam_x_moving = True
            self.cam_x_inc = self.cam_speed
        if status == "stopX":
            self.cam_x_moving = False
        if status == "stopY":
            self.cam_y_moving = False

    def keyboard_setup(self):
        self.accept("w", self.keyW)
        self.accept("w-up", self.stop_y)
        self.accept("s", self.keyS)
        self.accept("s-up", self.stop_y)
        self.accept("a", self.keyA)

        self.accept("a-up", self.stop_x)
        self.accept("d", self.keyD)
        self.accept("d-up", self.stop_x)
        self.accept("+", self.ZoomIn)
        self.accept("c", self.createArmy)

    def createArmy(self):
        self.army_create()

    def ZoomIn(self):
        self.camZ -= 1

    def keyW( self ):
        self.camera_move("up")

    def keyS( self ):
        self.camera_move("down")

    def keyA( self ):
        self.camera_move("left")

    def keyD( self ):
        self.camera_move("right")

    def stop_x( self ):
        self.camera_move("stopX")

    def stop_y( self ):
        self.camera_move("stopY")

    def generate_models(self):
        for p in range(len(self.provs)):
            print "Making",self.provs[p]
            city = self.loader.loadModel("models/house2.x")
            city.reparentTo(self.render)
            city.setName(self.provs[p])
            city.setScale(2, 2, 2)
            x = float(self.provs_x[p]*self.terrainScale)
            y = 257*self.terrainScale-float(self.provs_y[p]*self.terrainScale)
            city.setPos(x, y, self.getObjectZ(x,y)-1)
            oCityCol = city.attachNewNode(CollisionNode("BuildingCNode%d"%p))
            oCityCol.setScale((3,3,3))
            oCityCol.node().addSolid(CollisionSphere(0,0,0,1))
            oCityCol.setTag("prov","city")
            city.setTag("id",str(p+1))
            #oCityCol.show()

    def collideInBuilding(self,entry):
        np_into=entry.getIntoNodePath()
        np_into.getParent().setColor(.6,.5,1.0,1)

    def collideOutBuilding(self,entry):

        np_into=entry.getIntoNodePath()
        np_into.getParent().setColor(1.0,1.0,1.0,1)

        self.pickingEnabledObject = None
        self.txtBox.setText("<No province>")

    def collideAgainstBuilds(self,entry):
        if entry.getIntoNodePath().getParent() <> self.pickingEnabledOject:
            np_from=entry.getFromNodePath()
            np_into=entry.getIntoNodePath()

            self.pickingEnabledObject = np_into.getParent()


            self.txtBox.setText(self.pickingEnabledObject.getName())

    def mouseClick(self,status):
        if self.pickingEnabledObject:
            if status == "down":
                self.pickingEnabledObject.setScale(0.95*2)
                print self.pickingEnabledObject.getTag("id"),self.provs[int(self.pickingEnabledObject.getTag("id"))-1]
                self.selected_prov = int(self.pickingEnabledObject.getTag("id"))-1
                self.update_interface()

            if status == "up":
                self.pickingEnabledObject.setScale(1.0*2)
        elif self.pickingEnabledObject == None:
            self.selected_prov = -1
            self.update_interface()

    def rayUpdate(self,task):
        if base.mouseWatcherNode.hasMouse():
            mpos = base.mouseWatcherNode.getMouse()

            self.pickerRay.setFromLens(base.camNode, mpos.getX(),mpos.getY())
        return task.cont

    def getObjectZ(self, x, y):
        if ((x > 0) and (x < 257) and (y > 0) and (y < 257)):
            return(self.terrain.getElevation(x,y)*self.terrainSize)
        else:
            return 0
    def format_colour_tuple(self,colour):
        col = string.split(colour)
        tuple = (int(col[0]),int(col[1]),int(col[2]),255)
        return tuple


    def drawTerrain(self):
        self.terrainSize = 5
        heightmap = "maps/italy_heightmap.png"
        colmap = self.TEXTURE_MAP



        self.terrain = GeoMipTerrain("terrain")
        self.terrain.setHeightfield(heightmap)
        self.terrain.setColorMap(colmap)

        self.terrain.setBlockSize(64)
        #self.terrain.setNear(40)
        #self.terrain.setFar(120)
        #self.terrain.setMinLevel(1)
        self.terrain.setBruteforce(True)

        self.terrain.generate()
        self.terrain.setAutoFlatten(self.terrain.AFMLight)

        self.root = self.terrain.getRoot()
        self.root.reparentTo(render)
        self.root.setSz(self.terrainSize)
        #self.root.setScale(self.terrainScale,self.terrainScale,1)



    def xml_load_map(self,file,type):
        if type == "WorldMap":
            tree = xml.parse(file)
            root = tree.getroot()

            self.provs = []
            self.provs_x = []
            self.provs_y = []
            self.provs_rgb = []
            self.provs_owner = []
            self.provs_money = []
            self.provs_men = []

            counter = 1
            for p in root.findall("province"):
                self.provs.append(self.get_tag(root,"province", counter, "name"))
                self.provs_x.append(self.get_tag(root, "province", counter, "x"))
                self.provs_y.append(self.get_tag(root, "province", counter, "y"))
                self.provs_rgb.append(self.get_tag(root, "province", counter, "rgb"))
                self.provs_owner.append(0)
                self.provs_money.append(0)
                self.provs_men.append(0)
                counter+=1
        elif type == "Scenario":
            tree = xml.parse(file)
            root = tree.getroot()
            self.day = 0
            self.month = 0
            self.year = 0
            self.adce = 0

            self.day = int(root.attrib["day"])
            self.month = int(root.attrib["month"])
            self.year = int(root.attrib["year"])

            self.nations = []
            self.nations_rgb = []
            self.nations_capital = []
            self.nations_money = []
            self.nations_men = []
            self.nations_provs_id = []

            counter = 0
            for p in root.findall("province"):
                print p.attrib["id"]

            for n in root.findall("nation"):
                for p in n.findall("province"):
                    self.provs_owner[int(p.attrib["id"])-1] = int(p.find("owner").text)
                    self.provs_money[int(p.attrib["id"])-1] = int(p.find("money").text)
                    self.provs_men[int(p.attrib["id"])-1] = int(p.find("men").text)
                    print self.provs_owner[int(p.attrib["id"])-1]
                    counter+=1
            counter = 1
            for n in root.findall("nation"):
                self.nations.append(self.get_tag(root, "nation", counter, "name"))
                self.nations_capital.append(n.attrib["capital"])
                #print self.nations_capital
                self.nations_rgb.append(self.get_tag(root, "nation", counter, "rgb"))
                self.nations_money.append(int(self.get_tag(root, "nation", counter, "money")))
                self.nations_men.append(int(self.get_tag(root, "nation", counter, "men")))
                counter += 1

    def get_tag(self,root,str_tag,prov_id, prov_tag):
        prov = root.find('.//'+str_tag+'[@id="'+str(prov_id)+'"]')
        tag = prov.find(prov_tag).text
        return tag
Ejemplo n.º 7
0
 def setup_keyboard(self, acceptor: DirectObject):
     acceptor.accept("g", self._toggle_grid)
     acceptor.accept("[", self._decrease_grid)
     acceptor.accept("]", self._increase_grid)
from direct.showbase import DirectObject
from direct.directnotify import DirectNotifyGlobal
from direct.distributed import DistributedObject
from direct.task import Task
from direct.distributed import DoInterestManager
from otp.distributed.OtpDoGlobals import *
_ToonTownDistrictStatInterest = None
_ToonTownDistrictStatInterestComplete = 0
_trashObject = DirectObject.DirectObject()

def EventName():
    return 'ShardPopulationSet'


def isOpen():
    global _ToonTownDistrictStatInterest
    return _ToonTownDistrictStatInterest is not None


def isComplete():
    global _ToonTownDistrictStatInterestComplete
    return _ToonTownDistrictStatInterestComplete


def open(event = None):
    global _trashObject
    global _ToonTownDistrictStatInterest
    if not isOpen():

        def _CompleteProc(event):
            global _ToonTownDistrictStatInterestComplete
Ejemplo n.º 9
0
class StrategyGame(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)
        base.disableMouse()

        self.map_scale = 1
        wp = WindowProperties()
        wp.setFullscreen(True)

        self.win_width = 1920
        self.win_height = 1080
        wp.setSize(self.win_width, self.win_height)
        base.win.requestProperties(wp)

        self.msg = []
        self.msg_path = []
        self.msg_y = []
        self.msg_alpha = []
        self.msg_delay = 3.0
        self.msg_fadetime = 5.0
        self.pickingEnabledObject = None
        self.prov_selected = -1

        self.scenario = "scenarios/wellington/wellington_wars.xml"
        loading_screen = "textures/loading.jpg"
        self.load_image = OnscreenImage(image = loading_screen, scale = (1920.0/1080.0,1,1))
        self.load_text = OnscreenText(text="Initialising...", pos = (0,-0.45,0))
        self.load_state = "Initialisation..."
        #self.load_state = "Done!"

        taskMgr.add(self.task_loading,"LoadingTask")
        taskMgr.doMethodLater(1.0,self.xml_scen_load,"xmlload")

        self.cam = TimCam()

        self.mess_count = 0
        self.accept("space", self.messaging)


        #self.message_create("Howdy")
        taskMgr.add(self.task_messages,"MessagesTask")

    def init_collisions(self):
        base.cTrav = CollisionTraverser()
        self.cHandler = CollisionHandlerEvent()

        pickerNode = CollisionNode("mouseRayNode")
        pickerNPos = base.camera.attachNewNode(pickerNode)
        self.pickerRay = CollisionRay()
        pickerNode.addSolid(self.pickerRay)

        pickerNode.setTag("rays","ray1")
        base.cTrav.addCollider(pickerNPos, self.cHandler)

        self.cHandler.addInPattern("%(rays)ft-into-%(prov)it")
        self.cHandler.addOutPattern("%(rays)ft-out-%(prov)it")

        self.cHandler.addAgainPattern("ray_again_all%(""rays"")fh%(""prov"")ih")

        self.DO=DirectObject()

        self.DO.accept('ray1-into-city', self.collideInBuilding)
        self.DO.accept('ray1-out-city', self.collideOutBuilding)

        self.DO.accept('ray_again_all', self.collideAgainstBuilds)

        self.pickingEnabledOject=None

        self.DO.accept('mouse1', self.mouseClick, ["down"])
        self.DO.accept('mouse1-up', self.mouseClick, ["up"])

        taskMgr.add(self.rayUpdate, "updatePicker")

    def collideInBuilding(self,entry):
        np_into=entry.getIntoNodePath()
        np_into.getParent().setColor(.6,.5,1.0,1)

    def collideOutBuilding(self,entry):

        np_into=entry.getIntoNodePath()
        np_into.getParent().setColor(1.0,1.0,1.0,1)

        self.pickingEnabledObject = None

    def collideAgainstBuilds(self,entry):
        if entry.getIntoNodePath().getParent() <> self.pickingEnabledOject:
            np_from=entry.getFromNodePath()
            np_into=entry.getIntoNodePath()

            self.pickingEnabledObject = np_into.getParent()

    def mouseClick(self,status):
        if self.pickingEnabledObject:
            if status == "down":
                self.pickingEnabledObject.setScale(0.95*2)
                self.prov_selected = int(self.pickingEnabledObject.getTag("id"))
                self.message_create("You clicked on "+self.provinces[int(self.pickingEnabledObject.getTag("id"))][0])
                self.interface_update()

            if status == "up":
                self.pickingEnabledObject.setScale(1.0*2)
        elif self.pickingEnabledObject == None:
            self.prov_selected = -1
            self.interface_update()

    def rayUpdate(self,task):
        if base.mouseWatcherNode.hasMouse():
            mpos = base.mouseWatcherNode.getMouse()

            self.pickerRay.setFromLens(base.camNode, mpos.getX(),mpos.getY())
        return task.cont

    def interface_update(self):
        if self.prov_selected != -1:
            texture = loader.loadTexture("textures/interface_prov.png")
            self.interface_card.setTexture(texture)
            self.lbl_prov_name.setText(self.provinces[self.prov_selected][0])
            if self.provinces[self.prov_selected][4] != None:
                self.inter_img.setTexture(self.provinces[self.prov_selected][4])
            else:
                texture = loader.loadTexture("textures/planet.jpg")
                self.inter_img.setTexture(texture)
            self.inter_img.show()
        else:
            texture = loader.loadTexture("textures/interface_background.png")
            self.interface_card.setTexture(texture)
            self.lbl_prov_name.setText("")
            texture = loader.loadTexture("textures/planet.jpg")
            self.inter_img.setTexture(texture)
            self.inter_img.hide()



    def interface_draw(self):
        interface_scale = 2
        self.interface_card = self.draw_card_pixel("textures/interface_background.png",
                                                   (self.win_width)/2-(250*interface_scale),self.win_height-(128*interface_scale),
                                                   500*interface_scale,128*interface_scale)
        self.lbl_prov_name = self.label_create("",(1,1,1,1),
                                               (self.win_width)/2-((250-20)*interface_scale),
                                               self.win_height-((128-24)*interface_scale),10*interface_scale)
        self.inter_img = self.draw_card_pixel("textures/planet.jpg",(self.win_width)/2-((250-20)*interface_scale),
                                              self.win_height-((128-37)*interface_scale),
                                              76*interface_scale,76*interface_scale)
        self.inter_img.hide()

    def label_create(self,text,colour,x,y,scale):
        text_node = TextNode("MessageNode")
        text_node.setText(text)
        text_node_path = pixel2d.attachNewNode(text_node)
        text_node_path.setPos(x,0,-y)
        text_node_path.setScale(scale)
        text_node.setTextColor(colour)
        text_node.setAlign(TextNode.ALeft)
        return text_node

    def messaging(self):
        if self.mess_count < len(self.message_list):
            self.message_create(self.message_list[self.mess_count])
            self.mess_count += 1
        else:
            self.message_create(self.message_list[len(self.message_list)-1])
            self.mess_count = 0

    def task_loading(self,task):
        self.load_text.setText(self.load_state)
        if self.load_state == "Done!":
            self.interface_draw()
            self.message_list = []
            for p in range(len(self.provinces)):
                self.message_list.append(self.provinces[p+1][0]+" has been invaded by the enemy!")
            for m in range(len(self.message_list)):
                self.message_create(self.message_list[m])
            self.load_image.destroy()
            self.load_text.destroy()
            return task.done
        else:
            return task.cont

    def task_messages(self,task):
        task.delayTime = 1.0
        for m in range(len(self.msg_path)):
            if self.msg_path[m].getColorScale() == VBase4(1,1,1,0):
                # FIND A WAY TO KILL self.msg[m]
                # FIND A WAY TO KILL self.msg_path[m]
                self.msg_path.remove(self.msg_path[m])
                self.msg.remove(self.msg[m])
                self.msg_y.remove(self.msg_y[m])
                return task.cont
        return task.again



    def draw_card(self,renderer,pLL,pLR,pUR,pUL):
        cm = CardMaker("CardMaker")
        cm.setFrame(pLL,pLR,pUR,pUL)
        card = renderer.attachNewNode(cm.generate())
        card.clearColor()
        return (card)

    def draw_card_pixel(self,tex,x,y,width,height):
        cm = CardMaker("CardMaker")
        cm.setFrame(0,width,-height,0)
        card = pixel2d.attachNewNode(cm.generate())
        card.setTransparency(TransparencyAttrib.MAlpha)
        card.clearColor()
        texture = loader.loadTexture(tex)
        card.setTexture(texture)
        card.setPos(x,0,-y)
        return (card)

    def map_create(self,task):
        im = Image.open(self.map_region)
        pix = im.load()
        print im.getcolors()
        width,height = im.size
        aspect = width/height
        print width,height,aspect
        width *= self.map_scale
        height *= self.map_scale

        map = self.draw_card(render,(width/2,height/2,0),(-width/2,height/2,0),(-width/2,-height/2,0),(width/2,-height/2,0))
        map.setHpr(180,0,0)
        map.setTransparency(TransparencyAttrib.MAlpha)

        tex = loader.loadTexture(self.map_texture)
        map.setTexture(tex)

        z=1
        reg = self.draw_card(render,(width/2,height/2,z),(-width/2,height/2,z),(-width/2,-height/2,z),(width/2,-height/2,z))
        reg.setHpr(180,0,0)
        reg.setTransparency(TransparencyAttrib.MAlpha)

        size = width,height
        self.nat_map = Image.new("RGBA",size,(255,255,255,0))
        self.nat_map_pix = self.nat_map.load()
        #for x in range(width):
        #    for y in range(height):
        #        if pix[x,y][3] != 0 and pix[x,y] != (0,0,0,255):
        #            prov_from_col = self.get_prov_from_col(pix[x,y])
        #            self.nat_map_pix[x,y] = self.get_col_from_rgb(self.nations[self.provinces[prov_from_col][7]][1])
        self.nat_map.save("nat_map.png","PNG")

        tex_reg = loader.loadTexture("nat_map.png")
        reg.setTexture(tex_reg)
        reg.setAlphaScale(0.3)

        self.map_width = width
        self.map_height = height

        self.load_state = "Populating World..."
        taskMgr.doMethodLater(1.0,self.map_populate,"mappop")

        return task.done

    def get_col_from_rgb(self,rgb):
        col = string.split(rgb)
        return (int(col[0]),int(col[1]),int(col[2]),255)

    def get_prov_from_col(self,colour):
        found = False
        for p in range(len(self.provinces)):
            if self.get_col_from_rgb(self.provinces[p+1][1]) == colour:
                found = True
                return p+1
        if found == False:
            print "##ERROR FINDING PROV FROM COL "+str(colour)+"##"

    def map_populate(self,task):
        self.init_collisions()
        for p in range(len(self.provinces)):
            city = loader.loadModel("models/house2.x")
            city.reparentTo(render)
            city.setName(self.provinces[p+1][0])
            city.setScale(2, 2, 2)
            x = float(self.provinces[p+1][2]*self.map_scale)-(self.map_width/2)
            y = self.map_height-float(self.provinces[p+1][3]*self.map_scale)-(self.map_height/2)
            city.setPos(x, y, 1.0)
            city_col = city.attachNewNode(CollisionNode("CityCNode%d"%p))
            city_col.setScale((3,3,3))
            city_col.node().addSolid(CollisionSphere(0,0,0,1))
            city_col.setTag("prov","city")
            city.setTag("id",str(p+1))
        for p in range(len(self.paths)):
            path_split = string.replace(self.paths[p],"-"," ")
            path_split = string.split(path_split)
            prov_a = int(path_split[0])
            prov_b = int(path_split[1])
            line = LineSegs()
            line.setColor(1, 0, 0, 1)
            line.setThickness(5)
            line.moveTo(self.provinces[prov_a][2]-600, -(self.provinces[prov_a][3])+350, 2)
            line.drawTo(self.provinces[prov_b][2]-600, -(self.provinces[prov_b][3])+350, 2)

            node = line.create()
            node_path = NodePath(node)
            node_path.reparentTo(render)
            print "line drawn",self.provinces[prov_a][2],self.provinces[prov_a][3]
        for a in range(len(self.armies)):
            self.army_create(a+1,self.armies[a+1][2])

        self.load_state = "Done!"
        task.done

    def army_create(self,army_id,location):
        #self.provinces[location][8].append(army_id)
        x = float(self.provinces[location][2]*self.map_scale)-(self.map_width/2)
        y = self.map_height-float(self.provinces[location][3]*self.map_scale)-(self.map_height/2)
        army = loader.loadModel("models/man.x")
        army.reparentTo(render)
        army.setName(self.armies[army_id][0])
        army.setPos(x, y, 1.0)

    def message_create(self,text):
        msg_height = 17

        text_node = TextNode("MessageNode")
        text_node.setText(text)
        text_node_path = pixel2d.attachNewNode(text_node)
        text_node_path.setPos(0,0,-msg_height)
        text_node_path.setScale(15)
        text_node.setTextColor(0.8, 0.1, 0.1, 1)
        text_node.setAlign(TextNode.ALeft)

        for m in range(len(self.msg)):
                self.msg_y[m] -= msg_height
                self.msg_path[m].setPos(0,0,self.msg_y[m])
        self.msg.insert(0,text_node)
        self.msg_path.insert(0,text_node_path)
        self.msg_y.insert(0,-msg_height)

        fadeOut = LerpColorScaleInterval(text_node_path, self.msg_fadetime, VBase4(1,1,1,0), VBase4(1,1,1,1))
        para = Sequence(Wait(self.msg_delay), fadeOut)
        para.start()

    def xml_scen_load(self,task):
        tree = xml.parse(self.scenario)
        root = tree.getroot()

        self.map_region = root.attrib["region_map"]
        self.map_texture = root.attrib["texture_map"]

        self.day = (int(root.find("date/day").text))
        self.month = (int(root.find("date/month").text))
        self.year = (int(root.find("date/year").text))

        self.provinces = {}
        self.nations = {}
        self.armies = {}
        self.paths = []
        for p in root.findall("province"):
            if (p.find("image") != None):
                self.provinces[int(p.attrib["id"])] = [p.find("name").text,p.find("rgb").text,int(p.find("x").text),int(p.find("y").text),
                                                       loader.loadTexture(p.find("image").text),float(p.find("coin").text),float(p.find("men").text),int(p.attrib["owner"]),[]]
            else:
                self.provinces[int(p.attrib["id"])] = [p.find("name").text,p.find("rgb").text,int(p.find("x").text),int(p.find("y").text),
                                                       None,float(p.find("coin").text),float(p.find("men").text),int(p.attrib["owner"]),[]]
        print self.provinces

        for n in root.findall("nation"):
            if (n.find("flag") != None):
                self.nations[int(n.attrib["id"])] = [n.find("name").text,n.find("rgb").text,int(n.find("capital").text),int(n.find("coin").text),int(n.find("men").text),[],
                                                       loader.loadTexture(n.find("flag").text)]
            else:
                self.nations[int(n.attrib["id"])] = [n.find("name").text,n.find("rgb").text,int(n.find("capital").text),int(n.find("coin").text),int(n.find("men").text),[],
                                                       None]
        print self.nations

        for a in root.findall("army"):            #0:Name 1:Home 2:Location 3:Inf 4:Arch 5:Cav 6:x 7:y
            self.armies[int(a.attrib["id"])] = [a.find("name").text,int(a.find("home").text),int(a.find("location").text),
                                                int(a.find("infantry").text),int(a.find("archers").text),int(a.find("cavalry").text),"node"]
        print self.armies

        for pth in root.findall("paths/path"):
            self.paths.append(pth.attrib["name"])
        print self.paths

        im = Image.open(self.map_region)
        self.region_pix = im.load()
        self.region_width,self.region_height = im.size

        self.load_state = "Creating World..."
        #self.load_state = "Done!"
        taskMgr.doMethodLater(1.0,self.map_create,"mapcreate")
        task.done
Ejemplo n.º 10
0
class PirateMemberList(DirectObject):
    def __init__(self,
                 numShown,
                 parent,
                 title=None,
                 height=0.59999999999999998,
                 memberHeight=0.065000000000000002,
                 memberOffset=0.021000000000000001,
                 memberWidth=0.45000000000000001,
                 bottom=0,
                 hud=False,
                 width=0.47999999999999998,
                 sort=0):
        if hasattr(self, 'initialized'):
            self.arrangeMembers()
            return None

        self.shown = numShown
        self.memberHeight = memberHeight
        self.memberWidth = memberWidth
        self.memberOffset = memberOffset
        self.title = title
        self.wantSortButtons = sort
        self.width = width
        self.bottom = bottom
        self.height = height
        self.hud = hud
        self.baseFrame = DirectFrame(relief=None, parent=parent)
        if self.hud:
            self.baseFrame['state'] = DGG.DISABLED

        self.members = []
        self.memberAvatarDict = {}
        self.memberPlayerDict = {}
        self.onlineCheckTaskName = base.cr.specialName(
            'memberList_checkLastOnline')
        self.prearrangeTaskName = base.cr.specialName(
            'memberList_prearrangeMembers')
        self.onlineChangeEvent = base.cr.specialName('memberList_onlineChange')
        self.setup()
        self.arrangeMembers()
        self.initialized = 1
        self.show()
        self.sortMode = 'Name'
        self.onlineDataProbe = DirectObject()
        self.onlineCount = 0

    def mouseWheelUp(self, task=None):
        if len(self.members) > self.shown:
            amountScroll = self.shown / 1.0 * len(self.members)
            self.memberFrame.verticalScroll['value'] -= amountScroll

    def mouseWheelDown(self, task=None):
        if len(self.members) > self.shown:
            amountScroll = self.shown / 1.0 * len(self.members)
            self.memberFrame.verticalScroll['value'] += amountScroll

    def countMembers(self):
        return len(self.members)

    def show(self):
        self.baseFrame.show()
        self.accept('press-wheel_up-%s' % self.memberFrame.guiId,
                    self.mouseWheelUp)
        self.accept('press-wheel_down-%s' % self.memberFrame.guiId,
                    self.mouseWheelDown)
        self.accept(
            'press-wheel_up-%s' % self.memberFrame.verticalScroll.guiId,
            self.mouseWheelUp)
        self.accept(
            'press-wheel_down-%s' % self.memberFrame.verticalScroll.guiId,
            self.mouseWheelDown)
        self.accept(
            'press-wheel_up-%s' % self.memberFrame.verticalScroll.thumb.guiId,
            self.mouseWheelUp)
        self.accept(
            'press-wheel_down-%s' %
            self.memberFrame.verticalScroll.thumb.guiId, self.mouseWheelDown)
        self.accept(
            'press-wheel_up-%s' %
            self.memberFrame.verticalScroll.incButton.guiId, self.mouseWheelUp)
        self.accept(
            'press-wheel_down-%s' %
            self.memberFrame.verticalScroll.incButton.guiId,
            self.mouseWheelDown)
        self.accept(
            'press-wheel_up-%s' %
            self.memberFrame.verticalScroll.decButton.guiId, self.mouseWheelUp)
        self.accept(
            'press-wheel_down-%s' %
            self.memberFrame.verticalScroll.decButton.guiId,
            self.mouseWheelDown)
        self.accept('socailPanelWheelUp', self.mouseWheelUp)
        self.accept('socailPanelWheelDown', self.mouseWheelDown)

    def hide(self):
        self.baseFrame.hide()
        self.ignoreAll()

    def destroy(self):
        taskMgr.remove(self.onlineCheckTaskName)
        taskMgr.remove(self.prearrangeTaskName)
        self.onlineDataProbe.ignore(base.cr.statusDatabase.avatarDoneTaskName)
        self.ignoreAll()
        for member in self.members:
            member.detachNode()
            member.destroy()

        self.memberAvatarDict = {}
        self.memberPlayerDict = {}
        self.members = []
        self.baseFrame.destroy()

    def setPos(self, x, y, z):
        self.baseFrame.setPos(x, y, z)

    def setup(self):
        charGui = loader.loadModel('models/gui/char_gui')
        knob = (charGui.find('**/chargui_slider_node'),
                charGui.find('**/chargui_slider_node_down'),
                charGui.find('**/chargui_slider_node_over'))
        self.memberFrame = DirectScrolledFrame(
            parent=self.baseFrame,
            relief=None,
            state=DGG.NORMAL,
            manageScrollBars=0,
            autoHideScrollBars=1,
            frameSize=(0, self.width, self.bottom, self.height),
            canvasSize=(0, self.width - 0.050000000000000003,
                        self.bottom + 0.025000000000000001,
                        self.height - 0.025000000000000001),
            verticalScroll_relief=None,
            verticalScroll_frameSize=(0, PiratesGuiGlobals.ScrollbarSize,
                                      self.bottom, self.height),
            verticalScroll_image=charGui.find('**/chargui_slider_small'),
            verticalScroll_image_scale=((self.height - self.bottom) +
                                        0.050000000000000003, 1, 0.75),
            verticalScroll_image_hpr=(0, 0, 90),
            verticalScroll_image_pos=(self.width -
                                      PiratesGuiGlobals.ScrollbarSize * 0.5 -
                                      0.0, 0,
                                      (self.bottom + self.height) * 0.5),
            verticalScroll_image_color=(0.60999999999999999,
                                        0.59999999999999998,
                                        0.59999999999999998, 1),
            verticalScroll_thumb_image=knob,
            verticalScroll_thumb_relief=None,
            verticalScroll_thumb_image_scale=0.29999999999999999,
            verticalScroll_resizeThumb=0,
            horizontalScroll_relief=None,
            sortOrder=5)
        if self.hud:
            self.memberFrame['state'] = DGG.DISABLED

        self.memberFrame.verticalScroll.incButton.destroy()
        self.memberFrame.verticalScroll.decButton.destroy()
        self.memberFrame.horizontalScroll.incButton.destroy()
        self.memberFrame.horizontalScroll.decButton.destroy()
        self.memberFrame.horizontalScroll.hide()
        self.memberFrame.show()
        charGui = loader.loadModel('models/gui/toplevel_gui')
        buttonImage = (charGui.find('**/generic_button'),
                       charGui.find('**/generic_button_down'),
                       charGui.find('**/generic_button_over'),
                       charGui.find('**/generic_button_disabled'))
        if self.wantSortButtons:
            sortButtonWidth = self.memberWidth
            nameProp = 0.75
            nameSize = nameProp * sortButtonWidth
            onlineProp = 0.25
            onlineSize = onlineProp * sortButtonWidth
            levelSize = 0.0
            sortNameButton = DirectButton(
                parent=self.memberFrame,
                relief=None,
                image=buttonImage,
                image_scale=(nameSize, 1.0, 0.14999999999999999),
                image0_color=VBase4(0.65000000000000002, 0.65000000000000002,
                                    0.65000000000000002, 1),
                image1_color=VBase4(0.40000000000000002, 0.40000000000000002,
                                    0.40000000000000002, 1),
                image2_color=VBase4(0.90000000000000002, 0.90000000000000002,
                                    0.90000000000000002, 1),
                image3_color=VBase4(0.40999999999999998, 0.40000000000000002,
                                    0.40000000000000002, 1),
                text='Name',
                text_align=TextNode.ACenter,
                text_pos=(0, -0.01),
                text_scale=PiratesGuiGlobals.TextScaleMed,
                text_fg=PiratesGuiGlobals.TextFG2,
                text_shadow=PiratesGuiGlobals.TextShadow,
                pos=(nameSize * 0.5, 0, self.height + 0.040000000000000001),
                command=self.sortByName)
            sortNameButton.show()
            sortOnlineButton = DirectButton(
                parent=self.memberFrame,
                relief=None,
                image=buttonImage,
                image_scale=(onlineSize, 1.0, 0.14999999999999999),
                image0_color=VBase4(0.65000000000000002, 0.65000000000000002,
                                    0.65000000000000002, 1),
                image1_color=VBase4(0.40000000000000002, 0.40000000000000002,
                                    0.40000000000000002, 1),
                image2_color=VBase4(0.90000000000000002, 0.90000000000000002,
                                    0.90000000000000002, 1),
                image3_color=VBase4(0.40999999999999998, 0.40000000000000002,
                                    0.40000000000000002, 1),
                text='Online',
                text_align=TextNode.ACenter,
                text_pos=(0, -0.01),
                text_scale=PiratesGuiGlobals.TextScaleMed,
                text_fg=PiratesGuiGlobals.TextFG2,
                text_shadow=PiratesGuiGlobals.TextShadow,
                pos=(onlineSize * 0.5 + nameSize + levelSize, 0,
                     self.height + 0.040000000000000001),
                command=self.sortByOnline)
            sortOnlineButton.show()

        charGui.removeNode()

    def sortByName(self):
        self.sortMode = 'Name'
        self.arrangeMembers()

    def sortByOnline(self):
        self.sortMode = 'Online'
        self.arrangeMembers()

    def getMemberByAvId(self, avId):
        for member in self.members:
            if avId and member.avId == avId:
                return member
                continue

    def getMemberByPlayerId(self, playerId):
        for member in self.members:
            if playerId and member.playerId == playerId:
                return member
                continue

    def removeNotOnAvList(self, cullAvList):
        for member in self.members:
            if member.avId not in cullAvList:
                self.removeMember(member.avId, member.playerId, member.mode)
                continue

    def updateOrAddMember(self, avId, playerId, mode, modeInfo=None):
        tryAv = self.memberAvatarDict.get(avId)
        tryPlayer = self.memberPlayerDict.get(playerId)
        if tryAv and tryAv.isEmpty():
            if tryAv in self.members:
                self.members.remove(tryAv)

            tryAv = None
            del self.memberAvatarDict[avId]

        if tryPlayer and tryPlayer.isEmpty():
            if tryPlayer in self.members:
                self.members.remove(tryPlayer)

            tryPlayer = None
            del self.memberPlayerDict[playerId]

        if tryAv:
            if tryAv.mode == mode:
                self.updateMemberInfo(avId, playerId, mode, modeInfo)
            elif mode == MODE_FRIEND_AVATAR and tryAv.mode == MODE_FRIEND_PLAYER_AVATAR:
                self.addMember(avId, playerId, mode, modeInfo)
            elif mode == MODE_FRIEND_PLAYER_AVATAR and tryAv.mode == MODE_FRIEND_AVATAR:
                return None

        elif tryPlayer and tryPlayer.mode == mode:
            self.updateMemberInfo(avId, playerId, mode, modeInfo)
        else:
            self.addMember(avId, playerId, mode, modeInfo)

    def updateMemberInfo(self, avId, playerId, mode, modeInfo=None):
        tryAv = self.memberAvatarDict.get(avId)
        tryPlayer = self.memberPlayerDict.get(playerId)
        member = None
        if tryAv and tryAv.mode == mode:
            member = tryAv
        elif tryPlayer and tryPlayer.mode == mode:
            member = tryPlayer

        if member:
            member.update(modeInfo)
            self.prearrangeMembers()

    def addMember(self, avId, playerId, mode, modeInfo=None, fromClearList=0):
        if mode == MODE_FRIEND_AVATAR:
            someMember = self.getMemberByPlayerId(playerId)
            if someMember:
                playerId = someMember.playerId

        if mode == MODE_FRIEND_PLAYER_AVATAR:
            avId = base.cr.playerFriendsManager.findAvIdFromPlayerId(playerId)

        if self.memberAvatarDict.get(avId) or self.memberPlayerDict.get(
                playerId):
            self.removeMember(avId, playerId, mode)

        texcolor = (0.90000000000000002, 1, 0.90000000000000002, 1)
        fcolor = PiratesGuiGlobals.ButtonColor5
        addMe = PirateMemberButton(self, avId, playerId, mode, modeInfo)
        self.members.append(addMe)
        if avId:
            self.memberAvatarDict[avId] = addMe

        if playerId:
            self.memberPlayerDict[playerId] = addMe

        if mode == MODE_GUILD and len(self.members) > 0:
            self.accept('guildMemberOnlineStatus',
                        self.updateGuildMemberOnline)

        taskMgr.remove(self.onlineCheckTaskName)
        task = taskMgr.doMethodLater(1.0, self.requestLastOnlineTimes,
                                     self.onlineCheckTaskName)
        self.onlineDataProbe.ignore(base.cr.statusDatabase.avatarDoneTaskName)
        self.onlineDataProbe.accept(base.cr.statusDatabase.avatarDoneTaskName,
                                    self.updateOnlineData)
        self.prearrangeMembers()
        return addMe

    def addPotentialMember(self, avId, avName, mode):
        self.removeMember(avId, None, mode)
        texcolor = (0.90000000000000002, 1, 0.90000000000000002, 1)
        fcolor = PiratesGuiGlobals.ButtonColor5
        addMe = PirateMemberButton(self, avId, None, mode, name=avName)
        self.members.append(addMe)
        self.memberAvatarDict[avId] = addMe
        self.prearrangeMembers()
        if mode == MODE_GUILD and len(self.members) > 0:
            self.accept('guildMemberOnlineStatus',
                        self.updateGuildMemberOnline)

        taskMgr.remove(self.onlineCheckTaskName)
        task = taskMgr.doMethodLater(1.0, self.requestLastOnlineTimes,
                                     self.onlineCheckTaskName)
        self.onlineDataProbe.ignore(base.cr.statusDatabase.avatarDoneTaskName)
        self.onlineDataProbe.accept(base.cr.statusDatabase.avatarDoneTaskName,
                                    self.updateOnlineData)
        return addMe

    def removeMember(self, avId, playerId, mode):
        removedAvId = None
        removedPlayerId = None
        if not playerId and avId:
            avMemeber = self.memberAvatarDict.get(avId)
            if avMemeber:
                playerId = avMemeber.playerId

        elif playerId and not avId:
            playerMemeber = self.memberPlayerDict.get(avId)
            if playerMemeber:
                avId = playerMemeber.playerId

        if avId:
            removeMe = self.memberAvatarDict.get(avId)
            removedAvId = avId
            if removeMe:
                removedPlayerId = removeMe.playerId
                if removeMe in self.members:
                    self.members.remove(removeMe)

                removeMe.detachNode()
                removeMe.destroy()
                del self.memberAvatarDict[avId]

        if playerId:
            removeMe = self.memberPlayerDict.get(playerId)
            removedPlayerId = playerId
            if removeMe:
                removedAvId = removeMe.avId
                if removeMe in self.members:
                    self.members.remove(removeMe)

                removeMe.detachNode()
                removeMe.destroy()
                del self.memberPlayerDict[playerId]

        if mode == MODE_GUILD and len(self.members) == 0:
            self.ignore('guildMemberOnlineStatus')

        self.prearrangeMembers()
        return (removedAvId, removedPlayerId)

    def removeMemberWithRefill(self, avId, playerId, mode):
        self.removeMember(avId, playerId, mode)
        if mode in (MODE_FRIEND_AVATAR, MODE_FRIEND_PLAYER_AVATAR):
            self.refillMember(avId, playerId, mode)

    def refillMember(self, avId, playerId, mode):
        if mode == MODE_FRIEND_AVATAR:
            if playerId and base.cr.playerFriendsManager.isFriend(playerId):
                info = base.cr.playerFriendsManager.getFriendInfo(playerId)
                self.updateOrAddMember(None, playerId,
                                       MODE_FRIEND_PLAYER_AVATAR, info)

        elif mode == MODE_FRIEND_PLAYER_AVATAR:
            if avId and base.cr.avatarFriendsManager.isFriend(avId):
                info = base.cr.avatarFriendsManager.getFriendInfo(avId)
                self.updateOrAddMember(avId, None, MODE_FRIEND_AVATAR, info)

    def requestLastOnlineTimes(self, task):
        memberIds = []
        for member in self.members:
            if member.avId:
                memberIds.append(member.avId)
                continue

        base.cr.statusDatabase.queueOfflineAvatarStatus(memberIds)
        self.accept(base.cr.statusDatabase.avatarDoneTaskName,
                    self.updateOnlineData)
        return task.done

    def updateOnlineData(self):
        for member in self.members:
            if member.avId:
                onlineTime = base.cr.statusDatabase.avatarData.get(member.avId)
                if onlineTime:
                    member.updateOnlineTime(onlineTime)

    def updateGuildMemberOnline(self, avId, onlineStatus):
        for member in self.members:
            if member.avId == avId:
                member.modeInfo[3] = onlineStatus
                member.update()
                continue

    def updateGuildMemberRank(self, avId, rank):
        for member in self.members:
            if member.avId == avId:
                member.updateGuildRank(rank)
                continue

    def updateAll(self):
        for member in self.members:
            member.update()

    def updateAv(self, avId):
        member = self.memberAvatarDict.get(avId)
        if member:
            member.update()

    def prearrangeMembers(self):
        taskMgr.remove(self.prearrangeTaskName)
        taskMgr.doMethodLater(0.10000000000000001, self.arrangeMembers,
                              self.prearrangeTaskName)

    def arrangeMembers(self, task=None):
        numMembers = len(self.members)
        if numMembers == 0:
            return None

        self.members.sort(self.compareMembers)
        self.memberFrame['canvasSize'] = (0, 0.0, 0,
                                          numMembers * self.memberHeight)
        self.placement = self.memberHeight * numMembers
        for index in range(numMembers):
            self.placement -= self.memberHeight
            self.members[index].setPos(self.memberWidth * 0.5 - 0.0, 0,
                                       self.placement)

        self.updateAll()
        taskMgr.remove(self.prearrangeTaskName)
        if task:
            return task.done

    def getSize(self):
        return len(self.members)

    def clearMembers(self):
        for member in self.members:
            member.detachNode()
            member.destroy()

        self.members = []
        self.memberAvatarDict = {}
        self.memberPlayerDict = {}
        self.onlineCount = 0

    def compareMembers(self, first, other):
        if other is None:
            return -1

        if first.online and not (other.online):
            return -1
        elif not (first.online) and other.online:
            return 1

        if first.mode == MODE_CREW and first.mode == MODE_CREW_HUD or first.mode == MODE_CREW_HUD_SEA:
            if not hasattr(other, 'modeInfo') or not (other.modeInfo):
                return 1
            elif first.modeInfo:
                if first.modeInfo.isManager:
                    return -1
                elif other.modeInfo.isManager:
                    return 1

        if first.mode == MODE_GUILD:
            if not hasattr(other, 'modeInfo') or not (other.modeInfo):
                return 1
            elif first.modeInfo:
                if first.modeInfo[2] in (2, 3) and other.modeInfo[2] == 4:
                    return -1
                elif first.modeInfo[2] == 4 and other.modeInfo[2] in (2, 3):
                    return 1
                elif first.modeInfo[2] > other.modeInfo[2]:
                    return -1
                elif first.modeInfo[2] < other.modeInfo[2]:
                    return 1

        if (first.mode == MODE_FRIEND_PLAYER
                or first.mode == MODE_FRIEND_PLAYER_AVATAR
            ) and first.mode == MODE_FRIEND_AVATAR:
            return -1
        elif first.mode == MODE_FRIEND_AVATAR:
            if first.mode == MODE_FRIEND_PLAYER or first.mode == MODE_FRIEND_PLAYER_AVATAR:
                return 1
            elif self.sortMode == 'Online':
                if first.lastOnline == None:
                    return 1
                elif other.lastOnline == None:
                    return -1
                elif first.lastOnline > other.lastOnline:
                    return -1

                return 1
            elif first.mode == MODE_FRIEND_PLAYER_AVATAR:
                text1 = first['text'][0]
            else:
                text1 = first['text']
        if other.mode == MODE_FRIEND_PLAYER_AVATAR:
            text2 = other['text'][0]
        else:
            text2 = other['text']
        return cmp(text1.lower(), text2.lower())