def getInfo(self, tran, obj): result = ISystem.getInfo(self, tran, obj) log.debug('there!'); result.type = obj.type result.name = obj.name result.destinationOid = obj.destinationOid return result
def getScanInfos(self, tran, obj, scanPwr, player): log.debug('Generating wormhole scan data',obj.oid) result = IDataHolder() results = [result] if scanPwr >= Rules.level1InfoScanPwr: result._type = Const.T_SCAN result.scanPwr = scanPwr result.oid = obj.oid result.x = obj.x result.y = obj.y result.signature = obj.signature result.type = obj.type result.compOf = obj.compOf result.starClass = obj.starClass result.destinationOid = obj.destinationOid if scanPwr >= Rules.level2InfoScanPwr: result.name = obj.name result.combatCounter = obj.combatCounter if scanPwr >= Rules.level4InfoScanPwr: result.fleets = obj.fleets for fleetID in obj.fleets: fleet = tran.db[fleetID] if fleet.owner == player: continue newPwr = scanPwr * fleet.signature / obj.signature results.extend(self.cmd(fleet).getScanInfos(tran, fleet, newPwr, player)) return results
def loadTechImg(techID): global techImgs # remove possible "shifts" techID = techID % 10000 # load image filename = os.path.join(Rules.rulesetPath, "icons", "%04d.png" % techID) log.debug("Loading icon for tech %d from %s" % (techID, filename)) if not os.path.exists(filename): return False img = pygame.image.load(filename).convert_alpha() techImgs[techID] = img # red variant red = pygame.Surface((37, 37)) red.fill((255, 0, 0)) red.set_alpha(64) tmpImg = img.convert_alpha() tmpImg.blit(red, (0, 0)) techImgs[techID + redShift] = tmpImg # white variant white = pygame.Surface((37, 37)) white.fill((255, 255, 255)) white.set_alpha(64) tmpImg = img.convert_alpha() tmpImg.blit(white, (0, 0)) techImgs[techID + whiteShift] = tmpImg return True
def processINITPhase(self, tran, obj, data): if not obj.timeEnabled: return # compute emr level turn = tran.db[Const.OID_UNIVERSE].turn # galaxy keeps track of it's own time (because of pauses) obj.galaxyTurn += 1 obj.emrTime -= 1 if obj.emrTime <= 0: modulo = turn % Rules.emrPeriod for season in Rules.emrSeasons: if modulo >= season.startTime and modulo <= season.endTime: log.debug("EMR - season", season.name) obj.emrTrend = Utils.rand(int(season.emrLevelMin * 100), int(season.emrLevelMax * 100) + 1) / 100.0 obj.emrTime = Utils.rand(Rules.emrMinDuration, Rules.emrMaxDuration) log.debug("EMR - trend, time", obj.emrTrend, obj.emrTime) message = { "sender": "GNC", "senderID": obj.oid, "forum": "NEWS", "data": (obj.oid, Const.MSG_GNC_EMR_FORECAST, obj.oid, turn, (obj.emrTrend, obj.emrTime)), "topic": "EVENT", } self.cmd(obj).sendMsg(tran, obj, message) break elif obj.emrLevel >= obj.emrTrend: obj.emrLevel -= Utils.rand(1, 6) / 100.0 elif obj.emrLevel <= obj.emrTrend: obj.emrLevel += Utils.rand(1, 6) / 100.0 # remove old messages self.cmd(obj).deleteOldMsgs(tran, obj) return obj.systems
def moveToWormhole(self, tran, obj, targetID): origin = tran.db[targetID] if not (obj.x==origin.x and obj.y==origin.y): if not self.cmd(obj).moveToTarget(tran, obj, targetID): return 0 #ship hasn't arrived # enter wormhole if origin.type == T_WORMHOLE: #is wormhole, now enter it! destinationWormHole = tran.db[origin.destinationOid] if destinationWormHole.oid == targetID: return 1 if obj.oid not in destinationWormHole.fleets: destinationWormHole.fleets.append(obj.oid) if obj.oid not in destinationWormHole.closeFleets: destinationWormHole.closeFleets.append(obj.oid) if obj.oid in origin.fleets: origin.fleets.remove(obj.oid) if obj.oid in origin.closeFleets: origin.closeFleets.remove(obj.oid) obj.closeSystem = destinationWormHole.oid log.debug('IFleet', 'Entering Wormhole - destination ', destinationWormHole.oid) obj.orbiting = destinationWormHole.oid obj.x = destinationWormHole.x obj.y = destinationWormHole.y destinationWormHole.scannerPwrs[obj.owner] = max(obj.scannerPwr, destinationWormHole.scannerPwrs.get(obj.owner, 0)) Utils.sendMessage(tran, obj, MSG_ENTERED_WORMHOLE, destinationWormHole.oid , (origin.name,destinationWormHole.name)) arrived = 1 else: #is not wormhole...how'd you ever execute this command? Or is there some weird "terraform wormhole" technology we never forsaw? log.warning('IFleet', 'Cannot enter non-existant wormhole at location ', origin.oid) #Utils.sendMessage(tran, obj, MSG_ENTERED_WORMHOLE, destinationWormHole.oid , (origin.name,destinationWormHole.name)) arrived = 1 #since the move part was successful, just ignore this problem for the player return arrived
def forceAllyWithEDEN(self,tran,obj): for partyID in obj.diplomacyRels.keys(): party = tran.db.get(partyID, None) if party.type == Const.T_AIEDENPLAYER: diplSelf = obj.diplomacyRels.get(party.oid, None) log.debug("Allying Pirate with EDEN (forced)", obj.oid, partyID) diplEDEN = IDataHolder() diplEDEN.type = Const.T_DIPLREL diplEDEN.pacts = { Const.PACT_ALLOW_CIVILIAN_SHIPS: [Const.PACT_ACTIVE, Const.PACT_ALLOW_CIVILIAN_SHIPS], Const.PACT_ALLOW_MILITARY_SHIPS: [Const.PACT_ACTIVE, Const.PACT_ALLOW_MILITARY_SHIPS] } diplEDEN.relation = Const.REL_FRIENDLY diplEDEN.relChng = 0 diplEDEN.lastContact = tran.db[Const.OID_UNIVERSE].turn diplEDEN.contactType = Const.CONTACT_STATIC diplEDEN.stats = None diplSelf.relation = Const.REL_FRIENDLY diplSelf.pacts = { Const.PACT_ALLOW_CIVILIAN_SHIPS: [Const.PACT_ACTIVE, Const.PACT_ALLOW_CIVILIAN_SHIPS], Const.PACT_ALLOW_MILITARY_SHIPS: [Const.PACT_ACTIVE, Const.PACT_ALLOW_MILITARY_SHIPS] } obj.diplomacyRels[party.oid] = diplSelf party.diplomacyRels[obj.oid] = diplEDEN
def _countVotes(self, tran, obj, galaxy): VALID_TYPES = [Const.T_PLAYER, Const.T_AIPLAYER] log.debug("Voting for galaxy", galaxy.oid) # compute votes votesByName = {} votesByID = {} voterNames = {} for playerID in obj.players: player = tran.db[playerID] if galaxy.oid != player.galaxy: continue if player.type not in VALID_TYPES: continue # add to sum log.debug(playerID, "votes for", player.voteFor, "with votes", player.stats.slots) tmpPlayer = tran.db.get(player.voteFor, None) if not tmpPlayer or tmpPlayer.type not in VALID_TYPES: # reset vote player.voteFor = Const.OID_NONE votedName = None else: votedName = tmpPlayer.name # count votes votesByName[votedName] = votesByName.get(votedName, 0) + player.stats.slots votesByID[player.voteFor] = votesByID.get(player.voteFor, 0) + player.stats.slots try: voterNames[votedName].append(player.name) except KeyError: voterNames[votedName] = [player.name] return votesByName, votesByID, voterNames
def getDiplomacyWith(self, tran, obj, playerID): if obj.oid == playerID: return Const.REL_UNITY player = tran.db.get(playerID, None) if player.type in (Const.T_AIPIRPLAYER, Const.T_PIRPLAYER): dipl = obj.diplomacyRels.get(playerID, None) if not dipl: # make default dipl = IDataHolder() dipl.type = Const.T_DIPLREL dipl.pacts = { Const.PACT_ALLOW_CIVILIAN_SHIPS: [Const.PACT_ACTIVE, Const.PACT_ALLOW_CIVILIAN_SHIPS], Const.PACT_ALLOW_MILITARY_SHIPS: [Const.PACT_ACTIVE, Const.PACT_ALLOW_MILITARY_SHIPS] } dipl.relation = Const.REL_FRIENDLY dipl.relChng = 0 dipl.lastContact = tran.db[Const.OID_UNIVERSE].turn dipl.contactType = Const.CONTACT_NONE dipl.stats = None if playerID != obj.oid: obj.diplomacyRels[playerID] = dipl else: log.debug("getDiplomacyWith myself", obj.oid) return dipl # this AI battles with overyone # make default dipl = IDataHolder() dipl.type = Const.T_DIPLREL dipl.pacts = {} dipl.relation = Const.REL_ENEMY dipl.relChng = 0 dipl.lastContact = tran.db[Const.OID_UNIVERSE].turn dipl.contactType = Const.CONTACT_NONE dipl.stats = None return dipl
def redirectShips(self, tran, obj, sourceSystemID, targetSystemID): # check sourceSystemID ok = 0 if sourceSystemID == targetSystemID: targetSystemID = OID_NONE for planetID in tran.db[sourceSystemID].planets: if tran.db[planetID].owner == obj.oid: ok = 1 if not ok: raise GameException("You must own planet in the source system") # check targetSystemID if targetSystemID != OID_NONE and 0: # TODO: switch on ok = 0 for planetID in tran.db[targetSystemID].planets: if tran.db[planetID].owner == obj.oid: ok = 1 if not ok: raise GameException("You must own planet in the target system") # fine - record it log.debug(obj.oid, "Adding redirection", sourceSystemID, targetSystemID) if targetSystemID: obj.shipRedirections[sourceSystemID] = targetSystemID else: try: del obj.shipRedirections[sourceSystemID] except KeyError: pass return obj.shipRedirections
def createFont(): # create font for fontName in config.get("general", "fonts").split(","): section = "%s font" % fontName fontType = config.get(section, "type") log.debug("Loading font", fontName, fontType) if fontType == "windowsttf": if os.name == "nt": # get "Fonts" folder location handle = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders') path, valueType = _winreg.QueryValueEx(handle, 'Fonts') handle.Close() filename = os.path.join(path, config.get(section, "file")) else: continue elif fontType == "ttf": filename = config.get(section, "file") elif fontType == "default": filename = None # load font if filename == None or os.path.exists(filename): initFont('small', filename, config.getint(section, "small")) initFont('small-bold', filename, config.getint(section, "small"), bold = 1) initFont('normal', filename, config.getint(section, "normal")) initFont('normal-bold', filename, config.getint(section, "normal"), bold = 1) initFont('large', filename, config.getint(section, "large")) initFont('large-bold', filename, config.getint(section, "large"), bold = 1) return
def getMessagesLastID(objID): obj = get(objID, publicOnly = 1) if not hasattr(obj, "_messages"): log.debug("Creating _messages") obj._messages = {} obj._messagesLastID = -1 return obj._messagesLastID
def changePactCond(self, tran, obj, playerID, pactID, state, conditions): log.debug("changePactCond", obj.oid, playerID, pactID) # must have a contact if playerID not in obj.diplomacyRels: raise GameException('No contact with this player.') player = tran.db[playerID] # must be a player if player.type not in PLAYER_TYPES and player.type != T_ALLIANCE: raise GameException('Pacts can be offered to players and aliances only.') # check pactID pact = Rules.pactDescrs.get(pactID, None) if not pact: raise GameException('No such pact type.') # check state if state not in (PACT_OFF, PACT_INACTIVE, PACT_ACTIVE): raise GameException("Wrong pact state") # check conditions for tmpPactID in conditions: pact = Rules.pactDescrs.get(tmpPactID, None) if not pact: raise GameException('No such pact type.') # record pact dipl = self.cmd(obj).getDiplomacyWith(tran, obj, playerID) dipl.pacts[pactID] = [state] dipl.pacts[pactID].extend(conditions) # if state if PACT_OFF, disable state on partner's side if state == PACT_OFF: partner = tran.db[playerID] dipl = self.cmd(partner).getDiplomacyWith(tran, partner, obj.oid) if pactID in dipl.pacts: dipl.pacts[pactID][0] = PACT_OFF else: dipl.pacts[pactID] = [PACT_OFF] return obj.diplomacyRels
def stealTechs(self, tran, piratePlayer, oldOwnerID, stealFromPlanetID): if oldOwnerID == Const.OID_NONE: return log.debug(piratePlayer.oid, "IPiratePlayer stealing techs") oldOwner = tran.db[oldOwnerID] canSteal = Rules.pirateCanStealImprovements while canSteal > 0: stealed = False for techID in oldOwner.techs: tech = Rules.techs[techID] if oldOwner.techs[techID] <= piratePlayer.techs.get(techID, 0): # skip techs that are already stealed continue if (tech.isShipEquip or tech.isShipHull) and not tech.unpackStruct and canSteal > 0: self.givePirateTech(tran, piratePlayer, oldOwner, techID, stealFromPlanetID) canSteal -= 1 stealed = True if tech.isProject and canSteal > 0: self.givePirateTech(tran, piratePlayer, oldOwner, techID, stealFromPlanetID) canSteal -= 1 stealed = True if not stealed: break # update techs self.cmd(piratePlayer).update(tran, piratePlayer) return
def update(self, tran, obj): # check existence of all systems if 0: for systemID in obj.systems: if not tran.db.has_key(systemID): log.debug("CONSISTENCY - system %d from galaxy %d does not exists" % (systemID, obj.oid)) elif tran.db[systemID].type not in (T_SYSTEM, T_WORMHOLE): log.debug("CONSISTENCY - system %d from galaxy %d is not a T_SYSTEM or T_WORMHOLE" % (systemID, obj.oid)) # validate starting positions for planetID in obj.startingPos[:]: if not tran.db.has_key(planetID): log.debug("REMOVING nonexistent obj from start pos", planetID) obj.startingPos.remove(planetID) planet = tran.db[planetID] if planet.type != T_PLANET: log.debug("REMOVING ??? from start pos", planetID) obj.startingPos.remove(planetID) #if planet.plType != "E": # log.debug("REMOVING non earth planet from start pos", planetID) # obj.startingPos.remove(planetID) # check compOf if not tran.db.has_key(obj.compOf) or tran.db[obj.compOf].type != T_UNIVERSE: log.debug("CONSISTENCY invalid compOf for galaxy", obj.oid, obj.compOf) # TODO remove after 0.5.69 if not hasattr(obj, 'bookedCreation'): obj.bookedCreation = False
def loadTechImg(techID): global techImgs # remove possible "shifts" techID = techID % 10000 # load image filename = os.path.join(Rules.rulesetPath, "icons", "%04d.png" % techID) log.debug("Loading icon for tech %d from %s" % (techID, filename)) if not os.path.exists(filename): return False img = pygame.image.load(filename).convert_alpha() techImgs[techID] = img # red variant red = pygame.Surface((37,37)) red.fill((255, 0, 0)) red.set_alpha(64) tmpImg = img.convert_alpha() tmpImg.blit(red, (0, 0)) techImgs[techID + redShift] = tmpImg # white variant white = pygame.Surface((37,37)) white.fill((255, 255, 255)) white.set_alpha(64) tmpImg = img.convert_alpha() tmpImg.blit(white, (0, 0)) techImgs[techID + whiteShift] = tmpImg return True
def processINITPhase(self, tran, obj, data): # compute emr level turn = tran.db[OID_UNIVERSE].turn obj.emrTime -= 1 if obj.emrTime <= 0: modulo = turn % Rules.emrPeriod for season in Rules.emrSeasons: if modulo >= season.startTime and modulo <= season.endTime: log.debug("EMR - season", season.name) obj.emrTrend = Utils.rand(int(season.emrLevelMin * 100), int(season.emrLevelMax * 100) + 1) / 100.0 obj.emrTime = Utils.rand(Rules.emrMinDuration, Rules.emrMaxDuration) log.debug("EMR - trend, time", obj.emrTrend, obj.emrTime) message = { "sender": "GNC", "senderID": obj.oid, "forum": "NEWS", "data": (obj.oid, MSG_GNC_EMR_FORECAST, obj.oid, turn, (obj.emrTrend, obj.emrTime)), "topic": "EVENT", } self.cmd(obj).sendMsg(tran, obj, message) break elif obj.emrLevel >= obj.emrTrend: obj.emrLevel -= Utils.rand(1, 6) / 100.0 elif obj.emrLevel <= obj.emrTrend: obj.emrLevel += Utils.rand(1, 6) / 100.0 # if not obj.timeStopped: if not obj.timeEnabled: self.cmd(obj).enableTime(tran, obj) else: self.cmd(obj).enableTime(tran, obj, force = 1, enable = 0) # remove old messages self.cmd(obj).deleteOldMsgs(tran, obj) return obj.systems
def getInfo(self, tran, obj): result = ISystem.getInfo(self, tran, obj) log.debug('there!') result.type = obj.type result.name = obj.name result.destinationOid = obj.destinationOid return result
def isUpdateAvailable(self): """Check if client version matches server version and update client if neccessary""" log.message("Checking for update...") if "oslauncher" in sys.modules: log.message("Application launched from Outer Space Launcher -- will not update") return False updateMode = gdata.config.client.updatemode or "normal" # quit if update is disabled if updateMode == 'never': return False # compare server and client versions log.message("Retrieving server version") try: self.serverVersion = client.cmdProxy.getVersion() except KeyError: # call is not supported on older server versions log.debug("getVersion call not supported") self.reportFailure(_("Server does not support update feature yet. Check for updates manually, please.")) return None log.debug("Comparing server and client versions", self.serverVersion, ige.version.version) matches = True for i in ("major", "minor", "revision", "status"): if ige.version.version[i] != self.serverVersion[i]: matches = False if matches: log.message("Versions match, no need to update") return False log.message("Version do not match, update is needed") return True
def getMessagesLastID(objID): obj = get(objID, publicOnly=1) if not hasattr(obj, "_messages"): log.debug("Creating _messages") obj._messages = {} obj._messagesLastID = -1 return obj._messagesLastID
def getScanInfos(self, tran, obj, scanPwr, player): log.debug('Generating wormhole scan data', obj.oid) result = IDataHolder() results = [result] if scanPwr >= Rules.level1InfoScanPwr: result._type = Const.T_SCAN result.scanPwr = scanPwr result.oid = obj.oid result.x = obj.x result.y = obj.y result.signature = obj.signature result.type = obj.type result.compOf = obj.compOf result.starClass = obj.starClass result.destinationOid = obj.destinationOid if scanPwr >= Rules.level2InfoScanPwr: result.name = obj.name result.combatCounter = obj.combatCounter if scanPwr >= Rules.level4InfoScanPwr: result.fleets = obj.fleets for fleetID in obj.fleets: fleet = tran.db[fleetID] if fleet.owner == player: continue newPwr = scanPwr * fleet.signature / obj.signature results.extend( self.cmd(fleet).getScanInfos(tran, fleet, newPwr, player)) return results
def update(self, tran, obj): if obj.impactDelay > Rules.asteroidImpactDelay: # delete me self.cmd(obj).disbandFleet(tran, obj) return # closest system if not hasattr(obj, "closeSystem") or not tran.db.has_key(obj.closeSystem): if obj.orbiting == OID_NONE: log.warning("No close system for asteroid", obj.oid) # select any system systemID = tran.db[tran.db[OID_UNIVERSE].galaxies[0]].systems[0] obj.closeSystem = systemID else: obj.closeSystem = obj.orbiting system = tran.db[obj.closeSystem] if system.type == T_SYSTEM: if obj.oid not in system.closeFleets: system.closeFleets.append(obj.oid) else: log.debug("IAsteroid - invalid orbiting", obj.orbiting) self.cmd(obj).disbandFleet(tran, obj) return # verify close system if tran.db.has_key(obj.closeSystem): system = tran.db[obj.closeSystem] if system.type == T_SYSTEM: if obj.oid not in system.closeFleets: #@log.debug("Adding fleet", obj.oid, "into closeFleets", system.oid) system.closeFleets.append(obj.oid) else: obj.closeSystem = OID_NONE else: obj.closeSystem = OID_NONE
def createFont(): # create font for fontName in config.get("general", "fonts").split(","): section = "%s font" % fontName fontType = config.get(section, "type") log.debug("Loading font", fontName, fontType) if fontType == "windowsttf": if os.name == "nt": # get "Fonts" folder location handle = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders') path, valueType = winreg.QueryValueEx(handle, 'Fonts') handle.Close() filename = os.path.join(path, config.get(section, "file")) else: continue elif fontType == "ttf": filename = resources.get(config.get(section, "file")) elif fontType == "default": filename = None # load font if filename == None or os.path.exists(filename): Fonts.initFont('small', filename, config.getint(section, "small")) Fonts.initFont('small-bold', filename, config.getint(section, "small"), bold = 1) Fonts.initFont('small-italic', filename, config.getint(section, "small"), italic = 1) Fonts.initFont('normal', filename, config.getint(section, "normal")) Fonts.initFont('normal-bold', filename, config.getint(section, "normal"), bold = 1) Fonts.initFont('normal-italic', filename, config.getint(section, "normal"), italic = 1) Fonts.initFont('large', filename, config.getint(section, "large")) Fonts.initFont('large-bold', filename, config.getint(section, "large"), bold = 1) Fonts.initFont('large-italic', filename, config.getint(section, "large"), italic = 1) return
def disbandFleet(self, tran, obj): log.debug('IFleet', 'disbanding fleet', obj.oid, 'of player', obj.owner) # remove from player's fleets try: if obj.owner != OID_NONE: tran.db[obj.owner].fleets.remove(obj.oid) except Exception: log.warning('IFleet', 'disbandFleet: cannot remove fleet from owner\'s fleet') pass # remove from orbit # remove from index if necessary if obj.orbiting != OID_NONE: try: if tran.db.has_key(obj.orbiting): tran.db[obj.orbiting].fleets.remove(obj.oid) except Exception: log.warning('IFleet', 'disbandFleet: cannot remove fleet from system.') pass # remove from close fleets if obj.closeSystem != OID_NONE: try: if tran.db.has_key(obj.closeSystem): tran.db[obj.closeSystem].closeFleets.remove(obj.oid) except Exception: log.warning("IFleet", "disbandFleet: cannot remove fleet from the close system.") # delete from database try: tran.db.delete(obj.oid) except KeyError: log.warning('IFleet', 'disbandFleet: cannot remove fleet from database.')
def getPreCombatData(self, tran, obj): if obj.impactDelay > Rules.asteroidImpactDelay: # modify target's environment and minerals planet = tran.db[obj.target] #planet.plBio = max(0, int(planet.plBio + obj.asHP * Rules.asteroidPerHPBioMod)) #planet.plMin = min(200, int(planet.plMin + obj.asHP * Rules.asteroidPerHPMinMod)) # special shots from asteroid hp = obj.asHP shots = [] if hp > 1500: shots.append((Rules.asteroidAttack, Rules.Tech.ASTEROID1000)) hp = hp % 1000 if hp > 150: shots.append((Rules.asteroidAttack, Rules.Tech.ASTEROID100)) hp = hp % 100 if hp > 15: shots.append((Rules.asteroidAttack, Rules.Tech.ASTEROID10)) hp = hp % 10 if hp > 1: shots.append((Rules.asteroidAttack, Rules.Tech.ASTEROID1)) # destroy asteroid self.cmd(obj).disbandFleet(tran, obj) return shots, [0, 0, 0, 1] else: obj.impactDelay += 1 log.debug("Asteroid impact delay", obj.impactDelay) return [], [0, 0, 0, 1]
def update(self, tran, obj): # check existence of all systems if 0: for systemID in obj.systems: if not tran.db.has_key(systemID): log.debug( "CONSISTENCY - system %d from galaxy %d does not exists" % (systemID, obj.oid)) elif tran.db[systemID].type not in (T_SYSTEM, T_WORMHOLE): log.debug( "CONSISTENCY - system %d from galaxy %d is not a T_SYSTEM or T_WORMHOLE" % (systemID, obj.oid)) # validate starting positions for planetID in obj.startingPos[:]: if not tran.db.has_key(planetID): log.debug("REMOVING nonexistent obj from start pos", planetID) obj.startingPos.remove(planetID) planet = tran.db[planetID] if planet.type != T_PLANET: log.debug("REMOVING ??? from start pos", planetID) obj.startingPos.remove(planetID) #if planet.plType != "E": # log.debug("REMOVING non earth planet from start pos", planetID) # obj.startingPos.remove(planetID) # check compOf if not tran.db.has_key( obj.compOf) or tran.db[obj.compOf].type != T_UNIVERSE: log.debug("CONSISTENCY invalid compOf for galaxy", obj.oid, obj.compOf)
def processKeyUp(self, evt2): if self.callEventHandler: self.callEventHandler.processKeyUp(evt2) evt = self.keyPress if not self.keyPress: return ui.NoEvent self.keyPress = False # ==== Object Hotkeys ==== #I have not found unicode escape characters for Ctrl-0 through Ctrl-9, so using direct key reference (less preferred due to international keyboards) if evt.key in [49, 50, 51, 52, 53, 54, 55, 56, 57, 48]: self._processObjectHotkeys(evt) # ==== Map and Dialog Hotkeys ==== elif evt.key == pygame.K_ESCAPE and self.selectobject: log.debug('Canceled Key') if self.selectobject: self.app.setStatus(_("Ready.")) self.selectobject = False return ui.NoEvent if not evt.unicode: # force update self.star_map.scale += 1 self.star_map.scale -= 1 return ui.NoEvent if evt.unicode in u'+=': self._rescaleMap(evt, 5) elif evt.unicode == u'-': self._rescaleMap(evt, -5) # Space Bar - Recenter elif evt.unicode == u' ': x, y = pygame.mouse.get_pos() centerX, centerY = self._mapSurf.get_rect().center self.star_map.currX -= float(centerX - x) / self.star_map.scale self.star_map.currY += float(centerY - y) / self.star_map.scale self.repaint_map = 1 self._newCurrXY = 0 # ==== Standard Hotkeys ==== # Reserve CTRL-C for copy (future editor support) # Ctrl+F toggleMapping = { u'\x01': 'alternate', # Alternative system info u'\x07': 'grid', # Grid u'\x08': 'civ', # Civilian ships u'\x0C': 'lines', # Fleet lines u'\x10': 'pzone', # Control areas u'\x12': 'redir', # Redirections u'\x13': 'scanner' } # Scanner circles if evt.unicode in toggleMapping and pygame.key.get_mods( ) & pygame.KMOD_CTRL: self.toggleHotButtons(toggleMapping[evt.unicode]) # Ctrl+F to open the search (find) dialog elif evt.unicode == u'\x06' and pygame.key.get_mods( ) & pygame.KMOD_CTRL: self.searchDlg.display() # Reserve CTRL-V,X,and Z for paste, cut, and undo (future editor support) # ==== Else ==== else: # force update self.star_map.scale += 1 self.star_map.scale -= 1 return ui.NoEvent
def update(self, tran, obj): if obj.impactDelay > Rules.asteroidImpactDelay: # delete me self.cmd(obj).disbandFleet(tran, obj) return # closest system if not hasattr(obj, "closeSystem") or not tran.db.has_key( obj.closeSystem): if obj.orbiting == Const.OID_NONE: log.warning("No close system for asteroid", obj.oid) # select any system systemID = tran.db[tran.db[ Const.OID_UNIVERSE].galaxies[0]].systems[0] obj.closeSystem = systemID else: obj.closeSystem = obj.orbiting system = tran.db[obj.closeSystem] if system.type == Const.T_SYSTEM: if obj.oid not in system.closeFleets: system.closeFleets.append(obj.oid) else: log.debug("IAsteroid - invalid orbiting", obj.orbiting) self.cmd(obj).disbandFleet(tran, obj) return # verify close system if tran.db.has_key(obj.closeSystem): system = tran.db[obj.closeSystem] if system.type == Const.T_SYSTEM: if obj.oid not in system.closeFleets: #@log.debug("Adding fleet", obj.oid, "into closeFleets", system.oid) system.closeFleets.append(obj.oid) else: obj.closeSystem = Const.OID_NONE else: obj.closeSystem = Const.OID_NONE
def processINITPhase(self, tran, obj, data): try: ## find active/inactive pacts # set all active/on pacts to active for playerID in obj.players: #@log.debug("Processing player", playerID) player = tran.db[playerID] for partyID in player.diplomacyRels: #@log.debug("Processing party", partyID) dipl = player.diplomacyRels[partyID] for pactID in dipl.pacts.keys(): if pactID not in Rules.pactDescrs: # this is invalid pactID log.debug(playerID, "Deleting invalid pact with", partyID, "pact", pactID) del dipl.pacts[pactID] continue if dipl.pacts[pactID][0] > PACT_OFF: dipl.pacts[pactID][0] = PACT_ACTIVE # inactivate all pact that does not satisfy conditions changed = 1 defaultPact = [PACT_OFF] while changed: changed = 0 log.debug("Inactivate pacts iteration starting...") for playerID in obj.players: #@log.debug("Processing player", playerID) player = tran.db[playerID] # all parties of a player for partyID in player.diplomacyRels: #@log.debug("Processing party", partyID) party = tran.db[partyID] partyDipl = party.diplomacyRels.get(playerID, None) if not partyDipl: continue dipl = player.diplomacyRels[partyID] # correct relations dipl.relation = min(dipl.relation, partyDipl.relation) # all pacts with party for pactID in dipl.pacts: # check validity interval pactSpec = Rules.pactDescrs[pactID] if (dipl.relation < pactSpec.validityInterval[0] or \ dipl.relation > pactSpec.validityInterval[1]) and \ dipl.pacts[pactID][0] == PACT_ACTIVE: #@log.debug("Inactivating pact (validity interval)", playerID, pactID) dipl.pacts[pactID][0] = PACT_INACTIVE changed = 1 # check conditions for the pact if pact is active if dipl.pacts[pactID][0] == PACT_ACTIVE: for condPactID in dipl.pacts[pactID][1:]: #@log.debug("Checking", playerID, pactID, "against", partyID, condPactID) if partyDipl and partyDipl.pacts.get(condPactID, defaultPact)[0] != PACT_ACTIVE: dipl.pacts[pactID][0] = PACT_INACTIVE changed = 1 except Exception: log.warning("Cannot process diplomacy initialization") # TODO - send notifications if pacts are changed # remove old messages self.cmd(obj).deleteOldMsgs(tran, obj) return obj.players[:] + [OID_NATURE]
def startElement(self, name, attrs): if self.state == 1 and name == "techtree": self.state = 2 elif self.state == 2 and name == "technology": log.debug("Tech %s [%s]" % (attrs["name"], attrs["id"])) self.state = 3 self.tech = Technology(int(attrs["id"]), attrs["symbol"], techs) setattr(Tech, attrs["symbol"], int(attrs["id"])) self.tech.set("name", attrs["name"]) elif self.state == 3 and name == "structure": self.tech.set("isStructure", 1) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == "discovery": self.tech.set("isDiscovery", 1) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == "notdiscovery": self.tech.set("isDiscovery", 0) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == "starting": self.tech.set("isStarting", 1) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == "notstarting": self.tech.set("isStarting", 0) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == "shipequip": self.tech.set("isShipEquip", 1) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == "project": self.tech.set("isProject", 1) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == "shiphull": self.tech.set("isShipHull", 1) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == "mine": self.tech.set("isMine", 1) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == "data": for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == "preresearch": self.state = 4 self.text = "" elif self.state == 3 and name == "description": self.state = 4 self.text = "" elif self.state == 3 and name == "flavor": self.state = 4 self.text = "" else: raise "Unsupported tag %s" % str(name)
def startElement(self, name, attrs): if self.state == 1 and name == 'techtree': self.state = 2 elif self.state == 2 and name == 'technology': log.debug('Tech %s [%s]' % (attrs['name'], attrs['id'])) self.state = 3 self.tech = Technology(int(attrs['id']), attrs['symbol'], techs) setattr(Tech, attrs['symbol'], int(attrs['id'])) self.tech.set('name', attrs['name']) elif self.state == 3 and name == 'structure': self.tech.set('isStructure', 1) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == 'discovery': self.tech.set('isDiscovery', 1) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == 'notdiscovery': self.tech.set('isDiscovery', 0) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == 'starting': self.tech.set('isStarting', 1) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == 'notstarting': self.tech.set('isStarting', 0) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == 'shipequip': self.tech.set('isShipEquip', 1) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == 'project': self.tech.set('isProject', 1) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == 'shiphull': self.tech.set('isShipHull', 1) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == 'mine': self.tech.set('isMine', 1) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == 'data': for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == 'preresearch': self.state = 4 self.text = '' elif self.state == 3 and name == 'description': self.state = 4 self.text = '' elif self.state == 3 and name == 'flavor': self.state = 4 self.text = '' else: raise 'Unsupported tag %s' % str(name)
def startElement(self, name, attrs): if self.state == 1 and name == 'techtree': self.state = 2 elif self.state == 2 and name == 'technology': log.debug('Tech %s [%s]' % (attrs['name'], attrs['id'])) self.state = 3 self.tech = Technology(int(attrs['id']), attrs['symbol'], self.techs) setattr(self.Tech, attrs['symbol'], int(attrs['id'])) self.tech.set('name', attrs['name']) elif self.state == 3 and name == 'structure': self.tech.set('isStructure', 1) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == 'discovery': self.tech.set('isDiscovery', 1) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == 'notdiscovery': self.tech.set('isDiscovery', 0) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == 'starting': self.tech.set('isStarting', 1) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == 'notstarting': self.tech.set('isStarting', 0) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == 'shipequip': self.tech.set('isShipEquip', 1) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == 'project': self.tech.set('isProject', 1) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == 'shiphull': self.tech.set('isShipHull', 1) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == 'mine': self.tech.set('isMine', 1) for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == 'data': for key in attrs.keys(): self.tech.set(key, attrs[key]) elif self.state == 3 and name == 'preresearch': self.state = 4 self.text = '' elif self.state == 3 and name == 'description': self.state = 4 self.text = '' elif self.state == 3 and name == 'flavor': self.state = 4 self.text = '' else: raise 'Unsupported tag %s' % str(name)
def chsumDir(chsum, dirname, names): names.sort() for filename in names: if os.path.splitext(filename)[1] in ('.xml', '.py'): log.debug('Checking file', filename) fh = open(os.path.join(dirname, filename), 'rb') chsum.update(fh.read()) fh.close()
def onUpdateFinished(): global progressDlg log.debug("onUpdateFinished") try: progressDlg.Close() progressDlg.Destroy() progressDlg = None except: log.warning("Cannot close ProgressDialog window")
def backup(self, backupPath): """ Creates bzip2 archive of ais_list file and ai_data directory """ log.debug("Creating backup %s-ais.osbackup" % backupPath) tar = tarfile.open("%s-ais.osbackup" % backupPath, "w:bz2") tar.add(os.path.join(self.configDir, "ais_list")) tar.add(os.path.join(self.configDir, "ai_data")) tar.close()
def onUpdateFinished(): global progressDlg log.debug("onUpdateFinished") try: progressDlg.hide() except: log.warning("Cannot delete progressDlg window") for dialog in gdata.updateDlgs: dialog.update()
def detectClose(obj1, obj2, signatures): # ignore itself if obj1.oid >= obj2.oid: return d = math.hypot(obj1.x - obj2.x, obj1.y - obj2.y) if d < 1.0: log.debug("CLOSE FLEET detected", obj1.oid, obj2.oid, obj1.signature, obj2.signature) signatures[obj1.oid] = signatures.get(obj1.oid, 0) + obj2.signature signatures[obj2.oid] = signatures.get(obj2.oid, 0) + obj1.signature
def chsumDir(chsum, dirname, names): names.sort() for filename in names: if os.path.splitext(filename)[1] in ('.xml',): log.debug('Checking file', filename) # read file fh = open(os.path.join(dirname, filename), 'rb') chsum.update(fh.read()) fh.close()
def actionRedirect(self, tran, obj, refuelled): if obj.orbiting != OID_NONE: # try to find fleet with the redirect command (<10 ships) # and join it system = tran.db[obj.orbiting] for fleetID in system.fleets: fleet = tran.db[fleetID] if fleet.owner != obj.owner or obj.oid == fleetID: continue if Utils.isIdleFleet(fleet): continue action, target, actionData = fleet.actions[fleet.actionIndex] # same command, less than 20 ships in the resulting fleet if action == FLACTION_REDIRECT and len(fleet.ships) + len(obj.ships) <= 20: # join it log.debug("JOINING", obj.oid, fleetID) self.cmd(obj).joinFleet(tran, obj, fleetID) # "join" targets fleet.actions[fleet.actionIndex] = ( action, max(obj.actions[obj.actionIndex][1], target), actionData, ) return 0 # move? action, target, actionData = obj.actions[obj.actionIndex] if obj.orbiting == OID_NONE or target != OID_NONE: # ok, the target was already selected if not self.cmd(obj).moveToTarget(tran, obj, target): # keep moving return 0 # we are in the system - delete target obj.actions[obj.actionIndex] = (action, OID_NONE, actionData) # check if current system has a redirection player = tran.db[obj.owner] if obj.orbiting not in player.shipRedirections: # there is no redirection, we are done return 1 # select a new target if tanks are full # departure every 6th turn turn = tran.db[OID_UNIVERSE].turn if refuelled and turn % 6 == 0: obj.actions[obj.actionIndex] = (action, player.shipRedirections[obj.orbiting], actionData) return 0 # old code # check if current system has any redirection player = tran.db[obj.owner] if obj.orbiting not in player.shipRedirections: return 1 # form new command queue obj.actions = [ [FLACTION_REFUEL, player.shipRedirections[obj.orbiting], None], [FLACTION_REDIRECT, OID_NONE, None], ] obj.actionIndex = 0 return 0
def removeShips(self, tran, obj, ships): for ship in ships: obj.ships.remove(ship) if not obj.ships: log.debug('IFleet', 'removeShips removed last ship') self.cmd(obj).disbandFleet(tran, obj) else: self.cmd(obj).update(tran, obj) return obj
def backup(self, backupPath): """ Creates bzip2 archive of ais_list file and ai_data directory """ log.debug('Creating backup {0}-ais.osbackup'.format(backupPath)) tar = tarfile.open('{0}-ais.osbackup'.format(backupPath), 'w:bz2') tar.add(os.path.join(self.configDir, self.listname)) tar.add(os.path.join(self.configDir, 'ai_data', self.gameName)) tar.close()
def setKeyObject(self, objIDs, bObjIDs): objID = self.gotoObject(objIDs, bObjIDs) log.debug('Setting Key Object To:', objID) self.app.setStatus(_("Ready.")) self.selectobject = False if (objID == Const.OID_NONE): return obj = client.get(objID) if obj.type in (Const.T_SYSTEM, Const.T_PLANET, Const.T_FLEET): gdata.objectFocus[self.setKey] = objID
def enableTime(self, tran, obj, force=False): log.debug('IGalaxy', 'Checking for time...') if not force and not self._isEligibleEnableTime(tran, obj): return if obj.timeEnabled is None: self._firstEnableTime(tran, obj) # ok, enable time log.message('IGalaxy', 'Enabling time for', obj.oid) obj.timeEnabled = True self._trickleTimeToPlayers(tran, obj)
def onTaskInfo(self, widget, action, data): if self.activeQueue == None or self.activeIndex == None: return task = self.player.prodQueues[self.activeQueue][self.activeIndex] if not task.isShip: self.techInfoDlg.display(task.techID) else: log.debug("Show ship info") self.constructionDlg.selectedDesignID = task.techID self.constructionDlg.display()
def onTaskInfo(self, widget, action, data): if self.activeQueue == None or self.activeIndex == None: return task = self.player.prodQueues[self.activeQueue][self.activeIndex] if not task.isShip: self.techInfoDlg.display(task.techID) else: log.debug("Show ship info") self.constructionDlg.selectedDesignID = task.techID; self.constructionDlg.display()
def importFromPath(path): import sys oldpath = sys.path try: sys.path = [path] log.debug("Rules import - using path", sys.path) exec "from rules import *" in globals() log.message("Rules import succeeded") finally: sys.path = oldpath
def finishStructOUTPOST(tran, source, target, tech): log.debug("Finishing OUTPOST", tech.id, "target", target.oid) # setup morale if colonizing noninhabited planet if target.storPop == 0: target.morale = Rules.maxMorale # try to change owner of planet tran.gameMngr.cmdPool[target.type].changeOwner(tran, target, source.owner) # increase population target.storPop += tech.unpackPop target.maxPop += tech.unpackPop