Esempio n. 1
0
 def _processProdQueue(self, planet):
     player = client.getPlayer()
     if planet.prodQueue and planet.effProdProd > 0:
         index = 0
         totalProd = 0
         for task in planet.prodQueue:
             if task.isShip:
                 tech = player.shipDesigns[task.techID]
             else:
                 tech = client.getFullTechInfo(task.techID)
             prodFirst, prodNext = self._getTaskProd(task, tech, planet.oid)
             if index == 0:
                 constrInfo = tech.name
                 etc = math.ceil(float(prodFirst) / planet.effProdProd)
             totalProd += prodFirst + prodNext
             index += 1
         etc = res.formatTime(etc)
         totalEtc = res.formatTime(math.ceil(float(totalProd) / planet.effProdProd))
     elif planet.prodQueue:
         task = planet.prodQueue[0]
         if task.isShip:
             tech = player.shipDesigns[task.techID]
         else:
             tech = client.getTechInfo(task.techID)
         constrInfo = tech.name
         etc = _('N/A')
         totalEtc = _("N/A")
     else:
         constrInfo = _("-")
         etc = "-"
         totalEtc = _("-")
     return constrInfo, etc, totalEtc
Esempio n. 2
0
    def _showStructures(self, prodProd):
        items = []

        for techID in client.getPlayer().techs.keys():
            tech = client.getTechInfo(techID)
            if not tech.isStructure or tech.level not in self.showLevels or \
               (tech.isStructure and not self._filterStructure(tech)):
                continue

            if prodProd > 0:
                etc = math.ceil(float(tech.buildProd) / prodProd)
                if self.sourceID != self.planetID:
                    etc *= Rules.buildOnAnotherPlanetMod
                etc = res.formatTime(etc)
            else:
                etc = _("N/A")

            item = ui.Item(
                etc,
                techID=techID,
                tIsShip=0,
                name=tech.name,
                tl=tech.level,
                subtype=tech.subtype,
                icons=((res.getTechImg(techID), ui.ALIGN_N), ),
                font="small-bold",
                align=ui.ALIGN_S,
                tooltipTitle=_("Details"),
                tooltip="%s, %d %s, %s %d" %
                (tech.name, tech.buildProd, _("CP"), _("TL"), tech.level),
                statustip="%s, %d %s, %s %d" %
                (tech.name, tech.buildProd, _("CP"), _("TL"), tech.level))
            self.maxTechLevel = max(self.maxTechLevel, tech.level)
            items.append(item)
        return items
Esempio n. 3
0
    def _processResearchQueue(self):
        player = client.getPlayer()

        items = []
        index = 0
        queued = []
        totalSci = 0
        for task in player.rsrchQueue:
            queued.append(task.techID)
            item, taskSci = self._processResearchQueueTask(task)
            item.index = index
            items.append(item)
            totalSci += taskSci
            index += 1
        totalSci = math.ceil(float(totalSci) / player.effSciPoints)
        self.win.vRQueue.items = items
        self.win.vRQueue.itemsChanged()
        self.win.vRQueueTop.enabled = 0
        self.win.vRQueueUp.enabled = 0
        self.win.vRQueueDown.enabled = 0
        self.win.vRQueueAbort.enabled = 0
        self.win.vRQueueRepat.enabled = 0
        self.win.vRQueueRepat.pressed = 0
        self.win.vRQueueInfo.enabled = 0
        self.win.vRTotal.text = res.formatTime(totalSci) if totalSci else _(
            "N/A")
        return queued
Esempio n. 4
0
 def update(self, configUpdated=False):
     self.galaxyFinishPopup(None, None, False)
     self.alterMenu(None, None, False)
     player = client.getPlayer()
     turn = client.getTurn()
     self.win.vTurn.text = res.formatTime(turn)
     if configUpdated:
         self.win.vStarMap.updateConfigModes()
     self.win.vStarMap.precompute()
     # center of 1st player star
     if not self.centered:
         player = client.getPlayer()
         if player.planets:
             planet = client.get(player.planets[0])
             self.win.vStarMap.setPos(planet.x, planet.y)
         elif player.fleets:
             fleet = client.get(player.fleets[0])
             self.win.vStarMap.setPos(fleet.x, fleet.y)
         self.centered = 1
         self.refocus()  #only fire off when dialog first updated
     # enable/disable construction
     self.win.vConstruction.enabled = Utils.enableConstruction(client)
     # enable/disable diplomacy
     #if player.diplomacyRels:
     self.win.vDiplomacy.enabled = 1
     #else:
     #    self.win.vDiplomacy.enabled = 0
     # highlight messages button?
     self.messagesDlg.update()
     if self.messagesDlg.newMsgs > 0:
         self.win.vMessages.foreground = gdata.sevColors[gdata.MAJ]
     else:
         self.win.vMessages.foreground = None
Esempio n. 5
0
	def update(self,configUpdated=False):
		self.galaxyRestart(None, None, False)
		player = client.getPlayer()
		turn = client.getTurn()
		self.win.vTurn.text = res.formatTime(turn)
		if configUpdated:
			self.win.vStarMap.updateConfigModes()
		self.win.vStarMap.precompute()
		# center of 1st player star
		if not self.centered:
			player = client.getPlayer()
			if player.planets:
				planet = client.get(player.planets[0])
				self.win.vStarMap.setPos(planet.x, planet.y)
			elif player.fleets:
				fleet = client.get(player.fleets[0])
				self.win.vStarMap.setPos(fleet.x, fleet.y)
			self.centered = 1
			self.refocus() #only fire off when dialog first updated
		# enable/disable construction
		self.win.vConstruction.enabled = Utils.enableConstruction(client)
		# enable/disable diplomacy
		#if player.diplomacyRels:
		self.win.vDiplomacy.enabled = 1
		#else:
		#	self.win.vDiplomacy.enabled = 0
		# highlight messages button?
		self.messagesDlg.update()
		if self.messagesDlg.newMsgs > 0:
			self.win.vMessages.foreground = gdata.sevColors[gdata.MAJ]
		else:
			self.win.vMessages.foreground = None
Esempio n. 6
0
    def _showShips(self):
        items = []
        player = client.getPlayer()

        for designID in player.shipDesigns.keys():
            tech = player.shipDesigns[designID]
            if not self._filterShipSize(tech) or not self._filterShipMilitary(
                    tech):
                continue

            if tech.upgradeTo != Const.OID_NONE:
                # skip ships that are set to upgrade
                continue
            if self.prodProd > 0:
                etc = res.formatTime(
                    math.ceil(float(tech.buildProd) / self.prodProd))
            else:
                etc = _("N/A")
            item = ui.Item(tech.name,
                           tLevel=tech.level,
                           tProd=tech.buildProd,
                           techID=designID,
                           tIsShip=1,
                           tETC=etc)
            items.append(item)
        return items
Esempio n. 7
0
 def onSaveStarmapConfirm(self):
     turn = client.getTurn()
     name = 'starmap_' + res.formatTime(turn, '_')
     full_name = os.path.join(gdata.config.game.screenshot_dir, name)
     savedas = self.mapWidget.save(full_name, chronicle_shot=True)
     self.confirmDlg.display(_('File saved as %s' % savedas), _('OK'),
                             False)
 def _populateOpTime(self, fleet):
     if hasattr(fleet, 'storEn') and hasattr(fleet, 'operEn'):
         turns = fleet.storEn / fleet.operEn if fleet.operEn > 0 else 100000
         rawRange = turns * fleet.speed / Rules.turnsPerDay
         _range = "%.2f" % rawRange
         opTime = res.formatTime(turns)
     else:
         _range = "?"
         opTime = "?"
     return opTime, _range
Esempio n. 9
0
    def showCommands(self):
        if self.targetID == Const.OID_NONE:
            info = _('No target selected')
        else:
            target = client.get(self.targetID, noUpdate=1)
            info = getattr(target, 'name', res.getUnknownName())
        # correct buildingIndex
        if not self.sendShips:
            self.selectedShip = Const.OID_NONE
        elif self.selectedShip not in self.sendShips:
            self.selectedShip = self.sendShips.keys()[0]
        # get target data
        self.win.vTarget.text = info
        fleet = self.fleet
        if self.targetID != Const.OID_NONE:
            curTarget = client.get(self.targetID, noUpdate=1)
            target = Const.OID_NONE
            if fleet.orbiting != Const.OID_NONE and target == Const.OID_NONE:
                target = fleet.orbiting
            elif target == Const.OID_NONE:
                target = fleet.oid

            if target != Const.OID_NONE:
                lastTarget = client.get(target, noUpdate=1)
                curX = curTarget.x
                curY = curTarget.y
                lstX = lastTarget.x
                lstY = lastTarget.y
                dx = curX - lstX
                dy = curY - lstY
                lnght = math.sqrt(dx * dx + dy * dy)
                speedBoost = getattr(fleet, "speedBoost", 1)
                fleetSpeed = getattr(fleet, "speed", 0)
                maxDelta = fleetSpeed / Rules.turnsPerDay * speedBoost
                if maxDelta != 0:
                    eta = lnght / maxDelta
                    self.win.vEta.text = res.formatTime(eta)
                else:
                    self.win.vEta.text = _("N/A")
            else:
                self.win.vEta.text = _("N/A")

        if self.sendShips:
            self.win.vSelectedShip.enabled = 1
            designID = self.selectedShip
            self.win.vSelectedShip.text = client.getPlayer(
            ).shipDesigns[designID].name
            self.win.vSelectedShip.data = designID
        else:
            self.win.vSelectedShip.enabled = 0
            self.win.vSelectedShip.text = ""
            self.win.vSelectedShip.data = Const.OID_NONE
            self.win.setStatus(_("No ships found."))
Esempio n. 10
0
    def _processResearchQueueTask(self, task):
        player = client.getPlayer()
        tech = client.getTechInfo(task.techID)
        fulltech = client.getFullTechInfo(task.techID)
        researchSci = Utils.getTechRCost(player, task.techID, task.improvement)
        item = ui.Item(tech.name, techID=task.techID)
        item.tooltipTitle = _("Details")
        item.tooltip = _("Research points %d/%d, change %d pts/turn.") % (
            task.currSci, researchSci, task.changeSci)
        item.statustip = item.tooltip
        item.tImpToMax = "*" if task.improveToMax else ""
        item.tImproveToMax = task.improveToMax
        item.tProgress = _("%d %%") % int(
            task.currSci * 100 / researchSci) if task.currSci > 0 else _("-")
        totalSci = 0
        if task.changeSci > 0:
            etc = float(researchSci - task.currSci) / max(
                task.changeSci, player.effSciPoints)
            totalSci += researchSci - task.currSci
            if player.effSciPoints > 0:
                item.tETC = res.formatTime(etc)
            else:
                item.tETC = res.getNA()
        elif task.changeSci < 0:
            etc = -float(task.currSci) / min(task.changeSci,
                                             player.effSciPoints)
            item.tETC = _("[%s]") % res.formatTime(etc)
        elif player.effSciPoints > 0:
            etc = float(researchSci) / player.effSciPoints
            totalSci += researchSci
            item.tETC = res.formatTime(etc)
        else:
            item.tETC = res.getNA()

        if task.improveToMax:
            for impr in range(task.improvement + 1,
                              fulltech.maxImprovement + 1):
                totalSci += Utils.getTechRCost(player, task.techID, impr)
        item.tLevel = _("%d-%d") % (tech.level, task.improvement)
        return item, totalSci
Esempio n. 11
0
	def showCommands(self):
		if self.targetID == OID_NONE:
			info = _('No target selected')
		else:
			target = client.get(self.targetID, noUpdate = 1)
			info = getattr(target, 'name', res.getUnknownName())
		# correct buildingIndex
		if self.sendShipIndex >= len(self.sendShips):
			self.sendShipIndex = 0
		if self.sendShipTypeIndex >= 2:
			self.sendShipTypeIndex = 0
		# get target data
		self.win.vTarget.text = info
		fleet = self.fleet
		if self.targetID != OID_NONE:
			curTarget = client.get(self.targetID, noUpdate = 1)
			target = OID_NONE
			if fleet.orbiting != OID_NONE and target == OID_NONE:
				target = fleet.orbiting
			elif target == OID_NONE:
				target = fleet.oid

			if target != OID_NONE:
				lastTarget = client.get(target, noUpdate = 1)
				curX = curTarget.x
				curY = curTarget.y
				lstX = lastTarget.x
				lstY = lastTarget.y
				dx = curX - lstX
				dy = curY - lstY
				lnght = math.sqrt(dx*dx + dy*dy)
				speedBoost = getattr(fleet, "speedBoost", 1)
				fleetSpeed = getattr(fleet, "speed", 0)
				maxDelta = fleetSpeed / Rules.turnsPerDay * speedBoost
				if maxDelta != 0:
					eta = lnght / maxDelta
					self.win.vEta.text = res.formatTime(eta)
				else:
					self.win.vEta.text = _("N/A")
			else:
				self.win.vEta.text = _("N/A")

		if self.sendShips:
			self.win.vSendShip.enabled = 1
			techID = self.sendShips[self.sendShipIndex]
			self.win.vSendShip.text = client.getPlayer().shipDesigns[techID].name
			self.win.vSendShip.data = techID
			self.win.vSendShipType.text = self.sendShipType[self.sendShipTypeIndex]
		else:
			self.win.setStatus(_("No ships found."))
Esempio n. 12
0
 def show(self):
     player = client.getPlayer()
     items = []
     index = 0
     # copy
     msgs = player.messages[:]
     msgs.reverse()
     currTurn = client.getTurn()
     for sourceID, msgID, locationID, turn, data in msgs:
         item = ui.Item(None, index=index)
         item.tTime = res.formatTime(turn - currTurn)
         item.message = (sourceID, msgID, locationID, turn, data)
         item.tSourceID = sourceID
         if sourceID != OID_NONE and sourceID != player.oid:
             obj = client.get(sourceID, noUpdate=1)
             if obj:
                 item.tSource = getattr(obj, 'name', res.getUnknownName())
             else:
                 item.tSource = _('N/A')
         else:
             item.tSource = _('-')
         item.tLocationID = locationID
         if locationID != OID_NONE:
             obj = client.get(locationID, noUpdate=1)
             item.tLocation = getattr(obj, 'name', res.getUnknownName())
         else:
             item.tLocation = _('-')
         item.tMessage = messages.getMsgText(msgID, data)
         sev = messages.getMsgSeverity(msgID)
         if sev == messages.CRI:
             item.foreground = (0xd0, 0x20, 0x20)
         elif sev == messages.MAJ:
             item.foreground = (0xff, 0xff, 0x00)
         elif sev == messages.MIN:
             item.foreground = None
             if not self.showMIN:
                 continue
         elif sev == messages.INFO:
             item.foreground = (0xc0, 0xc0, 0xc0)
             if not self.showInfo:
                 continue
         index += 1
         items.append(item)
     self.win.vMessages.items = items
     self.win.vMessages.itemsChanged()
     self.win.vDelete.enabled = 0
Esempio n. 13
0
	def show(self):
		player = client.getPlayer()
		items = []
		index = 0
		# copy
		msgs = player.messages[:]
		msgs.reverse()
		currTurn = client.getTurn()
		for sourceID, msgID, locationID, turn, data in msgs:
			item = ui.Item(None, index = index)
			item.tTime = res.formatTime(turn - currTurn)
			item.message = (sourceID, msgID, locationID, turn, data)
			item.tSourceID = sourceID
			if sourceID != OID_NONE and sourceID != player.oid:
				obj = client.get(sourceID, noUpdate = 1)
				if obj:
					item.tSource = getattr(obj, 'name', res.getUnknownName())
				else:
					item.tSource = _('N/A')
			else:
				item.tSource = _('-')
			item.tLocationID = locationID
			if locationID != OID_NONE:
				obj = client.get(locationID, noUpdate = 1)
				item.tLocation = getattr(obj, 'name', res.getUnknownName())
			else:
				item.tLocation = _('-')
			item.tMessage = messages.getMsgText(msgID, data)
			sev = messages.getMsgSeverity(msgID)
			if sev == messages.CRI:
				item.foreground = (0xd0, 0x20, 0x20)
			elif sev == messages.MAJ:
				item.foreground = (0xff, 0xff, 0x00)
			elif sev == messages.MIN:
				item.foreground = None
				if not self.showMIN:
					continue
			elif sev == messages.INFO:
				item.foreground = (0xc0, 0xc0, 0xc0)
				if not self.showInfo:
					continue
			index += 1
			items.append(item)
		self.win.vMessages.items = items
		self.win.vMessages.itemsChanged()
		self.win.vDelete.enabled = 0
Esempio n. 14
0
    def _processImprovableTech(self, tech, scheduledIDs):
        player = client.getPlayer()

        item = ui.Item(tech.name,
                       techID=tech.id,
                       tLevel='%d-%d' % (tech.level, player.techs[tech.id]),
                       tStruct=(' ', '*')[tech.isStructure],
                       tShip=(' ', '*')[tech.isShipEquip])
        neededSci = Utils.getTechRCost(player, tech.id)
        item.tETC = res.formatTime(
            float(neededSci) /
            player.effSciPoints) if player.effSciPoints > 0 else _("N/A")
        item.foreground = (0xd0, 0xd0,
                           0xd0) if tech.id in scheduledIDs else None
        item.foreground = (
            0x80, 0x40,
            0x40) if tech.id in player.obsoleteTechs else item.foreground
        return item
Esempio n. 15
0
    def _processNonShips(self, tech):
        if self.prodProd > 0:
            etc = math.ceil(float(tech.buildProd) / self.prodProd)
            if self.targetID != self.planetID:
                etc *= Rules.buildOnAnotherPlanetMod
            etc = res.formatTime(etc)
        else:
            etc = _("N/A")

        item = ui.Item(tech.name,
                       tLevel=tech.level,
                       tProd=tech.buildProd,
                       techID=tech.id,
                       tIsShip=0,
                       tETC=etc)
        self.maxTechLevel = max(self.maxTechLevel, tech.level)

        return item
Esempio n. 16
0
    def _processResearchableTech(self, tech):
        player = client.getPlayer()

        item = ui.Item(tech.name, tLevel=tech.level, techID=tech.id)
        item.tStruct = '*' if getattr(tech, 'isStructure', None) else ''
        item.tShip = '*' if getattr(tech, 'isShipEquip', None) else ''

        neededSci = Utils.getTechRCost(player, tech.id)
        item.tETC = res.formatTime(
            float(neededSci) /
            player.effSciPoints) if player.effSciPoints > 0 else _("N/A")
        item.foreground = None

        if client.getFullTechInfo(
                tech.id
        ).finishResearchHandler == TechHandlers.finishResTLAdvance:
            item.foreground = gdata.sevColors[gdata.CRI]
        elif getattr(tech, "researchDisables", None):
            item.foreground = (0xff, 0xff, 0x00)
        return item
Esempio n. 17
0
 def show(self):
     player = client.getPlayer()
     # title
     self.win.vRQueueTitle.text = _('Research queue [%d pts/turn]') % (
         player.effSciPoints,
     )
     self.win.title = _("Research [TL%d]") % player.techLevel
     # Known techs
     items = []
     #~researchable = {}
     disabled = []
     taskIDs = {}
     for task in player.rsrchQueue:
         taskIDs[task.techID] = None
     for techID in player.techs.keys():
         if techID in player.obsoleteTechs and not self.showObsolete:
             continue
         tech = client.getTechInfo(techID)
         improvement = player.techs[techID]
         item = ui.Item(tech.name,
             techID = techID,
             tLevel = '%d-%d' % (tech.level, improvement),
             tStruct = (' ', '*')[tech.isStructure],
             tShip = (' ', '*')[tech.isShipEquip],
         )
         if improvement < Rules.techMaxImprovement and improvement < tech.maxImprovement:
             neededSci = Utils.getTechRCost(player, techID)
             if player.effSciPoints > 0:
                 item.tETC = res.formatTime(float(neededSci) / player.effSciPoints)
             else:
                 item.tETC = _("N/A")
             found = 0
             if taskIDs.has_key(techID):
                 item.foreground = (0xd0, 0xd0, 0xd0)
             else:
                 item.foreground = None
         else:
             item.tETC = res.getNA()
             item.foreground = (0x80, 0x80, 0x80)
             if not self.showCompleted:
                 # skip this item
                 continue
         if techID in player.obsoleteTechs:
             item.foreground = (0x80, 0x40, 0x40)
         items.append(item)
         disabled.extend(tech.researchDisables)
         #~for improvement in range(1, improvement + 1):
         #~    for techID in tech.researchEnables[improvement]:
         #~        researchable[techID] = 1
     self.win.vKTechs.items = items
     self.win.vKTechs.itemsChanged()
     # Research queue
     items = []
     index = 0
     queueTechs = []
     total = 0
     for task in player.rsrchQueue:
         tech = client.getTechInfo(task.techID)
         fulltech = client.getFullTechInfo(task.techID)
         queueTechs.append(task.techID)
         item = ui.Item(tech.name, techID = task.techID, index = index)
         researchSci = Utils.getTechRCost(player, task.techID, task.improvement)
         maxImprovement = min(Rules.techMaxImprovement,fulltech.maxImprovement)
         maxImpTotalSci = 0
         if task.improveToMax and task.improvement < maxImprovement:
             for impr in range(task.improvement+1,maxImprovement+1):
                 maxImpTotalSci += Utils.getTechRCost(player, task.techID, impr)
         item.tooltipTitle = _("Details")
         item.tooltip = _("Research points %d/%d, change %d pts/turn.") % (task.currSci, researchSci, task.changeSci)
         item.statustip = item.tooltip
         item.tImpToMax = ["", "*"][task.improveToMax]
         item.tImproveToMax = task.improveToMax
         if task.currSci > 0:
             item.tProgress = _("%d %%") % int(task.currSci * 100 / researchSci)
         else:
             item.tProgress = _("-")
         if task.changeSci > 0:
             value = float(researchSci - task.currSci) / max(task.changeSci, player.effSciPoints)
             total += int(value + 1)
             if player.effSciPoints > 0:
                 total += float(maxImpTotalSci) / player.effSciPoints
                 item.tETC = res.formatTime(value)
             else:
                 total = 0
                 item.tETC = res.getNA()
         elif task.changeSci < 0:
             value = - float(task.currSci) / min(task.changeSci, player.effSciPoints)
             item.tETC = _("[%s]") % res.formatTime(value)
         elif player.effSciPoints > 0:
             value = float(researchSci) / player.effSciPoints
             total += int(value + 1)
             total += float(maxImpTotalSci) / player.effSciPoints
             item.tETC = res.formatTime(value)
         else:
             item.tETC = res.getNA()
         item.tLevel = _("%d-%d") % (tech.level, task.improvement)
         items.append(item)
         index += 1
     self.win.vRQueue.items = items
     self.win.vRQueue.itemsChanged()
     self.win.vRQueueTop.enabled = 0
     self.win.vRQueueUp.enabled = 0
     self.win.vRQueueDown.enabled = 0
     self.win.vRQueueAbort.enabled = 0
     self.win.vRQueueRepat.enabled = 0
     self.win.vRQueueRepat.pressed = 0
     self.win.vRQueueInfo.enabled = 0
     if total == 0:
         self.win.vRTotal.text = _("N/A")
     else:
         self.win.vRTotal.text = res.formatTime(total)
     # Researchable techs
     items = []
     for techID in client.getAllTechIDs():
         if player.techs.has_key(techID) or techID in queueTechs \
             or techID in disabled:
             continue
         # can check requirements
         tech = client.getTechInfo(techID)
         if not hasattr(tech, "partialData"):
             continue
         item = ui.Item(tech.name, tLevel = tech.level, techID = techID)
         if hasattr(tech, 'isStructure'): item.tStruct = ('', '*')[tech.isStructure]
         else: item.tStruct = ''
         if hasattr(tech, 'isShipEquip'): item.tShip = ('', '*')[tech.isShipEquip]
         else: item.tShip = ''
         if hasattr(tech, 'researchMod'):
             neededSci = Utils.getTechRCost(player, techID)
             if player.effSciPoints > 0:
                 item.tETC = res.formatTime(float(neededSci) / player.effSciPoints)
             else:
                 item.tETC = _("N/A")
             item.foreground = None
         else:
             item.tSci = res.getNA()
             item.foreground = (0xc0, 0xc0, 0xc0)
             # skip this item
             continue
         if hasattr(tech, "researchDisables") and tech.researchDisables:
             item.foreground = (0xff, 0xff, 0x00)
         if client.getFullTechInfo(techID).finishResearchHandler == TechHandlers.finishResTLAdvance:
             item.foreground = gdata.sevColors[gdata.CRI]
         items.append(item)
     self.win.vRTechs.items = items
     self.win.vRTechs.itemsChanged()
Esempio n. 18
0
 def show(self):
     player = client.getPlayer()
     #
     items = []
     for planetID in client.db.keys():
         planet = client.get(planetID, noUpdate = 1)
         # skip non-planets
         if not hasattr(planet, "type") or planet.type != T_PLANET:
             continue
         # shall be shown?
         ok = 0
         if hasattr(planet, 'owner'):
             if self.showMine and planet.owner == player.oid:
                 ok = 1
             if self.showOtherPlayers and planet.owner != OID_NONE and \
                 planet.owner != player.oid:
                 ok = 1
             if self.showColonizable and planet.owner == OID_NONE and \
                 planet.plType not in ('G', 'A'):
                 ok = 1
             if self.showUncolonizable and planet.plType in ('G', 'A'):
                 ok = 1
         elif hasattr(planet, 'plType'):
             if self.showColonizable and planet.plType not in ('G', 'A'):
                 ok = 1
             if self.showUncolonizable and planet.plType in ('G', 'A'):
                 ok = 1
         if not ok:
             continue
         # fill in data
         #rel = REL_UNDEF
         maxNA = 999999
         maxNone = 99999
         ownerID = OID_NONE
         if hasattr(planet, 'owner'):
             ownerID = planet.owner
             #if planet.owner != OID_NONE:
             #    rel = client.getRelationTo(planet.owner)
             if planet.owner == OID_NONE:
             #else:
                 owner = _('[Nobody]')
         if hasattr(planet, 'owner') and planet.owner == player.oid:
             if planet.prodQueue and planet.effProdProd > 0:
                 index = 0
                 totalEtc = 0
                 for task in planet.prodQueue:
                     if task.isShip:
                         tech = client.getPlayer().shipDesigns[task.techID]
                     else:
                         tech = client.getFullTechInfo(task.techID)
                     if index == 0:
                         constrInfo = tech.name
                     # etc
                     if task.targetID != planetID:
                         if index == 0:
                             etc = math.ceil(float(tech.buildProd * Rules.buildOnAnotherPlanetMod - task.currProd) / planet.effProdProd)
                             totalEtc += etc
                             totalEtc += math.ceil((task.quantity - 1) * float(tech.buildProd * Rules.buildOnAnotherPlanetMod) / planet.effProdProd)
                         else:
                             totalEtc += math.ceil(float(tech.buildProd * Rules.buildOnAnotherPlanetMod - task.currProd) / planet.effProdProd)
                             totalEtc += math.ceil((task.quantity - 1) * float(tech.buildProd * Rules.buildOnAnotherPlanetMod) / planet.effProdProd)
                     else:
                         if index == 0:
                             etc = math.ceil(float(tech.buildProd - task.currProd) / planet.effProdProd)
                             totalEtc += etc
                             totalEtc += math.ceil((task.quantity - 1)* float(tech.buildProd) / planet.effProdProd)
                         else:
                             totalEtc += math.ceil(task.quantity * float(tech.buildProd - task.currProd) / planet.effProdProd)
                             totalEtc += math.ceil((task.quantity - 1) * float(tech.buildProd) / planet.effProdProd)
                     index += 1
                 etc_raw = etc
                 etc = res.formatTime(etc)
                 totalEtc_raw = totalEtc
                 totalEtc = res.formatTime(totalEtc)
             elif planet.prodQueue:
                 task = planet.prodQueue[0]
                 if task.isShip:
                     tech = client.getPlayer().shipDesigns[task.techID]
                 else:
                     tech = client.getTechInfo(task.techID)
                 constrInfo = tech.name
                 etc = _('N/A')
                 etc_raw = maxNA
                 totalEtc = _("N/A")
                 totalEtc_raw = maxNA
             elif planet.effProdProd > 0:
                 constrInfo = _("-")
                 etc = "-"
                 etc_raw = 0
                 totalEtc = _("-")
                 totalEtc_raw = 0
             else:
                 constrInfo = _("-")
                 etc = "-"
                 etc_raw = maxNone
                 totalEtc = _("-")
                 totalEtc_raw = maxNone
         else:
             constrInfo = '?'
             etc = '?'
             etc_raw = maxNA
             totalEtc = '?'
             totalEtc_raw = maxNA
         # used slots
         if hasattr(planet, 'slots'):
             freeSlots = planet.plSlots - len(planet.slots)
         else:
             freeSlots = '?'
         # morale
         if hasattr(planet, "morale"):
             morale = int(planet.morale)
         else:
             morale = "?"
         #
         plType = gdata.planetTypes[getattr(planet, 'plType', None)]
         # list item
         item = ui.Item(
             getattr(planet, 'name', res.getUnknownName()),
             tPlType = _(plType),
             tPlBio = getattr(planet, 'plBio', '?'),
             tPlMin = getattr(planet, 'plMin', '?'),
             tPlEn = getattr(planet, 'plEn', '?'),
             tChangeBio = getattr(planet, 'changeBio', '?'),
             tChangeEn = getattr(planet, 'changeEn', '?'),
             tETC = etc,
             tETC_raw = etc_raw,
             tTotalETC = totalEtc,
             tTotalETC_raw = totalEtc_raw,
             tConstrInfo = constrInfo,
             tFree = freeSlots,
             tMorale = morale,
             tSpace = getattr(planet, 'plSlots', '?'),
             tDiam = getattr(planet, 'plDiameter',0)/1000,
             tProd = getattr(planet, 'effProdProd', '?'),
             tSci = getattr(planet, 'effProdSci', '?'),
             tPlanetID = planetID,
             #foreground = res.getFFColorCode(rel),
             foreground = res.getPlayerColor(ownerID),
         )
         items.append(item)
     self.win.vPlanets.items = items
     self.win.vPlanets.itemsChanged()
     # buttons
     self.win.vMine.pressed = self.showMine
     self.win.vOtherPlayers = self.showOtherPlayers
     self.win.vColonizable = self.showColonizable
     self.win.vUncolonizable = self.showUncolonizable
Esempio n. 19
0
	def onSaveStarmapConfirm(self):
		turn = client.getTurn()
		name = res.formatTime(turn,'_')
		savedas = self.mapWidget.save(name)
		self.confirmDlg.display(_('File saved as %s' % savedas), _('OK'), False)
Esempio n. 20
0
 def _populateEta(self, fleet):
     return res.formatTime(fleet.eta) if hasattr(fleet, "eta") else "?"
Esempio n. 21
0
    def showCommands(self):
        self.win.vMoveBtn.pressed =  self.command == Const.FLACTION_MOVE
        self.win.vAttackBtn.pressed =  self.command == Const.FLACTION_DECLAREWAR
        self.win.vDeplShipBtn.pressed =  self.command == Const.FLACTION_DEPLOY
        self.win.vWaitBtn.pressed =  self.command == Const.FLACTION_WAIT
        self.win.vRefuelBtn.pressed =  self.command == Const.FLACTION_REFUEL
        self.win.vRepeatBtn.pressed =  self.command == Const.FLACTION_REPEATFROM
        self.win.vWormholeBtn.pressed =  self.command == Const.FLACTION_ENTERWORMHOLE
        # hide/show widgets
        for widget in self.win.widgets:
            if widget.tags and self.command in widget.tags:
                widget.visible = 1
            elif widget.tags:
                widget.visible = 0
        # target
        if self.targetID == Const.OID_NONE:
            info = _('No target selected')
        elif self.command in (Const.FLACTION_MOVE, Const.FLACTION_REFUEL, Const.FLACTION_ENTERWORMHOLE):
            target = client.get(self.targetID, noUpdate = 1)
            info = getattr(target, 'name', res.getUnknownName())
        elif self.command == Const.FLACTION_DEPLOY:
            target = client.get(self.targetID, noUpdate = 1)
            if target.type == Const.T_PLANET:
                info = getattr(target, 'name', res.getUnknownName())
            else:
                info = _('No planet selected')
        elif self.command == Const.FLACTION_DECLAREWAR:
            if self.targetPlayerID not in (Const.OID_NONE, client.getPlayerID()):
                target = client.get(self.targetPlayerID, noUpdate = 1)
                info = getattr(target, 'name', res.getUnknownName())
            else:
                info = _("No commander specified.")
        else:
            info = _('?')
        self.win.vTarget.text = info
        curTarget = client.get(self.targetID, noUpdate = 1)
        fleet = client.get(self.fleetDlg.fleetID, noUpdate = 1)
        target = Const.OID_NONE
        oldTarget = fleet # we can hack it - only coordinates are necessary

        waitTurns = sum([x[2] for x in fleet.actions[fleet.actionIndex:] if x[0] == Const.FLACTION_WAIT])
        eta = waitTurns # baseline
        targetIDs = [x[1] for x in fleet.actions[fleet.actionIndex:]]
        if self.targetID != Const.OID_NONE:
            targetIDs.append(self.targetID)
        for newTargetID in targetIDs:
            if newTargetID != Const.OID_NONE:
                newTarget = client.get(newTargetID)
                newEta = self._evalEta(fleet, oldTarget, newTarget)
                if newEta is not None:
                    eta += newEta
                else:
                    eta = None
                    break
                oldTarget = newTarget

        if eta is None or not targetIDs:
            self.win.vEta.text = _("N/A")
        else:
            self.win.vEta.text = res.formatTime(eta)

        # ships
        fleet = client.get(self.fleetDlg.fleetID, noUpdate = 1)
        self.deplShips = []
        # collect buildings
        for designID, a, b, c in fleet.ships: #fixed bug in reference of designID...added a, b, c to do it; breaks list lookup otherwise (not sure why) with hash error --RC
            tech = client.getPlayer().shipDesigns[designID]
            if tech.deployStructs:
                self.deplShips.append(designID)
                log.debug('Adding design with structure',designID)
            elif tech.deployHandlers:
                hasHandler = False
                for handler in tech.deployHandlers:
                    if handler != '': #why are blank handlers getting added in ship construction? catch here for now
                        hasHandler = True
                        break
                if hasHandler:
                    self.deplShips.append(designID)
                    log.debug('Adding design with project',designID)
        # correct buildingIndex
        if self.deplShipIndex >= len(self.deplShips):
            self.deplShipIndex = 0
        if self.deplShips:
            self.win.vDeplShipBtn.enabled = 1
            techID = self.deplShips[self.deplShipIndex]
            self.win.vDeplShip.text = client.getPlayer().shipDesigns[techID].name
            self.win.vDeplShip.data = techID
        else:
            self.win.vDeplShipBtn.enabled = 0
            if self.command == Const.FLACTION_DEPLOY:
                self.command == Const.FLACTION_MOVE
                self.showCommands()
Esempio n. 22
0
    def show(self):
        critical = self.win.vCritical.checked
        major = self.win.vMajor.checked
        minor = self.win.vMinor.checked
        info = self.win.vInfo.checked

        disp = 1

        player = client.getPlayer()
        items = []
        # object list (all player's objects + systems)
        objects = player.fleets[:]
        objects += player.planets[:]
        systems = {}
        for planetID in player.planets:
            planet = client.get(planetID)
            if planet.compOf not in systems:
                systems[planet.compOf] = None
        objects += systems.keys()

        # counting construction points value of each global production queue
        # holder for (number , eff production) of planets set to each queue
        globalQueueStats=[(0,0), (0,0), (0,0), (0,0), (0,0)]
        prodQueueProblems = []


        # go through all objects
        for objID in objects:
            if objID < OID_FREESTART:
                continue
            obj = client.get(objID, noUpdate = 1)
            if not hasattr(obj, "type"):
                continue
            if obj.type == T_SYSTEM:
                if not hasattr(obj, 'planets'):
                    continue
                bio = 0
                totalBio = 0
                en = 0
                totalEn = 0
                buildingQuantity = {}
                buildingInfo = {}
                # holds modified planets
                planetCopies = {}

                for planetID in obj.planets:
                    planet = client.get(planetID, noUpdate = 1)
                    # copy of planet to change plSlots count
                    if not planetID in planetCopies:
                        cPlanet = copy.deepcopy(planet)
                        planetCopies[planetID] = cPlanet
                    else:
                        cPlanet = planetCopies[planetID]
                    if hasattr(planet, 'owner') and planet.owner == player.oid:
                        queuePlanetNumber, queueEffProd = globalQueueStats[planet.globalQueue]
                        queuePlanetNumber += 1
                        queueEffProd += planet.effProdProd
                        globalQueueStats[planet.globalQueue] = (queuePlanetNumber, queueEffProd)
                        # compute bio and en for system
                        bio += planet.changeBio
                        totalBio += max(0, planet.storBio - planet.minBio)
                        en  += planet.changeEn
                        totalEn += max(0, planet.storEn - planet.minEn)
                        # the planet needs to have global queue 0 - the default one - to have its queue reported
                        if hasattr(planet, 'prodQueue') and self.win.vPlanets.checked and not planet.globalQueue:
                            totalEtc = 0
                            # compute length of production queue
                            if cPlanet.prodQueue and cPlanet.effProdProd > 0:
                                for task in cPlanet.prodQueue:
                                    if task.isShip:
                                        tech = client.getPlayer().shipDesigns[task.techID]
                                    else:
                                        tech = client.getFullTechInfo(task.techID)
                                        if tech.isStructure and hasattr(task, "demolishStruct") and task.demolishStruct == 0:
                                            # total count of constructing buildings on target
                                            if buildingQuantity.has_key(task.targetID):
                                                buildingQuantity[task.targetID] += task.quantity
                                            else:
                                                buildingQuantity[task.targetID] = task.quantity

                                            # information about source and target of constructing
                                            if buildingInfo.has_key((planetID, task.targetID)):
                                                buildingInfo[(planetID, task.targetID)] += task.quantity
                                            else:
                                                buildingInfo[(planetID, task.targetID)] = task.quantity
                                        elif tech.isProject and tech.id == 3802:
                                            # we are constructing Habitable Surface Expansion
                                            # so after construction we got some new slots on planet
                                            if not task.targetID in planetCopies:
                                                targetPlanet = client.get(task.targetID, noUpdate = 1)
                                                cPlanet = copy.deepcopy(targetPlanet)
                                                planetCopies[task.targetID] = cPlanet

                                            planetCopies[task.targetID].plSlots += task.quantity

                                    if task.targetID != planetID:
                                        totalEtc += math.ceil(float(tech.buildProd * Rules.buildOnAnotherPlanetMod - task.currProd) / planet.effProdProd)
                                        totalEtc += math.ceil((task.quantity - 1) * float(tech.buildProd * Rules.buildOnAnotherPlanetMod) / planet.effProdProd)
                                    else:
                                        totalEtc += math.ceil(task.quantity * float(tech.buildProd - task.currProd) / planet.effProdProd)
                                        totalEtc += math.ceil((task.quantity - 1) * float(tech.buildProd) / planet.effProdProd)
                            else:
                                totalEtc = 99999

                            prodQueueProblems.append((planetID, totalEtc, len(planet.prodQueue)))


                        # check for structures status
                        if hasattr(planet, 'slots') and self.win.vPlanets.checked:
                            for struct in planet.slots:
                                status = struct[STRUCT_IDX_STATUS]
                                problem = None
                                tech = client.getFullTechInfo(struct[STRUCT_IDX_TECHID])

                                if hasattr(player, 'techs'):
                                    techEff = Rules.techImprEff[player.techs.get(struct[STRUCT_IDX_TECHID], Rules.techBaseImprovement)]
                                else:
                                    techEff = Rules.techImprEff[Rules.techBaseImprovement]

                                HPturn = max(1, int(0.02 * tech.maxHP * techEff))
                                turnsToDestroy = math.ceil(struct[STRUCT_IDX_HP] / HPturn)

                                if turnsToDestroy < 48:
                                    dispDestr = major
                                    fgColorDestr = gdata.sevColors[gdata.MAJ]
                                    if turnsToDestroy < 24:
                                        dispDestr = critical
                                        fgColorDestr = gdata.sevColors[gdata.CRI]
                                else:
                                    dispDestr = minor
                                    fgColorDestr = None

                                if not status & STRUCT_STATUS_ON:
                                    # structure is off
                                    if dispDestr:
                                        items.append(ui.Item(planet.name, tOID = planetID, tType = T_PLANET, foreground = fgColorDestr,
                                            vDescription = _('Structure (%s) is off and will be destroyed in %s turns.') % (tech.name, res.formatTime(turnsToDestroy))))

                                elif status & STRUCT_STATUS_DETER:
                                    problem = _('is deteriorating and will be destroyed in %s turns') % res.formatTime(turnsToDestroy)
                                    disp = major
                                    fgColor = gdata.sevColors[gdata.MAJ]
                                elif status & STRUCT_STATUS_NOBIO:
                                    problem = _('has insufficient supply of biomatter')
                                    disp = info
                                    fgColor = gdata.sevColors[gdata.INFO]
                                elif status & STRUCT_STATUS_NOEN:
                                    problem = _('has insufficient supply of energy')
                                    disp = info
                                    fgColor = gdata.sevColors[gdata.INFO]
                                elif status & STRUCT_STATUS_NOPOP:
                                    problem = _('has insufficient supply of workers')
                                    disp = info
                                    fgColor = gdata.sevColors[gdata.INFO]
                                elif status & STRUCT_STATUS_REPAIRING:
                                    problem = _('is repairing')
                                    disp = info
                                    fgColor = gdata.sevColors[gdata.INFO]

                                if problem and disp:
                                    items.append(ui.Item(planet.name, tOID = planetID, tType = T_PLANET, foreground = fgColor,
                                        vDescription = _('Structure (%s) %s.') % (tech.name, problem)))

                for planetID, quantity in buildingQuantity.items():
                    planet = planetCopies[planetID]
                    # test, if there is total quantity of building as target for this planet
                    if planet.plSlots < len(planet.slots) + quantity and major:
                        # walk infos and search for all planets, that are building
                        # on planet founded above
                        for (sourceID, targetID), quantity in buildingInfo.items():
                            if planetID == targetID:
                                source = client.get(sourceID, noUpdate = 1)
                                items.append(ui.Item(source.name, tOID = sourceID, tType = T_PLANET, foreground = gdata.sevColors[gdata.MAJ],
                                            vDescription = _('There is no space for all constructed buildings on %s.') % (planet.name)))

                # check bio for system
                if bio < 0 and self.win.vSystems.checked:
                    disp = minor
                    fgColor = None
                    surplusTurns = totalBio / (-bio)
                    if surplusTurns < 168:
                        disp = major
                        fgColor = gdata.sevColors[gdata.MAJ]
                    if surplusTurns < 48:
                        disp = critical
                        fgColor = gdata.sevColors[gdata.CRI]

                    if disp:
                        if totalBio > 0:
                            items.append(ui.Item(obj.name, tOID = obj.oid, tType = T_SYSTEM, foreground = fgColor,
                                         vDescription = _('Bio decreasing - last turn change %d, surplus %d (%s).') % (bio, totalBio,res.formatTime(surplusTurns))))
                        else:
                            items.append(ui.Item(obj.name, tOID = obj.oid, tType = T_SYSTEM, foreground = fgColor,
                                         vDescription = _('Bio decreasing - last turn change %d, surplus %d.') % (bio, totalBio)))

                #check en for system
                if en < 0 and self.win.vSystems.checked:
                    disp = minor
                    fgColor = None
                    surplusTurns = totalEn / (-en)
                    if surplusTurns < 168:
                        disp = major
                        fgColor = gdata.sevColors[gdata.MAJ]
                    if surplusTurns < 48:
                        disp = critical
                        fgColor = gdata.sevColors[gdata.CRI]

                    if disp:
                        if totalEn > 0:
                            items.append(ui.Item(obj.name, tOID = obj.oid, tType = T_SYSTEM, foreground = fgColor,
                                        vDescription = _('Energy decreasing - last turn change %d, surplus %d (%s).') % (en, totalEn,res.formatTime(surplusTurns))))
                        else:
                            items.append(ui.Item(obj.name, tOID = obj.oid, tType = T_SYSTEM, foreground = fgColor,
                                         vDescription = _('Energy decreasing - last turn change %d, surplus %d.') % (en, totalEn)))

            # check fleets
            elif obj.type == T_FLEET and self.win.vFleets.checked:
                if hasattr(obj, 'owner') and obj.owner == player.oid:
                    energyReserve = obj.storEn  * 100 / obj.maxEn
                    system = None
                    disp = major
                    fgColor = gdata.sevColors[gdata.MAJ]
                    note = _(' and IS NOT refueling')

                    maxRefuelMax = 0
                    if hasattr(obj, 'orbiting') and obj.orbiting:
                        system = client.get(obj.orbiting, noUpdate = 1)
                        if hasattr(system, 'planets'):
                            for planetID in system.planets:
                                planet = client.get(planetID, noUpdate = 1)
                                if hasattr(planet, 'owner') and hasattr(planet, 'refuelMax'):
                                    if player.diplomacyRels.has_key(planet.owner):
                                        dipl = client.getDiplomacyWith(planet.owner)
                                        if dipl.pacts.has_key(PACT_ALLOW_TANKING) and dipl.pacts[PACT_ALLOW_TANKING][0] == PACT_ACTIVE:
                                            maxRefuelMax = max(maxRefuelMax, planet.refuelMax)
                                    else:
                                        if planet.owner == player.oid:
                                            maxRefuelMax = max(maxRefuelMax, planet.refuelMax)

                            if maxRefuelMax > 0:
                                disp = info
                                fgColor = gdata.sevColors[gdata.INFO]
                                note = _(' and IS refueling')
                                if maxRefuelMax <= energyReserve:
                                    note = _(' and CAN refuel, but reach planet maximum refuel amount')

                    else:
                        continue

                    systemName = res.getUnknownName()
                    if system and hasattr(system, "name"):
                        systemName = system.name

                    # check fleets energy reserve
                    if energyReserve < 50 and maxRefuelMax == 0:
                        disp = major
                        fgColor = gdata.sevColors[gdata.MAJ]
                        if energyReserve < 25 and maxRefuelMax == 0:
                            disp = critical
                            fgColor = gdata.sevColors[gdata.CRI]
                    else:
                        fgColor = gdata.sevColors[gdata.INFO]
                        disp = info

                    # is fleet named?
                    if hasattr(obj,'customname') and obj.customname:
                        name = obj.customname
                    else:
                        name = getattr(obj, "name", None)

                    if energyReserve == 100 and info and disp:
                        items.append(ui.Item(systemName, tOID = obj.oid, tType = T_FLEET,foreground = gdata.sevColors[gdata.INFO],
                                    vDescription = _('Fleet "%s" has full fuel tanks.') % (name)))
                    elif disp:
                        items.append(ui.Item(systemName, tOID = obj.oid, tType = T_FLEET,foreground = fgColor,
                                    vDescription = _('Fleet "%s" is low on fuel [%d %%]%s.') % (name, energyReserve, note)))


        queConstValues = [0, 0, 0, 0, 0]
        queEtc = [0, 0, 0, 0, 0]
        for queue in xrange(5):
            quePlanets, queEffProd = globalQueueStats[queue]
            for task in player.prodQueues[queue]:
                if task.isShip:
                    tech = client.getPlayer().shipDesigns[task.techID]
                else:
                    tech = client.getFullTechInfo(task.techID)
                queConstValues[queue] += task.quantity * tech.buildProd
            if queEffProd > 0:
                queEtc[queue] = math.ceil(float(queConstValues[queue])/queEffProd)
            else:
                queEtc[queue] = 99999

        # creation of items with production queue [default one] problems
        for planetID, totalEtc, queueLen in prodQueueProblems:
            planet = client.get(planetID, noUpdate = 1)

            # check empty production queue
            if queueLen == 0 and planet.effProdProd > 0 and queConstValues[0] == 0 and critical:
                items.append(ui.Item(planet.name, tOID = planetID, tType = T_PLANET,
                    foreground = gdata.sevColors[gdata.CRI],
                    vDescription = _('Production queue is empty.')))

            # check end of production queue
            if totalEtc+queEtc[0] < 48:
                fgColor = None
                disp = minor
                if totalEtc+queEtc[0] < 24:
                    disp = major
                    fgColor = gdata.sevColors[gdata.MAJ]
                    if disp:
                        items.append(ui.Item(planet.name, tOID = planetID, tType = T_PLANET, foreground = fgColor,
                            vDescription = _('Production queue may end in {0} turns ({1} directly in planet queue), {2} item(s) on list.'.format(res.formatTime(totalEtc+queEtc[0]), res.formatTime(totalEtc), queueLen))))

        # creation of items with global queue problems
        for queue in xrange(1, 5):
            queName = res.globalQueueName(queue)
            quePlanets = globalQueueStats[queue][0]
            # check empty global production queue with at least one planet [so its relevant]
            if queConstValues[queue] == 0 and  quePlanets > 0 and critical:
                items.append(ui.Item(_('Global queue ' + queName), tType = T_QUEUE,
                    foreground = gdata.sevColors[gdata.CRI],
                    vDescription = _('Global production queue {0} used by {1} planet(s) is empty.'.format(queName, quePlanets))))

            # check end of global production queue
            elif queEtc[queue] < 48:
                fgColor = None
                disp = minor
                if queEtc[queue] < 24:
                    disp = major
                    fgColor = gdata.sevColors[gdata.MAJ]
                if disp:
                    items.append(ui.Item(_('Global queue ' + queName), tType = T_QUEUE, foreground = fgColor,
                        vDescription = _('Global production queue {0} used by {1} planet(s) runs out in {2} turns.'.format(queName, quePlanets, res.formatTime(queEtc[queue])))))

        # check research queue
        if self.win.vResearch.checked:
            totalEtc = 0
            # compute length of research queue
            for task in player.rsrchQueue:
                tech = client.getTechInfo(task.techID)
                fulltech = client.getFullTechInfo(task.techID)
                researchSci = Utils.getTechRCost(player, task.techID, task.improvement)
                maxImprovement = min(Rules.techMaxImprovement,fulltech.maxImprovement)
                maxImpTotalSci = 0
                if task.improveToMax and task.improvement < maxImprovement:
                    for impr in range(task.improvement+1,maxImprovement+1):
                        maxImpTotalSci += Utils.getTechRCost(player, task.techID, impr)
                if task.changeSci > 0:
                    value = float(researchSci - task.currSci) / max(task.changeSci, player.effSciPoints)
                    totalEtc += int(value + 1)
                    if player.effSciPoints != 0:
                        totalEtc += float(maxImpTotalSci) / player.effSciPoints
                elif task.changeSci < 0:
                    totalEtc -= float(task.currSci) / min(task.changeSci, player.effSciPoints)
                elif player.effSciPoints > 0:
                    value = float(researchSci) / player.effSciPoints
                    totalEtc += int(value + 1)
                    totalEtc += float(maxImpTotalSci) / player.effSciPoints
                else:
                    totalEtc = 99999
                    break

            # check empty research queue
            if totalEtc == 0 and len(player.rsrchQueue) == 0 and player.effSciPoints > 0 and major:
                items.append(ui.Item(_('Research'), tType = T_TECHNOLOGY, foreground = gdata.sevColors[gdata.MAJ],
                    vDescription = _('Research queue is empty.')))
            # check short reseach queue
            elif totalEtc < 48:
                disp = minor
                fgColor = None
                if totalEtc < 24:
                    disp = major
                    fgColor = gdata.sevColors[gdata.MAJ]

                if disp:
                    items.append(ui.Item(_('Research'), tType = T_TECHNOLOGY, foreground = fgColor,
                                vDescription = _('Research queue ends in %s turns, %d item(s) on list.') % (res.formatTime(totalEtc), len(player.rsrchQueue))))

        self.win.vProblems.items = items
        self.win.vProblems.itemsChanged()
Esempio n. 23
0
	def onSaveStarmapConfirm(self):
		turn = client.getTurn()
		name = res.formatTime(turn,'_')
		savedas = self.mapWidget.save(name)
		self.confirmDlg.display(_('File saved as %s' % savedas), _('OK'), False)
Esempio n. 24
0
	def showCommands(self):
		self.win.vMoveBtn.pressed =  self.command == FLACTION_MOVE
		self.win.vAttackBtn.pressed =  self.command == FLACTION_DECLAREWAR
		self.win.vDeplShipBtn.pressed =  self.command == FLACTION_DEPLOY
		self.win.vWaitBtn.pressed =  self.command == FLACTION_WAIT
		self.win.vRefuelBtn.pressed =  self.command == FLACTION_REFUEL
		self.win.vRepeatBtn.pressed =  self.command == FLACTION_REPEATFROM
		self.win.vWormholeBtn.pressed =  self.command == FLACTION_ENTERWORMHOLE
		# hide/show widgets
		for widget in self.win.widgets:
			if widget.tags and self.command in widget.tags:
				widget.visible = 1
			elif widget.tags:
				widget.visible = 0
		# target
		if self.targetID == OID_NONE:
			info = _('No target selected')
		elif self.command in (FLACTION_MOVE, FLACTION_REFUEL, FLACTION_ENTERWORMHOLE):
			target = client.get(self.targetID, noUpdate = 1)
			info = getattr(target, 'name', res.getUnknownName())
		elif self.command == FLACTION_DEPLOY:
			target = client.get(self.targetID, noUpdate = 1)
			if target.type == T_PLANET:
				info = getattr(target, 'name', res.getUnknownName())
			else:
				info = _('No planet selected')
		elif self.command == FLACTION_DECLAREWAR:
			if self.targetPlayerID not in (OID_NONE, client.getPlayerID()):
				target = client.get(self.targetPlayerID, noUpdate = 1)
				info = getattr(target, 'name', res.getUnknownName())
			else:
				info = _("No commander specified.")
		else:
			info = _('?')
		self.win.vTarget.text = info
		if self.targetID != OID_NONE:
			curTarget = client.get(self.targetID, noUpdate = 1)
			fleet = client.get(self.fleetDlg.fleetID, noUpdate = 1)
			target = OID_NONE
			if len(fleet.actions) > 1:
				if self.cmdIndex != 0 and self.cmdIndex < len(fleet.actions):
					idx = self.cmdIndex
				else:
					idx = len(fleet.actions)
				while True:
					idx -= 1
					if idx < 0:
						break
					#print "idx", idx, fleet.actions[idx]
					action, target, actionData = fleet.actions[idx]
					if target != OID_NONE:
						break
			if fleet.orbiting != OID_NONE and target == OID_NONE:
				target = fleet.orbiting
			elif target == OID_NONE:
				target = fleet.oid

			if target != OID_NONE:
				lastTarget = client.get(target, noUpdate = 1)
				curX = curTarget.x
				curY = curTarget.y
				lstX = lastTarget.x
				lstY = lastTarget.y
				dx = curX - lstX
				dy = curY - lstY
				lnght = math.sqrt(dx*dx + dy*dy)
				speedBoost = getattr(fleet, "speedBoost", 1)
				fleetSpeed = getattr(fleet, "speed", 0)
				maxDelta = fleetSpeed / Rules.turnsPerDay * speedBoost
				if maxDelta != 0:
					eta = lnght / maxDelta
					self.win.vEta.text = res.formatTime(eta)
				else:
					self.win.vEta.text = _("N/A")
			else:
				self.win.vEta.text = _("N/A")

		# ships
		fleet = client.get(self.fleetDlg.fleetID, noUpdate = 1)
		self.deplShips = []
		# collect buildings
                for designID, a, b, c in fleet.ships: #fixed bug in reference of designID...added a, b, c to do it; breaks list lookup otherwise (not sure why) with hash error --RC
			tech = client.getPlayer().shipDesigns[designID]
			if tech.deployStructs:
				self.deplShips.append(designID)
				log.debug('Adding design with structure',designID)
			elif tech.deployHandlers:
				hasHandler = False
				for handler in tech.deployHandlers:
					if handler != '': #why are blank handlers getting added in ship construction? catch here for now
						hasHandler = True
						break
				if hasHandler:
					self.deplShips.append(designID)
					log.debug('Adding design with project',designID)
		# correct buildingIndex
		if self.deplShipIndex >= len(self.deplShips):
			self.deplShipIndex = 0
		if self.deplShips:
			self.win.vDeplShipBtn.enabled = 1
			techID = self.deplShips[self.deplShipIndex]
			self.win.vDeplShip.text = client.getPlayer().shipDesigns[techID].name
			self.win.vDeplShip.data = techID
		else:
			self.win.vDeplShipBtn.enabled = 0
			if self.command == FLACTION_DEPLOY:
				self.command == FLACTION_MOVE
				self.showCommands()
Esempio n. 25
0
    def show(self):
        critical = self.win.vCritical.checked
        major = self.win.vMajor.checked
        minor = self.win.vMinor.checked
        info = self.win.vInfo.checked

        disp = 1

        player = client.getPlayer()
        items = []
        # object list (all player's objects + systems)
        objects = player.fleets[:]
        objects += player.planets[:]
        systems = {}
        for planetID in player.planets:
            planet = client.get(planetID)
            if planet.compOf not in systems:
                systems[planet.compOf] = None
        objects += systems.keys()

        # counting construction points value of each global production queue
        # holder for (number , eff production) of planets set to each queue
        globalQueueStats = [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]
        prodQueueProblems = []

        # go through all objects
        for objID in objects:
            if objID < Const.OID_FREESTART:
                continue
            obj = client.get(objID, noUpdate=1)
            if not hasattr(obj, "type"):
                continue
            if obj.type == Const.T_SYSTEM:
                if not hasattr(obj, 'planets'):
                    continue
                bio = 0
                totalBio = 0
                en = 0
                totalEn = 0
                buildingQuantity = {}
                buildingInfo = {}
                # holds modified planets
                planetCopies = {}

                for planetID in obj.planets:
                    planet = client.get(planetID, noUpdate=1)
                    # copy of planet to change plSlots count
                    if not planetID in planetCopies:
                        cPlanet = copy.deepcopy(planet)
                        planetCopies[planetID] = cPlanet
                    else:
                        cPlanet = planetCopies[planetID]
                    if hasattr(planet, 'owner') and planet.owner == player.oid:
                        queuePlanetNumber, queueEffProd = globalQueueStats[
                            planet.globalQueue]
                        queuePlanetNumber += 1
                        queueEffProd += planet.effProdProd
                        globalQueueStats[planet.globalQueue] = (
                            queuePlanetNumber, queueEffProd)
                        # compute bio and en for system
                        bio += planet.changeBio
                        totalBio += max(0, planet.storBio - planet.minBio)
                        en += planet.changeEn
                        totalEn += max(0, planet.storEn - planet.minEn)
                        # the planet needs to have global queue 0 - the default one - to have its queue reported
                        if hasattr(
                                planet, 'prodQueue'
                        ) and self.win.vPlanets.checked and not planet.globalQueue:
                            totalEtc = 0
                            # compute length of production queue
                            if cPlanet.prodQueue and cPlanet.effProdProd > 0:
                                for task in cPlanet.prodQueue:
                                    if task.isShip:
                                        tech = client.getPlayer().shipDesigns[
                                            task.techID]
                                    else:
                                        tech = client.getFullTechInfo(
                                            task.techID)
                                        if tech.isStructure and hasattr(
                                                task, "demolishStruct"
                                        ) and task.demolishStruct == 0:
                                            # total count of constructing buildings on target
                                            if buildingQuantity.has_key(
                                                    task.targetID):
                                                buildingQuantity[
                                                    task.
                                                    targetID] += task.quantity
                                            else:
                                                buildingQuantity[
                                                    task.
                                                    targetID] = task.quantity

                                            # information about source and target of constructing
                                            if buildingInfo.has_key(
                                                (planetID, task.targetID)):
                                                buildingInfo[(
                                                    planetID, task.targetID
                                                )] += task.quantity
                                            else:
                                                buildingInfo[(
                                                    planetID, task.targetID
                                                )] = task.quantity
                                        elif tech.isProject and tech.id == 3802:
                                            # we are constructing Habitable Surface Expansion
                                            # so after construction we got some new slots on planet
                                            if not task.targetID in planetCopies:
                                                targetPlanet = client.get(
                                                    task.targetID, noUpdate=1)
                                                cPlanet = copy.deepcopy(
                                                    targetPlanet)
                                                planetCopies[
                                                    task.targetID] = cPlanet

                                            planetCopies[
                                                task.
                                                targetID].plSlots += task.quantity

                                    if task.targetID != planetID:
                                        totalEtc += math.ceil(
                                            float(tech.buildProd *
                                                  Rules.buildOnAnotherPlanetMod
                                                  - task.currProd) /
                                            planet.effProdProd)
                                        totalEtc += math.ceil(
                                            (task.quantity - 1) * float(
                                                tech.buildProd *
                                                Rules.buildOnAnotherPlanetMod)
                                            / planet.effProdProd)
                                    else:
                                        totalEtc += math.ceil(
                                            task.quantity *
                                            float(tech.buildProd -
                                                  task.currProd) /
                                            planet.effProdProd)
                                        totalEtc += math.ceil(
                                            (task.quantity - 1) *
                                            float(tech.buildProd) /
                                            planet.effProdProd)
                            else:
                                totalEtc = 99999

                            prodQueueProblems.append(
                                (planetID, totalEtc, len(planet.prodQueue)))

                        # check for structures status
                        if hasattr(planet,
                                   'slots') and self.win.vPlanets.checked:
                            for struct in planet.slots:
                                status = struct[Const.STRUCT_IDX_STATUS]
                                problem = None
                                tech = client.getFullTechInfo(
                                    struct[Const.STRUCT_IDX_TECHID])

                                if hasattr(player, 'techs'):
                                    techEff = Rules.techImprEff[
                                        player.techs.get(
                                            struct[Const.STRUCT_IDX_TECHID],
                                            Rules.techBaseImprovement)]
                                else:
                                    techEff = Rules.techImprEff[
                                        Rules.techBaseImprovement]

                                HPturn = max(1,
                                             int(0.02 * tech.maxHP * techEff))
                                turnsToDestroy = math.ceil(
                                    struct[Const.STRUCT_IDX_HP] / HPturn)

                                if turnsToDestroy < 48:
                                    dispDestr = major
                                    fgColorDestr = gdata.sevColors[gdata.MAJ]
                                    if turnsToDestroy < 24:
                                        dispDestr = critical
                                        fgColorDestr = gdata.sevColors[
                                            gdata.CRI]
                                else:
                                    dispDestr = minor
                                    fgColorDestr = None

                                if not status & Const.STRUCT_STATUS_ON:
                                    # structure is off
                                    if dispDestr:
                                        items.append(
                                            ui.Item(
                                                planet.name,
                                                tOID=planetID,
                                                tType=Const.T_PLANET,
                                                foreground=fgColorDestr,
                                                vDescription=
                                                _('Structure (%s) is off and will be destroyed in %s turns.'
                                                  ) %
                                                (tech.name,
                                                 res.formatTime(turnsToDestroy)
                                                 )))

                                elif status & Const.STRUCT_STATUS_DETER:
                                    problem = _('is deteriorating')
                                    disp = major
                                    fgColor = gdata.sevColors[gdata.MAJ]
                                elif status & Const.STRUCT_STATUS_NOBIO:
                                    problem = _(
                                        'has insufficient supply of biomatter')
                                    disp = info
                                    fgColor = gdata.sevColors[gdata.INFO]
                                elif status & Const.STRUCT_STATUS_NOEN:
                                    problem = _(
                                        'has insufficient supply of energy')
                                    disp = info
                                    fgColor = gdata.sevColors[gdata.INFO]
                                elif status & Const.STRUCT_STATUS_NOPOP:
                                    problem = _(
                                        'has insufficient supply of workers')
                                    disp = info
                                    fgColor = gdata.sevColors[gdata.INFO]
                                elif status & Const.STRUCT_STATUS_REPAIRING:
                                    problem = _('is repairing')
                                    disp = info
                                    fgColor = gdata.sevColors[gdata.INFO]

                                if problem and disp:
                                    items.append(
                                        ui.Item(planet.name,
                                                tOID=planetID,
                                                tType=Const.T_PLANET,
                                                foreground=fgColor,
                                                vDescription=_(
                                                    'Structure (%s) %s.') %
                                                (tech.name, problem)))

                for planetID, quantity in buildingQuantity.items():
                    planet = planetCopies[planetID]
                    # test, if there is total quantity of building as target for this planet
                    if planet.plSlots < len(planet.slots) + quantity and major:
                        # walk infos and search for all planets, that are building
                        # on planet founded above
                        for (sourceID,
                             targetID), quantity in buildingInfo.items():
                            if planetID == targetID:
                                source = client.get(sourceID, noUpdate=1)
                                items.append(
                                    ui.Item(
                                        source.name,
                                        tOID=sourceID,
                                        tType=Const.T_PLANET,
                                        foreground=gdata.sevColors[gdata.MAJ],
                                        vDescription=
                                        _('There is no space for all constructed buildings on %s.'
                                          ) % (planet.name)))

                # check bio for system
                if bio < 0 and self.win.vSystems.checked:
                    disp = minor
                    fgColor = None
                    surplusTurns = totalBio / (-bio)
                    if surplusTurns < 168:
                        disp = major
                        fgColor = gdata.sevColors[gdata.MAJ]
                    if surplusTurns < 48:
                        disp = critical
                        fgColor = gdata.sevColors[gdata.CRI]

                    if disp:
                        if totalBio > 0:
                            items.append(
                                ui.Item(
                                    obj.name,
                                    tOID=obj.oid,
                                    tType=Const.T_SYSTEM,
                                    foreground=fgColor,
                                    vDescription=
                                    _('Bio decreasing - last turn change %d, surplus %d (%s).'
                                      ) % (bio, totalBio,
                                           res.formatTime(surplusTurns))))
                        else:
                            items.append(
                                ui.Item(
                                    obj.name,
                                    tOID=obj.oid,
                                    tType=Const.T_SYSTEM,
                                    foreground=fgColor,
                                    vDescription=
                                    _('Bio decreasing - last turn change %d, surplus %d.'
                                      ) % (bio, totalBio)))

                #check en for system
                if en < 0 and self.win.vSystems.checked:
                    disp = minor
                    fgColor = None
                    surplusTurns = totalEn / (-en)
                    if surplusTurns < 168:
                        disp = major
                        fgColor = gdata.sevColors[gdata.MAJ]
                    if surplusTurns < 48:
                        disp = critical
                        fgColor = gdata.sevColors[gdata.CRI]

                    if disp:
                        if totalEn > 0:
                            items.append(
                                ui.Item(
                                    obj.name,
                                    tOID=obj.oid,
                                    tType=Const.T_SYSTEM,
                                    foreground=fgColor,
                                    vDescription=
                                    _('Energy decreasing - last turn change %d, surplus %d (%s).'
                                      ) % (en, totalEn,
                                           res.formatTime(surplusTurns))))
                        else:
                            items.append(
                                ui.Item(
                                    obj.name,
                                    tOID=obj.oid,
                                    tType=Const.T_SYSTEM,
                                    foreground=fgColor,
                                    vDescription=
                                    _('Energy decreasing - last turn change %d, surplus %d.'
                                      ) % (en, totalEn)))

            # check fleets
            elif obj.type == Const.T_FLEET and self.win.vFleets.checked:
                if hasattr(obj, 'owner') and obj.owner == player.oid:
                    energyReserve = obj.storEn * 100 / obj.maxEn
                    system = None
                    disp = major
                    fgColor = gdata.sevColors[gdata.MAJ]
                    note = _(' and IS NOT refueling')

                    maxRefuelMax = 0
                    if hasattr(obj, 'orbiting') and obj.orbiting:
                        system = client.get(obj.orbiting, noUpdate=1)
                        if hasattr(system, 'planets'):
                            for planetID in system.planets:
                                planet = client.get(planetID, noUpdate=1)
                                if hasattr(planet, 'owner') and hasattr(
                                        planet, 'refuelMax'):
                                    if player.diplomacyRels.has_key(
                                            planet.owner):
                                        dipl = client.getDiplomacyWith(
                                            planet.owner)
                                        if dipl.pacts.has_key(
                                                Const.PACT_ALLOW_TANKING
                                        ) and dipl.pacts[
                                                Const.PACT_ALLOW_TANKING][
                                                    0] == Const.PACT_ACTIVE:
                                            maxRefuelMax = max(
                                                maxRefuelMax, planet.refuelMax)
                                    else:
                                        if planet.owner == player.oid:
                                            maxRefuelMax = max(
                                                maxRefuelMax, planet.refuelMax)

                            if maxRefuelMax > 0:
                                disp = info
                                fgColor = gdata.sevColors[gdata.INFO]
                                note = _(' and IS refueling')
                                if maxRefuelMax <= energyReserve:
                                    note = _(
                                        ' and CAN refuel, but reach planet maximum refuel amount'
                                    )

                    else:
                        continue

                    systemName = res.getUnknownName()
                    if system and hasattr(system, "name"):
                        systemName = system.name

                    # check fleets energy reserve
                    if energyReserve < 50 and maxRefuelMax == 0:
                        disp = major
                        fgColor = gdata.sevColors[gdata.MAJ]
                        if energyReserve < 25 and maxRefuelMax == 0:
                            disp = critical
                            fgColor = gdata.sevColors[gdata.CRI]
                    else:
                        fgColor = gdata.sevColors[gdata.INFO]
                        disp = info

                    # is fleet named?
                    if hasattr(obj, 'customname') and obj.customname:
                        name = obj.customname
                    else:
                        name = getattr(obj, "name", None)

                    if energyReserve == 100 and info and disp:
                        items.append(
                            ui.Item(systemName,
                                    tOID=obj.oid,
                                    tType=Const.T_FLEET,
                                    foreground=gdata.sevColors[gdata.INFO],
                                    vDescription=_(
                                        'Fleet "%s" has full fuel tanks.') %
                                    (name)))
                    elif disp:
                        items.append(
                            ui.Item(
                                systemName,
                                tOID=obj.oid,
                                tType=Const.T_FLEET,
                                foreground=fgColor,
                                vDescription=_(
                                    'Fleet "%s" is low on fuel [%d %%]%s.') %
                                (name, energyReserve, note)))

        queConstValues = [0, 0, 0, 0, 0]
        queEtc = [0, 0, 0, 0, 0]
        for queue in xrange(5):
            quePlanets, queEffProd = globalQueueStats[queue]
            for task in player.prodQueues[queue]:
                if task.isShip:
                    tech = client.getPlayer().shipDesigns[task.techID]
                else:
                    tech = client.getFullTechInfo(task.techID)
                queConstValues[queue] += task.quantity * tech.buildProd
            if queEffProd > 0:
                queEtc[queue] = math.ceil(
                    float(queConstValues[queue]) / queEffProd)
            else:
                queEtc[queue] = 99999

        # creation of items with production queue [default one] problems
        for planetID, totalEtc, queueLen in prodQueueProblems:
            planet = client.get(planetID, noUpdate=1)

            # check empty production queue
            if queueLen == 0 and planet.effProdProd > 0 and queConstValues[
                    0] == 0 and critical:
                items.append(
                    ui.Item(planet.name,
                            tOID=planetID,
                            tType=Const.T_PLANET,
                            foreground=gdata.sevColors[gdata.CRI],
                            vDescription=_('Production queue is empty.')))

            # check end of production queue
            if totalEtc + queEtc[0] < 48:
                fgColor = None
                disp = minor
                if totalEtc + queEtc[0] < 24:
                    disp = major
                    fgColor = gdata.sevColors[gdata.MAJ]
                    if disp:
                        items.append(
                            ui.Item(
                                planet.name,
                                tOID=planetID,
                                tType=Const.T_PLANET,
                                foreground=fgColor,
                                vDescription=_(
                                    'Production queue may end in {0} turns ({1} directly in planet queue), {2} item(s) on list.'
                                    .format(
                                        res.formatTime(totalEtc + queEtc[0]),
                                        res.formatTime(totalEtc), queueLen))))

        # creation of items with global queue problems
        for queue in xrange(1, 5):
            queName = res.globalQueueName(queue)
            quePlanets = globalQueueStats[queue][0]
            # check empty global production queue with at least one planet [so its relevant]
            if queConstValues[queue] == 0 and quePlanets > 0 and critical:
                items.append(
                    ui.Item(
                        _('Global queue ' + queName),
                        tType=Const.T_QUEUE,
                        foreground=gdata.sevColors[gdata.CRI],
                        vDescription=_(
                            'Global production queue {0} used by {1} planet(s) is empty.'
                            .format(queName, quePlanets))))

            # check end of global production queue
            elif queEtc[queue] < 48:
                fgColor = None
                disp = minor
                if queEtc[queue] < 24:
                    disp = major
                    fgColor = gdata.sevColors[gdata.MAJ]
                if disp:
                    items.append(
                        ui.Item(
                            _('Global queue ' + queName),
                            tType=Const.T_QUEUE,
                            foreground=fgColor,
                            vDescription=_(
                                'Global production queue {0} used by {1} planet(s) runs out in {2} turns.'
                                .format(queName, quePlanets,
                                        res.formatTime(queEtc[queue])))))

        # check research queue
        if self.win.vResearch.checked:
            totalEtc = 0
            # compute length of research queue
            for task in player.rsrchQueue:
                tech = client.getTechInfo(task.techID)
                fulltech = client.getFullTechInfo(task.techID)
                researchSci = Utils.getTechRCost(player, task.techID,
                                                 task.improvement)
                maxImprovement = min(Rules.techMaxImprovement,
                                     fulltech.maxImprovement)
                maxImpTotalSci = 0
                if task.improveToMax and task.improvement < maxImprovement:
                    for impr in range(task.improvement + 1,
                                      maxImprovement + 1):
                        maxImpTotalSci += Utils.getTechRCost(
                            player, task.techID, impr)
                if task.changeSci > 0:
                    value = float(researchSci - task.currSci) / max(
                        task.changeSci, player.effSciPoints)
                    totalEtc += int(value + 1)
                    if player.effSciPoints != 0:
                        totalEtc += float(maxImpTotalSci) / player.effSciPoints
                elif task.changeSci < 0:
                    totalEtc -= float(task.currSci) / min(
                        task.changeSci, player.effSciPoints)
                elif player.effSciPoints > 0:
                    value = float(researchSci) / player.effSciPoints
                    totalEtc += int(value + 1)
                    totalEtc += float(maxImpTotalSci) / player.effSciPoints
                else:
                    totalEtc = 99999
                    break

            # check empty research queue
            if totalEtc == 0 and len(
                    player.rsrchQueue
            ) == 0 and player.effSciPoints > 0 and major:
                items.append(
                    ui.Item(_('Research'),
                            tType=Const.T_TECHNOLOGY,
                            foreground=gdata.sevColors[gdata.MAJ],
                            vDescription=_('Research queue is empty.')))
            # check short reseach queue
            elif totalEtc < 48:
                disp = minor
                fgColor = None
                if totalEtc < 24:
                    disp = major
                    fgColor = gdata.sevColors[gdata.MAJ]

                if disp:
                    items.append(
                        ui.Item(
                            _('Research'),
                            tType=Const.T_TECHNOLOGY,
                            foreground=fgColor,
                            vDescription=
                            _('Research queue ends in %s turns, %d item(s) on list.'
                              ) % (res.formatTime(totalEtc),
                                   len(player.rsrchQueue))))

        self.win.vProblems.items = items
        self.win.vProblems.itemsChanged()
Esempio n. 26
0
	def show(self):
		player = client.getPlayer()
		# title
		self.win.vRQueueTitle.text = _('Research queue [%d pts/turn]') % (
			player.effSciPoints,
		)
		self.win.title = _("Research [TL%d]") % player.techLevel
		# Known techs
		items = []
		#~researchable = {}
		disabled = []
		taskIDs = {}
		for task in player.rsrchQueue:
			taskIDs[task.techID] = None
		for techID in player.techs.keys():
			tech = client.getTechInfo(techID)
			improvement = player.techs[techID]
			item = ui.Item(tech.name,
				techID = techID,
				tLevel = '%d-%d' % (tech.level, improvement),
				tStruct = (' ', '*')[tech.isStructure],
				tShip = (' ', '*')[tech.isShipEquip],
			)
			if improvement < Rules.techMaxImprovement and improvement < tech.maxImprovement:
				neededSci = Utils.getTechRCost(player, techID)
				if player.effSciPoints > 0:
					item.tETC = res.formatTime(float(neededSci) / player.effSciPoints)
				else:
					item.tETC = _("N/A")
				found = 0
				if taskIDs.has_key(techID):
					item.foreground = (0xd0, 0xd0, 0xd0)
				else:
					item.foreground = None
			else:
				item.tETC = res.getNA()
				item.foreground = (0x80, 0x80, 0x80)
				if not self.showCompleted:
					# skip this item
					continue
			items.append(item)
			disabled.extend(tech.researchDisables)
			#~for improvement in range(1, improvement + 1):
			#~	for techID in tech.researchEnables[improvement]:
			#~		researchable[techID] = 1
		self.win.vKTechs.items = items
		self.win.vKTechs.itemsChanged()
		# Research queue
		items = []
		index = 0
		queueTechs = []
		total = 0
		for task in player.rsrchQueue:
			tech = client.getTechInfo(task.techID)
			fulltech = client.getFullTechInfo(task.techID)
			queueTechs.append(task.techID)
			item = ui.Item(tech.name, techID = task.techID, index = index)
			researchSci = Utils.getTechRCost(player, task.techID, task.improvement)
			maxImprovement = min(Rules.techMaxImprovement,fulltech.maxImprovement)
			maxImpTotalSci = 0
			if task.improveToMax and task.improvement < maxImprovement:
				for impr in range(task.improvement+1,maxImprovement+1):
					maxImpTotalSci += Utils.getTechRCost(player, task.techID, impr)
			item.tooltip = _("Research points %d/%d, change %d pts/turn.") % (task.currSci, researchSci, task.changeSci)
			item.statustip = item.tooltip
			item.tImpToMax = ["", "*"][task.improveToMax]
			item.tImproveToMax = task.improveToMax
			if task.currSci > 0:
				item.tProgress = _("%d %%") % int(task.currSci * 100 / researchSci)
			else:
				item.tProgress = _("-")
			if task.changeSci > 0:
				value = float(researchSci - task.currSci) / max(task.changeSci, player.effSciPoints)
				total += int(value + 1)
				if player.effSciPoints > 0:
					total += float(maxImpTotalSci) / player.effSciPoints
					item.tETC = res.formatTime(value)
				else:
					total = 0
					item.tETC = res.getNA()
			elif task.changeSci < 0:
				value = - float(task.currSci) / min(task.changeSci, player.effSciPoints)
				item.tETC = _("[%s]") % res.formatTime(value)
			elif player.effSciPoints > 0:
				value = float(researchSci) / player.effSciPoints
				total += int(value + 1)
				total += float(maxImpTotalSci) / player.effSciPoints
				item.tETC = res.formatTime(value)
			else:
				item.tETC = res.getNA()
			item.tLevel = _("%d-%d") % (tech.level, task.improvement)
			items.append(item)
			index += 1
		self.win.vRQueue.items = items
		self.win.vRQueue.itemsChanged()
		self.win.vRQueueTop.enabled = 0
		self.win.vRQueueUp.enabled = 0
		self.win.vRQueueDown.enabled = 0
		self.win.vRQueueAbort.enabled = 0
		self.win.vRQueueRepat.enabled = 0
		self.win.vRQueueRepat.pressed = 0
		self.win.vRQueueInfo.enabled = 0
		if total == 0:
			self.win.vRTotal.text = _("N/A")
		else:
			self.win.vRTotal.text = res.formatTime(total)
		# Researchable techs
		items = []
		for techID in client.getAllTechIDs():
			if player.techs.has_key(techID)	or techID in queueTechs \
				or techID in disabled:
				continue
			# can check requirements
			tech = client.getTechInfo(techID)
			if not hasattr(tech, "partialData"):
				continue
			item = ui.Item(tech.name, tLevel = tech.level, techID = techID)
			if hasattr(tech, 'isStructure'): item.tStruct = ('', '*')[tech.isStructure]
			else: item.tStruct = ''
			if hasattr(tech, 'isShipEquip'): item.tShip = ('', '*')[tech.isShipEquip]
			else: item.tShip = ''
			if hasattr(tech, 'researchMod'):
				neededSci = Utils.getTechRCost(player, techID)
				if player.effSciPoints > 0:
					item.tETC = res.formatTime(float(neededSci) / player.effSciPoints)
				else:
					item.tETC = _("N/A")
				item.foreground = None
			else:
				item.tSci = res.getNA()
				item.foreground = (0xc0, 0xc0, 0xc0)
				# skip this item
				continue
			if hasattr(tech, "researchDisables") and tech.researchDisables:
				item.foreground = (0xff, 0xff, 0x00)
			if client.getFullTechInfo(techID).finishResearchHandler == TechHandlers.finishResTLAdvance:
					item.foreground = gdata.sevColors[gdata.CRI]
			items.append(item)
		self.win.vRTechs.items = items
		self.win.vRTechs.itemsChanged()
Esempio n. 27
0
 def _populateLastUpgrade(self, fleet):
     return res.formatTime(fleet.lastUpgrade) if hasattr(
         fleet, "lastUpgrade") else "?"
Esempio n. 28
0
    def showTechs(self):
        # techs
        items = []
        select = None
        showMilitary = self.win.vMilitary.checked
        showBio = self.win.vBioProduction.checked
        showEn = self.win.vEnProduction.checked
        showCP = self.win.vCPProduction.checked
        showRP = self.win.vRPProduction.checked
        showMorale = self.win.vMorale.checked

        for techID in client.getPlayer().techs.keys():
            tech = client.getTechInfo(techID)

            if not ((tech.isMilitary and showMilitary) or \
               ((getattr(tech, "prodBio", 0) > 0 or getattr(tech, "prodEnv", 0) > 0) and showBio) or \
               (getattr(tech, "prodEn", 0) > 0 and showEn) or \
               (getattr(tech, "prodProd", 0) > 0 and showCP) or \
               (getattr(tech, "prodSci", 0) > 0 and showRP) or \
               (getattr(tech, "moraleTrgt", 0) > 0 and showMorale)):
                continue

            sourcePlanet = client.get(self.sourceID, noUpdate=1)
            prodProd = getattr(sourcePlanet, "effProdProd", 0)

            if prodProd > 0:
                etc = math.ceil(float(tech.buildProd) / prodProd)
                if self.sourceID != self.planetID:
                    etc *= Rules.buildOnAnotherPlanetMod
                etc = res.formatTime(etc)
            else:
                etc = _("N/A")

            item = ui.Item(
                etc,
                techID=techID,
                tIsShip=0,
                name=tech.name,
                tl=tech.level,
                subtype=tech.subtype,
                icons=((res.getTechImg(techID), ui.ALIGN_N), ),
                font="small-bold",
                align=ui.ALIGN_S,
                tooltipTitle=_("Details"),
                tooltip="%s, %d %s, %s %d" %
                (tech.name, tech.buildProd, _("CP"), _("TL"), tech.level),
                statustip="%s, %d %s, %s %d" %
                (tech.name, tech.buildProd, _("CP"), _("TL"), tech.level),
            )
            if tech.level > self.maxTechLevel:
                self.maxTechLevel = tech.level
            # TODO FIX ME
            if tech.level in self.showLevels and \
                ((self.showStructures and tech.isStructure) or \
                (self.showOther and (tech.isProject))) or tech.level == 99:
                items.append(item)
                if techID == self.techID:
                    select = item

        # sort methods
        if self.sort == 'none':  # sort by name
            items.sort(key=lambda a: a.name)
        elif self.sort == 'tl':  # sort by TL, subsort by name
            items.sort(key=lambda a: a.name)
            items.sort(key=lambda a: a.tl)
        elif self.sort == 'type':  #sort by subtype, subsort by tl
            items.sort(key=lambda a: a.tl)
            items.sort(key=lambda a: a.subtype)
        self.win.vTechs.items = items
        self.win.vTechs.itemsChanged()
        if select:
            self.win.vTechs.selectItem(select)

        # filter
        for i in xrange(1, 10):
            widget = getattr(self.win, 'vLevel%d' % i)
            if i in self.showLevels and i <= self.maxTechLevel:
                widget.visible = 1
                widget.pressed = 1
            elif i not in self.showLevels and i <= self.maxTechLevel:
                widget.visible = 1
                widget.pressed = 0
            else:
                widget.visible = 0

        # quantity
        self.win.vQuantity.text = str(self.quantity)
Esempio n. 29
0
    def showCommands(self):
        self.win.vMoveBtn.pressed =  self.command == Const.FLACTION_MOVE
        self.win.vAttackBtn.pressed =  self.command == Const.FLACTION_DECLAREWAR
        self.win.vDeplShipBtn.pressed =  self.command == Const.FLACTION_DEPLOY
        self.win.vWaitBtn.pressed =  self.command == Const.FLACTION_WAIT
        self.win.vRefuelBtn.pressed =  self.command == Const.FLACTION_REFUEL
        self.win.vRepeatBtn.pressed =  self.command == Const.FLACTION_REPEATFROM
        self.win.vWormholeBtn.pressed =  self.command == Const.FLACTION_ENTERWORMHOLE
        # hide/show widgets
        for widget in self.win.widgets:
            if widget.tags and self.command in widget.tags:
                widget.visible = 1
            elif widget.tags:
                widget.visible = 0
        # target
        if self.targetID == Const.OID_NONE:
            info = _('No target selected')
        elif self.command in (Const.FLACTION_MOVE, Const.FLACTION_REFUEL, Const.FLACTION_ENTERWORMHOLE):
            target = client.get(self.targetID, noUpdate = 1)
            info = getattr(target, 'name', res.getUnknownName())
        elif self.command == Const.FLACTION_DEPLOY:
            target = client.get(self.targetID, noUpdate = 1)
            if target.type == Const.T_PLANET:
                info = getattr(target, 'name', res.getUnknownName())
            else:
                info = _('No planet selected')
        elif self.command == Const.FLACTION_DECLAREWAR:
            if self.targetPlayerID not in (Const.OID_NONE, client.getPlayerID()):
                target = client.get(self.targetPlayerID, noUpdate = 1)
                info = getattr(target, 'name', res.getUnknownName())
            else:
                info = _("No commander specified.")
        else:
            info = _('?')
        self.win.vTarget.text = info
        curTarget = client.get(self.targetID, noUpdate = 1)
        fleet = client.get(self.fleetDlg.fleetID, noUpdate = 1)
        target = Const.OID_NONE
        oldTarget = fleet # we can hack it - only coordinates are necessary

        waitTurns = sum([x[2] for x in fleet.actions[fleet.actionIndex:] if x[0] == Const.FLACTION_WAIT])
        eta = waitTurns # baseline
        targetIDs = [x[1] for x in fleet.actions[fleet.actionIndex:]]
        if self.targetID != Const.OID_NONE:
            targetIDs.append(self.targetID)
        for newTargetID in targetIDs:
            if newTargetID != Const.OID_NONE:
                newTarget = client.get(newTargetID)
                newEta = self._evalEta(fleet, oldTarget, newTarget)
                if newEta is not None:
                    eta += newEta
                else:
                    eta = None
                    break
                oldTarget = newTarget

        if eta is None or not targetIDs:
            self.win.vEta.text = _("N/A")
        else:
            self.win.vEta.text = res.formatTime(eta)

        # ships
        fleet = client.get(self.fleetDlg.fleetID, noUpdate = 1)
        self.deplShips = []
        # collect buildings
        for designID, a, b, c in fleet.ships: #fixed bug in reference of designID...added a, b, c to do it; breaks list lookup otherwise (not sure why) with hash error --RC
            tech = client.getPlayer().shipDesigns[designID]
            if tech.deployStructs:
                self.deplShips.append(designID)
                log.debug('Adding design with structure',designID)
            elif tech.deployHandlers:
                hasHandler = False
                for handler in tech.deployHandlers:
                    if handler != '': #why are blank handlers getting added in ship construction? catch here for now
                        hasHandler = True
                        break
                if hasHandler:
                    self.deplShips.append(designID)
                    log.debug('Adding design with project',designID)
        # correct buildingIndex
        if self.deplShipIndex >= len(self.deplShips):
            self.deplShipIndex = 0
        if self.deplShips:
            self.win.vDeplShipBtn.enabled = 1
            techID = self.deplShips[self.deplShipIndex]
            self.win.vDeplShip.text = client.getPlayer().shipDesigns[techID].name
            self.win.vDeplShip.data = techID
        else:
            self.win.vDeplShipBtn.enabled = 0
            if self.command == Const.FLACTION_DEPLOY:
                self.command == Const.FLACTION_MOVE
                self.showCommands()
Esempio n. 30
0
    def showTechs(self):
        # techs
        items = []
        select = None
        showMilitary = self.win.vMilitary.checked
        showBio = self.win.vBioProduction.checked
        showEn = self.win.vEnProduction.checked
        showCP = self.win.vCPProduction.checked
        showRP = self.win.vRPProduction.checked
        showMorale = self.win.vMorale.checked

        for techID in client.getPlayer().techs.keys():
            tech = client.getTechInfo(techID)

            if not ((tech.isMilitary and showMilitary) or \
               ((getattr(tech, "prodBio", 0) > 0 or getattr(tech, "prodEnv", 0) > 0) and showBio) or \
               (getattr(tech, "prodEn", 0) > 0 and showEn) or \
               (getattr(tech, "prodProd", 0) > 0 and showCP) or \
               (getattr(tech, "prodSci", 0) > 0 and showRP) or \
               (getattr(tech, "moraleTrgt", 0) > 0 and showMorale)):
                continue

            sourcePlanet = client.get(self.sourceID, noUpdate = 1)
            prodProd = getattr(sourcePlanet, "effProdProd", 0)

            if prodProd > 0:
                etc = math.ceil(float(tech.buildProd) / prodProd)
                if self.sourceID != self.planetID:
                    etc *= Rules.buildOnAnotherPlanetMod
                etc = res.formatTime(etc)
            else:
                etc = _("N/A")

            item = ui.Item(etc,
                techID = techID,
                tIsShip = 0,
                name = tech.name,
                tl = tech.level,
                subtype = tech.subtype,
                icons = ((res.getTechImg(techID), ui.ALIGN_N),),
                font = "small-bold",
                align = ui.ALIGN_S,
                tooltip = "%s, %d %s, %s %d" % (tech.name, tech.buildProd,_("CP"),_("TL"), tech.level),
                statustip = "%s, %d %s, %s %d" % (tech.name, tech.buildProd,_("CP"),_("TL"), tech.level),
            )
            if tech.level > self.maxTechLevel:
                self.maxTechLevel = tech.level
            # TODO FIX ME
            if tech.level in self.showLevels and \
                ((self.showStructures and tech.isStructure) or \
                (self.showOther and (tech.isProject))) or tech.level == 99:
                items.append(item)
                if techID == self.techID:
                    select = item

        # sort methods
        if self.sort == 'none': # sort by name
            items.sort(lambda a, b: cmp(a.name, b.name))
        elif self.sort == 'tl': # sort by TL, subsort by name
            items.sort(lambda a, b: cmp(a.name, b.name))
            items.sort(lambda a, b: cmp(a.tl, b.tl))
        elif self.sort == 'type': #sort by subtype, subsort by tl
            items.sort(lambda a, b: cmp(a.tl, b.tl))
            items.sort(lambda a, b: cmp(a.subtype, b.subtype))
        self.win.vTechs.items = items
        self.win.vTechs.itemsChanged()
        if select:
            self.win.vTechs.selectItem(select)

        # filter
        for i in xrange(1, 10):
            widget = getattr(self.win, 'vLevel%d' % i)
            if i in self.showLevels and i <= self.maxTechLevel:
                widget.visible = 1
                widget.pressed = 1
            elif i not in self.showLevels and i <= self.maxTechLevel:
                widget.visible = 1
                widget.pressed = 0
            else:
                widget.visible = 0

        # quantity
        self.win.vQuantity.text = str(self.quantity)
Esempio n. 31
0
    def showTechs(self):
        # techs
        items = []
        select = None

        showMilitary = self.win.vMilitary.checked
        showBio = self.win.vBioProduction.checked
        showEn = self.win.vEnProduction.checked
        showCP = self.win.vCPProduction.checked
        showRP = self.win.vRPProduction.checked
        showMorale = self.win.vMorale.checked

        showSmall = self.win.vSmall.checked
        showMed = self.win.vMedium.checked
        showLarge = self.win.vLarge.checked
        showCivShip = self.win.vCivShip.checked
        showMilShip = self.win.vMilShip.checked

        for techID in client.getPlayer().techs.keys():
            tech = client.getTechInfo(techID)

            # hide pirate techs from ships and miscs view
            if not self.showStructures and tech.level == 99:
                continue

            if tech.isStructure:
                if (tech.isMilitary or getattr(tech, "prodBio", 0) > 0 or getattr(tech, "prodEnv", 0) > 0 or \
                        getattr(tech, "prodEn", 0) > 0 or getattr(tech, "prodProd", 0) > 0 or \
                        getattr(tech, "prodSci", 0) > 0 or getattr(tech, "moraleTrgt", 0) > 0):
                    if not ((tech.isMilitary and showMilitary) or \
                           ((getattr(tech, "prodBio", 0) > 0 or getattr(tech, "prodEnv", 0) > 0) and showBio) or \
                            (getattr(tech, "prodEn", 0) > 0 and showEn) or \
                            (getattr(tech, "prodProd", 0) > 0 and showCP) or \
                            (getattr(tech, "prodSci", 0) > 0 and showRP) or \
                            (getattr(tech, "moraleTrgt", 0) > 0 and showMorale)):
                        continue

            if self.prodProd > 0:
                etc = math.ceil(float(tech.buildProd) / self.prodProd)
                if self.targetID != self.planetID:
                    etc *= Rules.buildOnAnotherPlanetMod
                etc = res.formatTime(etc)
            else:
                etc = _("N/A")
            item = ui.Item(
                tech.name,
                tLevel=tech.level,
                tProd=tech.buildProd,
                techID=techID,
                tIsShip=0,
                tETC=etc,
            )
            if item.tLevel > self.maxTechLevel:
                self.maxTechLevel = item.tLevel

            if item.tLevel in self.showLevels and \
                ((self.showStructures and tech.isStructure) or \
                (self.showOther and (tech.isProject))):
                items.append(item)
                if techID == self.techID:
                    select = item

        # special handling for ships
        player = client.getPlayer()
        if self.showShips:
            for designID in player.shipDesigns.keys():
                tech = player.shipDesigns[designID]

                if not ((tech.combatClass == 0 and showSmall) or
                        (tech.combatClass == 1 and showMed) or
                        (tech.combatClass == 2 and showLarge)):
                    continue

                if not ((tech.isMilitary and showMilShip) or
                        (not tech.isMilitary and showCivShip)):
                    continue

                if tech.upgradeTo != Const.OID_NONE:
                    # skip ships that are set to upgrade
                    continue
                if self.prodProd > 0:
                    etc = res.formatTime(
                        math.ceil(float(tech.buildProd) / self.prodProd))
                else:
                    etc = _("N/A")
                item = ui.Item(
                    tech.name,
                    tLevel=tech.level,
                    tProd=tech.buildProd,
                    techID=designID,
                    tIsShip=1,
                    tETC=etc,
                )
                items.append(item)
                if designID == self.techID:
                    select = item
        # sort it by level and then by name
        items.sort(key=lambda a: (100 - a.tLevel, a.text))
        self.win.vTechs.items = items
        self.win.vTechs.itemsChanged()
        self.win.vTechs.selectItem(select)
        # filter
        for i in xrange(1, 10):
            widget = getattr(self.win, 'vLevel%d' % i)
            if i in self.showLevels and i <= self.maxTechLevel:
                widget.visible = 1
                widget.pressed = 1
            elif i not in self.showLevels and i <= self.maxTechLevel:
                widget.visible = 1
                widget.pressed = 0
            else:
                widget.visible = 0
        self.win.vStructuresToggle.pressed = self.showStructures
        self.win.vShipsToggle.pressed = self.showShips
        self.win.vOtherToggle.pressed = self.showOther
        # targets
        info = []
        system = client.get(self.systemID, noUpdate=1)
        select = None
        if hasattr(system, 'planets'):
            for planetID in system.planets:
                planet = client.get(planetID, noUpdate=1)
                owner = res.getUnknownName()
                #rel = Const.REL_UNDEF
                ownerID = Const.OID_NONE
                if hasattr(planet, 'owner'):
                    ownerID = planet.owner
                    if planet.owner != Const.OID_NONE:
                        owner = client.get(planet.owner, noUpdate=1).name
                        #rel = client.getRelationTo(planet.owner)
                    else:
                        owner = _('[Nobody]')
                if planet.plType in ("A", "G"):
                    color = gdata.sevColors[gdata.DISABLED]
                else:
                    #color = res.getFFColorCode(rel)
                    color = res.getPlayerColor(ownerID)
                plname = getattr(planet, 'name', res.getUnknownName())
                item = ui.Item(
                    plname,
                    text_raw=getattr(planet, 'plEn', plname),
                    planetID=planetID,
                    plOwner=owner,
                    foreground=color,
                )
                info.append(item)
                if planetID == self.targetID:
                    select = item
        self.win.vTargets.items = info
        self.win.vTargets.itemsChanged()
        self.win.vTargets.selectItem(select)
        # quantity
        self.win.vQuantity.text = str(self.quantity)
Esempio n. 32
0
    def show(self):
        # get check box selections
        mine = self.win.vMine.checked
        enemy = self.win.vEnemy.checked
        unfriendly = self.win.vUnfriendy.checked
        neutral = self.win.vNeutral.checked
        friendly = self.win.vFriendly.checked
        allied = self.win.vAllied.checked
        redirects = self.win.vRedirects.checked

        player = client.getPlayer()
        #
        items = []
        for fleetID in client.db.keys():
            fleet = client.get(fleetID, noUpdate=1)
            # skip non-fleets
            if not hasattr(fleet, "type") or (fleet.type != Const.T_FLEET and
                                              fleet.type != Const.T_ASTEROID):
                continue
            # shall be shown?
            fgColor = None

            ownerTipTitle = ""
            ownerName = ""
            ownerNameTip = ""

            # check fleet color and if display fleet
            if hasattr(fleet, 'owner'):
                plRelation = client.getRelationTo(fleet.owner)
                fgColor = res.getPlayerColor(fleet.owner)
                ok = 0
                if mine and fleet.owner == player.oid:
                    ok = 1
                elif enemy and plRelation >= Const.REL_ENEMY_LO and plRelation < Const.REL_ENEMY_HI:
                    ok = 1
                elif unfriendly and plRelation >= Const.REL_UNFRIENDLY_LO and plRelation < Const.REL_UNFRIENDLY_HI:
                    ok = 1
                elif neutral and plRelation >= Const.REL_NEUTRAL_LO and plRelation < Const.REL_NEUTRAL_HI:
                    ok = 1
                elif friendly and plRelation >= Const.REL_FRIENDLY_LO and plRelation < Const.REL_FRIENDLY_HI:
                    ok = 1
                elif allied and plRelation >= Const.REL_ALLY_LO and plRelation < Const.REL_ALLY_HI:
                    ok = 1

                if not ok:
                    continue

                if fleet.owner != player.oid:
                    owner = getattr(client.get(fleet.owner, noUpdate=1),
                                    "name", res.getUnknownName())
                    ownerName = " (%s)" % owner
                    ownerNameTip = owner
                    ownerTipTitle = _("Owner")
            else:
                # asteroids has no owner
                fgColor = res.getFFColorCode(0)  #enemy
                if not enemy:
                    continue

            # check position of fleet
            system = None
            systemName = "-"
            if hasattr(fleet, 'orbiting') and fleet.orbiting:
                system = client.get(fleet.orbiting, noUpdate=1)
                systemName = getattr(system, "name", res.getUnknownName())
            elif hasattr(fleet, 'closeSystem'):
                system = client.get(fleet.closeSystem, noUpdate=1)
                systemName = _("%s (dst)") % getattr(system, "name",
                                                     res.getUnknownName())

            # get fleet current action and target of action
            order = "-"
            targetName = "-"
            if hasattr(fleet, 'actions'):
                if fleet.actionIndex < len(fleet.actions):
                    action, target, data = fleet.actions[fleet.actionIndex]
                    if action == Const.FLACTION_REDIRECT and not redirects:
                        continue
                    order = gdata.fleetActions[action]
                    if target != Const.OID_NONE:
                        targetName = getattr(client.get(target, noUpdate=1),
                                             'name', res.getUnknownName())
                        order = "%s %s" % (order, targetName)
            # eta
            if hasattr(fleet, "eta"): eta = res.formatTime(fleet.eta)
            else: eta = "?"

            # fuel
            if hasattr(fleet, "storEn"):
                if fleet.maxEn > 0: fuel = 100 * fleet.storEn / fleet.maxEn
                else: fuel = 0
            else:
                fuel = "?"

            # operational time
            if hasattr(fleet, 'storEn') and hasattr(fleet, 'operEn'):
                turns = 100000
                if fleet.operEn > 0: turns = fleet.storEn / fleet.operEn
                rawRange = turns * fleet.speed / Rules.turnsPerDay
                range = "%.2f" % rawRange
                opTime = res.formatTime(turns)
            else:
                rawRange = 0
                range = "?"
                opTime = "?"

            # last upgrade
            if hasattr(fleet, "lastUpgrade"):
                lastUpgrade = res.formatTime(fleet.lastUpgrade)
            else:
                lastUpgrade = "?"

            if hasattr(fleet, 'customname') and fleet.customname:
                fleetname = fleet.customname
            else:
                fleetname = getattr(fleet, 'name', res.getUnknownName())

            # create ListBox Item for fleet
            item = ui.Item("%s %s" % (fleetname, ownerName),
                           tooltipTitle=ownerTipTitle,
                           tooltip=ownerNameTip,
                           tLocation=systemName,
                           tOrder=order,
                           tMP=getattr(fleet, "combatPwr", "?"),
                           tETA=eta,
                           tETA_raw=getattr(fleet, "eta", 0),
                           tSignature=getattr(fleet, "signature", "?"),
                           tFuel=fuel,
                           tOpTime=opTime,
                           tRange=range,
                           tRange_raw=rawRange,
                           tLastUpgrade=lastUpgrade,
                           tFleetID=fleetID,
                           foreground=fgColor)
            items.append(item)

        self.win.vFleets.items = items
        self.win.vFleets.itemsChanged()
Esempio n. 33
0
 def show(self):
     player = client.getPlayer()
     #
     items = []
     for planetID in client.db.keys():
         planet = client.get(planetID, noUpdate=1)
         # skip non-planets
         if not hasattr(planet, "type") or planet.type != Const.T_PLANET:
             continue
         # shall be shown?
         ok = 0
         if hasattr(planet, 'owner'):
             if self.showMine and planet.owner == player.oid:
                 ok = 1
             if self.showOtherPlayers and planet.owner != Const.OID_NONE and \
                 planet.owner != player.oid:
                 ok = 1
             if self.showColonizable and planet.owner == Const.OID_NONE and \
                 planet.plType not in ('G', 'A'):
                 ok = 1
             if self.showUncolonizable and planet.plType in ('G', 'A'):
                 ok = 1
         elif hasattr(planet, 'plType'):
             if self.showColonizable and planet.plType not in ('G', 'A'):
                 ok = 1
             if self.showUncolonizable and planet.plType in ('G', 'A'):
                 ok = 1
         if not ok:
             continue
         # fill in data
         #rel = Const.REL_UNDEF
         maxNA = 999999
         maxNone = 99999
         ownerID = Const.OID_NONE
         if hasattr(planet, 'owner'):
             ownerID = planet.owner
             #if planet.owner != Const.OID_NONE:
             #    rel = client.getRelationTo(planet.owner)
             if planet.owner == Const.OID_NONE:
                 #else:
                 owner = _('[Nobody]')
         if hasattr(planet, 'owner') and planet.owner == player.oid:
             if planet.prodQueue and planet.effProdProd > 0:
                 index = 0
                 totalEtc = 0
                 for task in planet.prodQueue:
                     if task.isShip:
                         tech = client.getPlayer().shipDesigns[task.techID]
                     else:
                         tech = client.getFullTechInfo(task.techID)
                     if index == 0:
                         constrInfo = tech.name
                     # etc
                     if task.targetID != planetID:
                         if index == 0:
                             etc = math.ceil(
                                 float(tech.buildProd *
                                       Rules.buildOnAnotherPlanetMod -
                                       task.currProd) / planet.effProdProd)
                             totalEtc += etc
                             totalEtc += math.ceil(
                                 (task.quantity - 1) *
                                 float(tech.buildProd *
                                       Rules.buildOnAnotherPlanetMod) /
                                 planet.effProdProd)
                         else:
                             totalEtc += math.ceil(
                                 float(tech.buildProd *
                                       Rules.buildOnAnotherPlanetMod -
                                       task.currProd) / planet.effProdProd)
                             totalEtc += math.ceil(
                                 (task.quantity - 1) *
                                 float(tech.buildProd *
                                       Rules.buildOnAnotherPlanetMod) /
                                 planet.effProdProd)
                     else:
                         if index == 0:
                             etc = math.ceil(
                                 float(tech.buildProd - task.currProd) /
                                 planet.effProdProd)
                             totalEtc += etc
                             totalEtc += math.ceil(
                                 (task.quantity - 1) *
                                 float(tech.buildProd) / planet.effProdProd)
                         else:
                             totalEtc += math.ceil(
                                 task.quantity *
                                 float(tech.buildProd - task.currProd) /
                                 planet.effProdProd)
                             totalEtc += math.ceil(
                                 (task.quantity - 1) *
                                 float(tech.buildProd) / planet.effProdProd)
                     index += 1
                 etc_raw = etc
                 etc = res.formatTime(etc)
                 totalEtc_raw = totalEtc
                 totalEtc = res.formatTime(totalEtc)
             elif planet.prodQueue:
                 task = planet.prodQueue[0]
                 if task.isShip:
                     tech = client.getPlayer().shipDesigns[task.techID]
                 else:
                     tech = client.getTechInfo(task.techID)
                 constrInfo = tech.name
                 etc = _('N/A')
                 etc_raw = maxNA
                 totalEtc = _("N/A")
                 totalEtc_raw = maxNA
             elif planet.effProdProd > 0:
                 constrInfo = _("-")
                 etc = "-"
                 etc_raw = 0
                 totalEtc = _("-")
                 totalEtc_raw = 0
             else:
                 constrInfo = _("-")
                 etc = "-"
                 etc_raw = maxNone
                 totalEtc = _("-")
                 totalEtc_raw = maxNone
         else:
             constrInfo = '?'
             etc = '?'
             etc_raw = maxNA
             totalEtc = '?'
             totalEtc_raw = maxNA
         # used slots
         if hasattr(planet, 'slots'):
             freeSlots = planet.plSlots - len(planet.slots)
         else:
             freeSlots = '?'
         # morale
         if hasattr(planet, "morale"):
             morale = int(planet.morale)
         else:
             morale = "?"
         #
         plType = gdata.planetTypes[getattr(planet, 'plType', None)]
         # list item
         item = ui.Item(
             getattr(planet, 'name', res.getUnknownName()),
             tPlType=_(plType),
             tPlBio=getattr(planet, 'plBio', '?'),
             tPlMin=getattr(planet, 'plMin', '?'),
             tPlEn=getattr(planet, 'plEn', '?'),
             tChangeBio=getattr(planet, 'changeBio', '?'),
             tChangeEn=getattr(planet, 'changeEn', '?'),
             tETC=etc,
             tETC_raw=etc_raw,
             tTotalETC=totalEtc,
             tTotalETC_raw=totalEtc_raw,
             tConstrInfo=constrInfo,
             tFree=freeSlots,
             tMorale=morale,
             tSpace=getattr(planet, 'plSlots', '?'),
             tDiam=getattr(planet, 'plDiameter', 0) / 1000,
             tProd=getattr(planet, 'effProdProd', '?'),
             tSci=getattr(planet, 'effProdSci', '?'),
             tPlanetID=planetID,
             #foreground = res.getFFColorCode(rel),
             foreground=res.getPlayerColor(ownerID),
         )
         items.append(item)
     self.win.vPlanets.items = items
     self.win.vPlanets.itemsChanged()
     # buttons
     self.win.vMine.pressed = self.showMine
     self.win.vOtherPlayers = self.showOtherPlayers
     self.win.vColonizable = self.showColonizable
     self.win.vUncolonizable = self.showUncolonizable
Esempio n. 34
0
    def show(self):
        # get check box selections
        mine = self.win.vMine.checked
        enemy = self.win.vEnemy.checked
        unfriendly = self.win.vUnfriendy.checked
        neutral = self.win.vNeutral.checked
        friendly = self.win.vFriendly.checked
        allied = self.win.vAllied.checked
        redirects = self.win.vRedirects.checked

        player = client.getPlayer()
        #
        items = []
        for fleetID in client.db.keys():
            fleet = client.get(fleetID, noUpdate = 1)
            # skip non-fleets
            if not hasattr(fleet, "type") or (fleet.type != T_FLEET and fleet.type != T_ASTEROID):
                continue
            # shall be shown?
            fgColor = None

            ownerName = ""
            ownerNameTip = ""

            # check fleet color and if display fleet
            if hasattr(fleet, 'owner'):
                plRelation = client.getRelationTo(fleet.owner)
                fgColor = res.getPlayerColor(fleet.owner)
                ok = 0
                if mine and fleet.owner == player.oid:
                    ok = 1
                elif enemy and plRelation >= REL_ENEMY_LO and plRelation < REL_ENEMY_HI:
                    ok = 1
                elif unfriendly and plRelation >= REL_UNFRIENDLY_LO and plRelation < REL_UNFRIENDLY_HI:
                    ok = 1
                elif neutral and plRelation >= REL_NEUTRAL_LO and plRelation < REL_NEUTRAL_HI:
                    ok = 1
                elif friendly and plRelation >= REL_FRIENDLY_LO and plRelation < REL_FRIENDLY_HI:
                    ok = 1
                elif allied and plRelation >= REL_ALLY_LO and plRelation < REL_ALLY_HI:
                    ok = 1

                if not ok:
                    continue

                if fleet.owner != player.oid:
                    owner = getattr(client.get(fleet.owner, noUpdate = 1), "name", res.getUnknownName())
                    ownerName = " (%s)" % owner
                    ownerNameTip = owner
            else:
                # asteroids has no owner
                fgColor = res.getFFColorCode(0) #enemy
                if not enemy:
                    continue

            # check position of fleet
            system = None
            systemName = "-"
            if hasattr(fleet, 'orbiting') and fleet.orbiting:
                system = client.get(fleet.orbiting, noUpdate = 1)
                systemName = getattr(system, "name", res.getUnknownName())
            elif hasattr(fleet, 'closeSystem'):
                system = client.get(fleet.closeSystem, noUpdate = 1)
                systemName = _("%s (dst)") % getattr(system, "name", res.getUnknownName())

            # get fleet current action and target of action
            order = "-"
            targetName = "-"
            if hasattr(fleet, 'actions'):
                if fleet.actionIndex < len(fleet.actions):
                    action, target, data  = fleet.actions[fleet.actionIndex]
                    if action == FLACTION_REDIRECT and not redirects:
                        continue
                    order = gdata.fleetActions[action]
                    if target != OID_NONE:
                        targetName = getattr(client.get(target, noUpdate = 1), 'name', res.getUnknownName())
                        order = "%s %s" % (order, targetName)
            # eta
            if hasattr(fleet, "eta"): eta = res.formatTime(fleet.eta)
            else: eta = "?"

            # fuel
            if hasattr(fleet, "storEn"):
                if fleet.maxEn > 0: fuel = 100 * fleet.storEn / fleet.maxEn
                else: fuel = 0
            else:
                fuel = "?"

            # operational time
            if hasattr(fleet, 'storEn') and hasattr(fleet, 'operEn'):
                turns = 100000
                if fleet.operEn > 0: turns = fleet.storEn / fleet.operEn
                rawRange = turns * fleet.speed / Rules.turnsPerDay
                range = "%.2f" % rawRange
                opTime = res.formatTime(turns)
            else:
                rawRange = 0
                range = "?"
                opTime = "?"

            # last upgrade
            if hasattr(fleet, "lastUpgrade"):
                lastUpgrade = res.formatTime(fleet.lastUpgrade)
            else:
                lastUpgrade = "?"

            if hasattr(fleet,'customname') and fleet.customname:
                fleetname = fleet.customname
            else:
                fleetname = getattr(fleet, 'name', res.getUnknownName())

            # create ListBox Item for fleet
            item = ui.Item(
                "%s %s" % (fleetname, ownerName),
                tooltip = ownerNameTip,
                tLocation = systemName,
                tOrder = order,
                tMP = getattr(fleet, "combatPwr", "?"),
                tETA = eta,
                tETA_raw = getattr(fleet, "eta", 0),
                tSignature = getattr(fleet, "signature", "?"),
                tFuel = fuel,
                tOpTime = opTime,
                tRange = range,
                tRange_raw = rawRange,
                tLastUpgrade = lastUpgrade,
                tFleetID = fleetID,
                foreground = fgColor)
            items.append(item)

        self.win.vFleets.items = items
        self.win.vFleets.itemsChanged()
Esempio n. 35
0
    def showTechs(self):
        # techs
        items = []
        select = None

        showMilitary = self.win.vMilitary.checked
        showBio = self.win.vBioProduction.checked
        showEn = self.win.vEnProduction.checked
        showCP = self.win.vCPProduction.checked
        showRP = self.win.vRPProduction.checked
        showMorale = self.win.vMorale.checked

        showSmall = self.win.vSmall.checked
        showMed = self.win.vMedium.checked
        showLarge = self.win.vLarge.checked
        showCivShip = self.win.vCivShip.checked
        showMilShip = self.win.vMilShip.checked

        for techID in client.getPlayer().techs.keys():
            tech = client.getTechInfo(techID)

            # hide pirate techs from ships and miscs view
            if not self.showStructures and tech.level == 99:
                continue

            if tech.isStructure:
                if (tech.isMilitary or getattr(tech, "prodBio", 0) > 0 or getattr(tech, "prodEnv", 0) > 0 or \
                        getattr(tech, "prodEn", 0) > 0 or getattr(tech, "prodProd", 0) > 0 or \
                        getattr(tech, "prodSci", 0) > 0 or getattr(tech, "moraleTrgt", 0) > 0):
                    if not ((tech.isMilitary and showMilitary) or \
                           ((getattr(tech, "prodBio", 0) > 0 or getattr(tech, "prodEnv", 0) > 0) and showBio) or \
                            (getattr(tech, "prodEn", 0) > 0 and showEn) or \
                            (getattr(tech, "prodProd", 0) > 0 and showCP) or \
                            (getattr(tech, "prodSci", 0) > 0 and showRP) or \
                            (getattr(tech, "moraleTrgt", 0) > 0 and showMorale)):
                        continue

            if self.prodProd > 0:
                etc = math.ceil(float(tech.buildProd) / self.prodProd)
                if self.targetID != self.planetID:
                    etc *= Rules.buildOnAnotherPlanetMod
                etc = res.formatTime(etc)
            else:
                etc = _("N/A")
            item = ui.Item(tech.name,
                tLevel = tech.level,
                tProd = tech.buildProd,
                techID = techID,
                tIsShip = 0,
                tETC = etc,
            )
            if item.tLevel > self.maxTechLevel:
                self.maxTechLevel = item.tLevel

            if item.tLevel in self.showLevels and \
                ((self.showStructures and tech.isStructure) or \
                (self.showOther and (tech.isProject))):
                items.append(item)
                if techID == self.techID:
                    select = item

        # special handling for ships
        player = client.getPlayer()
        if self.showShips:
            for designID in player.shipDesigns.keys():
                tech = player.shipDesigns[designID]

                if not ((tech.combatClass == 0 and showSmall) or (tech.combatClass == 1 and showMed) or (tech.combatClass == 2 and showLarge)):
                    continue

                if not ((tech.isMilitary and showMilShip) or (not tech.isMilitary and showCivShip)):
                    continue

                if tech.upgradeTo != OID_NONE:
                    # skip ships that are set to upgrade
                    continue
                if self.prodProd > 0:
                    etc = res.formatTime(math.ceil(float(tech.buildProd) / self.prodProd))
                else:
                    etc = _("N/A")
                item = ui.Item(tech.name,
                    tLevel = tech.level,
                    tProd = tech.buildProd,
                    techID = designID,
                    tIsShip = 1,
                    tETC = etc,
                )
                items.append(item)
                if designID == self.techID:
                    select = item
        # sort it by level and then by name
        items.sort(lambda a, b: cmp((100 - a.tLevel, a.text), (100 - b.tLevel, b.text)))
        self.win.vTechs.items = items
        self.win.vTechs.itemsChanged()
        self.win.vTechs.selectItem(select)
        # filter
        for i in xrange(1, 10):
            widget = getattr(self.win, 'vLevel%d' % i)
            if i in self.showLevels and i <= self.maxTechLevel:
                widget.visible = 1
                widget.pressed = 1
            elif i not in self.showLevels and i <= self.maxTechLevel:
                widget.visible = 1
                widget.pressed = 0
            else:
                widget.visible = 0
        self.win.vStructuresToggle.pressed = self.showStructures
        self.win.vShipsToggle.pressed = self.showShips
        self.win.vOtherToggle.pressed = self.showOther
        # targets
        info = []
        system = client.get(self.systemID, noUpdate = 1)
        select = None
        if hasattr(system, 'planets'):
            for planetID in system.planets:
                planet = client.get(planetID, noUpdate = 1)
                owner = res.getUnknownName()
                #rel = REL_UNDEF
                ownerID = OID_NONE
                if hasattr(planet, 'owner'):
                    ownerID = planet.owner
                    if planet.owner != OID_NONE:
                        owner = client.get(planet.owner, noUpdate = 1).name
                        #rel = client.getRelationTo(planet.owner)
                    else:
                        owner = _('[Nobody]')
                if planet.plType in ("A", "G"):
                    color = gdata.sevColors[gdata.DISABLED]
                else:
                    #color = res.getFFColorCode(rel)
                    color = res.getPlayerColor(ownerID)
                plname = getattr(planet, 'name', res.getUnknownName())
                item = ui.Item(
                    plname,
                    text_raw = getattr(planet, 'plEn', plname),
                    planetID = planetID,
                    plOwner = owner,
                    foreground = color,
                )
                info.append(item)
                if planetID == self.targetID:
                    select = item
        self.win.vTargets.items = info
        self.win.vTargets.itemsChanged()
        self.win.vTargets.selectItem(select)
        # quantity
        self.win.vQuantity.text = str(self.quantity)
Esempio n. 36
0
 def onSaveStarmapConfirm(self):
     turn = client.getTurn()
     name = 'starmap_' + res.formatTime(turn,'_')
     full_name = os.path.join(gdata.config.game.screenshot_dir, name)
     savedas = self.mapWidget.save(full_name, chronicle_shot=True)
     self.confirmDlg.display(_('File saved as %s' % savedas), _('OK'), False)