def __init__(self, app): self.app = app self.newAccDlg = NewAccDlg(app) self.confirmDlg = ConfirmDlg(app) self.messageDlg = MessageBoxDlg(app) self.firstlogin = True self.createUI()
def __init__(self, app): self.app = app self.wantsNew = False self.needsPassword = False self.previousSelection = None # this is to fix connection lost/relog usability issue self.createUI() self.passwordDlg = PasswordDlg(app) self.confirmDlg = ConfirmDlg(app) self.confirmDlg.setTitle(_("No free starting position"))
def __init__(self, app): self.app = app self.showStructures = 1 self.showShips = 0 self.showOther = 0 self.techID = 0 self.sort = 'type' self.showLevels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.techInfoDlg = TechInfoDlg(app) self.confirmDlg = ConfirmDlg(app) self.createUI()
def __init__(self, app): self.app = app self.showStructures = 1 self.showShips = 0 self.showOther = 0 self.techID = 0 self.showLevels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 99] self.techInfoDlg = TechInfoDlg(app) self.constructionDlg = ConstructionDlg(app) self.confirmDlg = ConfirmDlg(app) self.createUI() self.win.setTagAttr('struct', 'visible', 1) self.win.setTagAttr('ship', 'visible', 0) # set default sorting for technologies self.win.vTechs.setSort("text")
def __init__(self, app): self.app = app self.createUI() self.selTechDlg = ConstrSelTechDlg(app) self.upgradeDlg = ConstrUpgradeDlg(app) self.confirmDlg = ConfirmDlg(app) self.selectedDesignID = None
def __init__(self, app): self.app = app self.techInfoDlg = TechInfoDlg(app) self.confirmDlg = ConfirmDlg(app) self.showCompleted = 0 self.showObsolete = 0 self.createUI()
def __init__(self, app): self.app = app self.newAccDlg = NewAccDlg(app) self.confirmDlg = ConfirmDlg(app) self.firstlogin = True self.versionChecked = False self.createUI()
def __init__(self, app): self.app = app self.newAccDlg = NewAccountDlg(app) self.playerSelectDlg = PlayerSelectDlg(app) self.confirmDlg = ConfirmDlg(app) self.firstlogin = True self.versionChecked = False self.createUI()
def __init__(self, app): self.app = app self.createUI() self.fleetCommandDlg = FleetCommandDlg(self.app) self.fleetSpecsDlg = FleetSpecsDlg(self.app) self.fleetSplitDlg = FleetSplitDlg(self.app) self.renameFleetDlg = RenameFleetDlg(self.app) self.fleetScoutBloomDlg = FleetScoutBloomDlg(self.app) self.confirmDlg = ConfirmDlg(app)
def __init__(self, app): self.app = app self.createUI() # self.selectedObjID = None self.selectedForum = None self.selectedTopic = None self.selectedType = None self.newMessageDlg = NewMessageDlg(app) self.newMsgs = 0 self.confirmDlg = ConfirmDlg(app) self.uignore = [] self.gignore = [] self.lignore = [] if gdata.config.ignore.universe: self.uignore = gdata.config.ignore.universe.split(',') if gdata.config.ignore.galaxy: self.gignore = gdata.config.ignore.galaxy.split(',') if gdata.config.ignore.local: self.lignore = gdata.config.ignore.local.split(',')
def __init__(self, app): self.app = app self.player = None self.vPQueues = None self.queueNo = 5 self.activeQueue = 0 self.activeIndex = None self.changeQtyDlg = ChangeQtyDlg(app) self.newGlobalTaskDlg = NewGlobalTaskDlg(self.app) self.constructionDlg = ConstructionDlg(app) self.techInfoDlg = TechInfoDlg(app) self.confirmDlg = ConfirmDlg(app) self.createUI()
def __init__(self, app): self.app = app self.starSystemDlg = StarSystemDlg(self.app) self.fleetDlg = FleetDlg(self.app) self.researchDlg = ResearchDlg(self.app) self.confirmDlg = ConfirmDlg(self.app) self.diplomacyDlg = DiplomacyDlg.DiplomacyDlg(self.app) self.constructionDlg = ConstructionDlg(self.app) self.messagesDlg = MessagesDlg(self.app) self.planetsOverviewDlg = PlanetsOverviewDlg(self.app) self.systemOverviewDlg = SystemOverviewDlg(self.app) self.fleetsOverviewDlg = FleetsOverviewDlg(self.app) self.optionsDlg = OptionsDlg(self.app) self.searchDlg = SearchDlg(self.app) self.problemsDlg = ProblemsDlg.ProblemsDlg(self.app) self.empireOverviewDlg = EmpireOverviewDlg.EmpireOverviewDlg(self.app) self.galaxyRestartDlg = GalaxyRestartDlg(self.app) self.planetsAnalysisDlg = PlanetsAnalysisDlg(app) self.fleetsAnalysisDlg = FleetsAnalysisDlg(app) self.mapWidget = None self.createUI() self.centered = 0
class MessagesDlg: def __init__(self, app): self.app = app self.createUI() # self.selectedObjID = None self.selectedForum = None self.selectedTopic = None self.selectedType = None self.newMessageDlg = NewMessageDlg(app) self.newMsgs = 0 self.confirmDlg = ConfirmDlg(app) self.uignore = [] self.gignore = [] self.lignore = [] if gdata.config.ignore.universe: self.uignore = gdata.config.ignore.universe.split(',') if gdata.config.ignore.galaxy: self.gignore = gdata.config.ignore.galaxy.split(',') if gdata.config.ignore.local: self.lignore = gdata.config.ignore.local.split(',') def display(self): self.show() self.win.show() # register for updates if self not in gdata.updateDlgs: gdata.updateDlgs.append(self) def hide(self): self.win.setStatus(_("Ready.")) self.win.hide() # unregister updates if self in gdata.updateDlgs: gdata.updateDlgs.remove(self) def update(self): self.show() def show(self, updateForum=1): self.newMsgs = 0 # player = client.getPlayer() objList = [player.oid] objList.extend(player.galaxies) objList.append(OID_UNIVERSE) # show forums items = [] colors = [gdata.sevColors[gdata.INFO], gdata.sevColors[gdata.MIN]] # Inbox msgs, new = self.getMsgsNumber(player.oid, "INBOX", 'local') self.newMsgs += new spec = gdata.mailboxSpec[T_PLAYER, "INBOX"] item = ui.Item(_(spec[0]), tObjID=player.oid, tForum="INBOX", tType=T_PLAYER, tMsgs=_("%d / %d") % (new, msgs), foreground=colors[new > 0]) items.append(item) # Events msgs, new = self.getMsgsNumber(player.oid, "EVENTS") self.newMsgs += new spec = gdata.mailboxSpec[T_PLAYER, "EVENTS"] eventsItem = ui.Item(_(spec[0]), tObjID=player.oid, tForum="EVENTS", tType=T_PLAYER, tMsgs=_("%d / %d") % (new, msgs), foreground=colors[new > 0]) items.append(eventsItem) # Outbox msgs, new = self.getMsgsNumber(player.oid, "OUTBOX") self.newMsgs += new spec = gdata.mailboxSpec[T_PLAYER, "OUTBOX"] item = ui.Item(_(spec[0]), tObjID=player.oid, tForum="OUTBOX", tType=T_PLAYER, tMsgs=_("%d / %d") % (new, msgs), foreground=colors[new > 0]) items.append(item) # galaxies for galaxyID in player.galaxies: galaxy = client.get(galaxyID) # folder item = ui.Item(_("Galaxy %s") % galaxy.name, tObjID=OID_NONE, tForum="", tMsgs="", foreground=colors[0]) items.append(item) # news msgs, new = self.getMsgsNumber(galaxyID, "NEWS") self.newMsgs += new spec = gdata.mailboxSpec[T_GALAXY, "NEWS"] item = ui.Item(" %s" % _(spec[0]), tObjID=galaxyID, tForum="NEWS", tType=T_GALAXY, tMsgs=_("%d / %d") % (new, msgs), foreground=colors[new > 0]) items.append(item) # public msgs, new = self.getMsgsNumber(galaxyID, "PUBLIC", 'galaxy') self.newMsgs += new spec = gdata.mailboxSpec[T_GALAXY, "PUBLIC"] item = ui.Item(" %s" % _(spec[0]), tObjID=galaxyID, tForum="PUBLIC", tType=T_GALAXY, tMsgs=_("%d / %d") % (new, msgs), foreground=colors[new > 0]) items.append(item) # universe item = ui.Item(_("Outer Space"), tObjID=OID_NONE, tForum="", tMsgs="", foreground=colors[0]) items.append(item) # news msgs, new = self.getMsgsNumber(OID_UNIVERSE, "NEWS") self.newMsgs += new spec = gdata.mailboxSpec[T_UNIVERSE, "NEWS"] item = ui.Item(" %s" % _(spec[0]), tObjID=OID_UNIVERSE, tForum="NEWS", tType=T_UNIVERSE, tMsgs=_("%d / %d") % (new, msgs), foreground=colors[new > 0]) items.append(item) # public msgs, new = self.getMsgsNumber(OID_UNIVERSE, "PUBLIC", 'universe') self.newMsgs += new spec = gdata.mailboxSpec[T_UNIVERSE, "PUBLIC"] item = ui.Item(" %s" % _(spec[0]), tObjID=OID_UNIVERSE, tForum="PUBLIC", tType=T_UNIVERSE, tMsgs=_("%d / %d") % (new, msgs), foreground=colors[new > 0]) items.append(item) # qa msgs, new = self.getMsgsNumber(OID_UNIVERSE, "QA", 'universe') self.newMsgs += new spec = gdata.mailboxSpec[T_UNIVERSE, "QA"] item = ui.Item(" %s" % _(spec[0]), tObjID=OID_UNIVERSE, tForum="QA", tType=T_UNIVERSE, tMsgs=_("%d / %d") % (new, msgs), foreground=colors[new > 0]) items.append(item) # ideas msgs, new = self.getMsgsNumber(OID_UNIVERSE, "IDEAS", 'universe') self.newMsgs += new spec = gdata.mailboxSpec[T_UNIVERSE, "IDEAS"] item = ui.Item(" %s" % _(spec[0]), tObjID=OID_UNIVERSE, tForum="IDEAS", tType=T_UNIVERSE, tMsgs=_("%d / %d") % (new, msgs), foreground=colors[new > 0]) items.append(item) # issues msgs, new = self.getMsgsNumber(OID_UNIVERSE, "ISSUES", 'universe') self.newMsgs += new spec = gdata.mailboxSpec[T_UNIVERSE, "ISSUES"] item = ui.Item(" %s" % _(spec[0]), tObjID=OID_UNIVERSE, tForum="ISSUES", tType=T_UNIVERSE, tMsgs=_("%d / %d") % (new, msgs), foreground=colors[new > 0]) items.append(item) # self.win.vForums.items = items self.win.vForums.itemsChanged() # find item to select found = 0 for item in items: if item.tObjID == self.selectedObjID and item.tForum == self.selectedForum: self.win.vForums.selectItem(item) found = 1 break if not found: self.win.vForums.selectItem(eventsItem) # display forum if updateForum: self.onForumSelected(None, None, None) # update mgs button gdata.mainGameDlg.updateMsgButton() def getMsgsNumber(self, objID, forum, forumtype='none'): try: messages = client.get(objID)._messages except AttributeError: log.debug("Suplying default messages for object", objID, forum) messages = {} new = 0 msgs = 0 for messageID in messages: message = messages[messageID] if forumtype == 'universe': if message["sender"] in self.uignore: continue elif forumtype == 'galaxy': if message["sender"] in self.gignore: continue elif forumtype == 'local': if message["sender"] in self.lignore: continue if message["forum"] == forum: if message["readed"] == 0: new += 1 msgs += 1 return msgs, new def onForumSelected(self, widget, action, data): selItem = self.win.vForums.selection[0] if selItem.tObjID == OID_NONE: # select last valid for item in self.win.vForums.items: if item.tObjID == self.selectedObjID and \ item.tForum == self.selectedForum: self.win.vForums.selectItem(item) break return self.selectedObjID = selItem.tObjID self.selectedForum = selItem.tForum self.selectedType = selItem.tType self.win.vNewTopic.enabled = 1 self.win.vAllReaded.enabled = 1 self.win.vDeleteAll.enabled = 1 player = client.getPlayer() playerid = player.oid objMessages = client.get(selItem.tObjID)._messages ids = objMessages.keys() ids.sort() ids.reverse() topics = [] items = [] for messageID in ids: message = objMessages[messageID] if message["forum"] == selItem.tForum: # ignore by universe, local (private messages), or galaxy if selItem.tObjID == OID_UNIVERSE: if message["sender"] in self.uignore: continue elif selItem.tObjID == playerid: if message["sender"] in self.lignore: continue else: if message["sender"] in self.gignore: continue # regenerate topics for messages with data if message.has_key("data") and message["topic"] == "EVENT": sourceID, msgID, locationID, turn, data = message["data"] message["topic"] = messages.getMsgText(msgID, data).split("\n")[0] topic = message["topic"] item = ui.Item(topic) if topic not in topics: topics.append(topic) #item = ui.Item(topic, tObjID = selItem.tObjID, tForum = selItem.tForum, # tMgsId = -1, font = "normal-bold") #items.append(item) if message.has_key("data"): sourceID, msgID, locationID, turn, data = message["data"] item.tLocationID = locationID item.tSourceID = sourceID obj = client.get(sourceID, noUpdate=1, publicOnly=1) #Custom name in "sender" if hasattr(obj, 'customname') and obj.customname: item.tSender = _('"%s"') % obj.customname else: item.tSender = message["sender"] foreground = gdata.sevColors[messages.getMsgSeverity( msgID)] if message["readed"]: state = _(" ") else: state = _("N") else: item.tSender = message["sender"] if message["readed"]: foreground = gdata.sevColors[gdata.NONE] if message["replied"]: state = _("R") else: state = _(" ") else: foreground = gdata.sevColors[gdata.MIN] state = _("N") date = time.strftime(_("%m-%d %H:%M"), time.localtime(message["time"])) #if date == time.strftime(_("%Y-%m-%d"), time.localtime()): # date = time.strftime(_("%H:%M"), time.localtime(message["time"])) item.tObjID = selItem.tObjID item.tForum = selItem.tForum item.tMsgID = messageID item.foreground = foreground item.tState = state item.tDate = date item.tDate_raw = message["time"] item.tType = selItem.tType items.append(item) self.win.vMessages.items = items self.win.vMessages.itemsChanged() if self.selectedForum != "EVENTS": # reset messages scrollbar position self.win.vMessages.bar.slider.position = 0 self.win.vMessages.itemsChanged() self.win.vMessage.text = [""] self.win.vReply.enabled = 0 self.win.vNewTopic.enabled = gdata.mailboxSpec[ selItem.tType, selItem.tForum][1] != None self.win.vDelete.enabled = len(self.win.vMessages.selection) > 0 def onMessageSelected(self, widget, action, data): selItem = self.win.vMessages.selection[0] selItem.tState = " " message = client.get(selItem.tObjID)._messages[selItem.tMsgID] if "data" not in message: selItem.foreground = gdata.sevColors[gdata.NONE] self.win.vMessages.itemsChanged() message["readed"] = 1 text = [] if message.has_key("data"): text = messages.getFullMessageText(message).split("\n") if message.has_key("text"): text.extend(message["text"].split("\n")) self.win.vMessage.text = text self.win.vMessage.offsetRow = 0 self.win.vMessage.vertScrollbar.slider.position = 0 self.win.vReply.enabled = gdata.mailboxSpec[selItem.tType, selItem.tForum][1] != None self.win.vDelete.enabled = 1 self.win.vToClipboard.enabled = 1 self.show(updateForum=0) def onToClipboard(self, widget, action, data): self.win.vMessage.toClipboard() def onNewTopic(self, widget, action, data): self.newMessageDlg.display(self, self.selectedObjID, self.selectedType, self.selectedForum) def onReply(self, widget, action, data): selItem = self.win.vMessages.selection[0] topic = client.get(selItem.tObjID)._messages[selItem.tMsgID]["topic"] self.newMessageDlg.display(self, self.selectedObjID, self.selectedType, self.selectedForum, selItem.tMsgID) def onRefresh(self, widget, action, data): client.getMessages() self.update() def onDelete(self, widget, action, data): selItem = self.win.vMessages.selection[0] i = 0 # magic 14 is the amount of message topics shown at a time sliderMaxPos = len(self.win.vMessages.items) - 14 sliderPos = int(self.win.vMessages.bar.slider.position) for candidate in self.win.vMessages.items: if candidate == selItem: break i += 1 del client.get(selItem.tObjID)._messages[selItem.tMsgID] self.update() if i >= len(self.win.vMessages.items): i -= 1 if sliderPos >= sliderMaxPos and sliderMaxPos > 0: # deleting when scrolled the list down all the way sliderPos = sliderMaxPos - 1 if i - abs(sliderPos) > 14 - 1 or i < sliderPos: # center vMessages on selected message sliderPos = i - 7 if sliderPos < 0: sliderPos = 0 if sliderPos >= sliderMaxPos: sliderPos = sliderMaxPos - 1 if i < 0: # no more messages to be shown return self.win.vMessages.selectItem(self.win.vMessages.items[i]) self.onMessageSelected(None, None, None) self.win.vMessages.bar.slider.position = sliderPos self.win.vMessages.itemsChanged() def onDeleteAll(self, widget, action, data): self.confirmDlg.display(_("Delete all messages in this mailbox?"), _("Yes"), _("No"), self.onDeleteAllConfirmed) def onDeleteAllConfirmed(self): obj = client.get(self.selectedObjID) # must make list (changing directory) for messageID in obj._messages.keys(): message = obj._messages[messageID] if message["forum"] == self.selectedForum: del obj._messages[messageID] self.update() def onAllReaded(self, widget, action, data): obj = client.get(self.selectedObjID) for messageID in obj._messages: message = obj._messages[messageID] if message["forum"] == self.selectedForum: message["readed"] = 1 self.update() def onPostMenu(self, widget, action, data): selItem = self.win.vMessages.selection[0] if hasattr(selItem, "tLocationID"): self.eventPopup.show() def onShowLoc(self, widget, action, data): item = self.win.vMessages.selection[0] if item.tLocationID != OID_NONE: obj = client.get(item.tLocationID, noUpdate=1) if hasattr(obj, "x"): gdata.mainGameDlg.win.vStarMap.highlightPos = (obj.x, obj.y) gdata.mainGameDlg.win.vStarMap.setPos(obj.x, obj.y) self.hide() return if item.tForum == "EVENTS" and re.match( ('^%s(.*)') % (_('Research completed:')), item.text): gdata.mainGameDlg.researchDlg.display() return self.win.setStatus(_("Cannot show location")) def onShowLocDel(self, widget, action, data): self.onShowLoc(widget, action, data) self.onDelete(widget, action, data) def onShowSource(self, widget, action, data): item = self.win.vMessages.selection[0] if item.tForum == "EVENTS" and re.match( ('^%s(.*)') % (_('Research completed:')), item.text): gdata.mainGameDlg.researchDlg.display() return if item.tSourceID != OID_NONE: gdata.mainGameDlg.onSelectMapObj(None, None, item.tSourceID) #self.hide() return self.win.setStatus(_("Cannot show location")) def onShowSourceDel(self, widget, action, data): self.onShowSource(widget, action, data) self.onDelete(widget, action, data) def onClose(self, widget, action, data): self.hide() def createUI(self): w, h = gdata.scrnSize self.win = ui.Window( self.app, modal=1, escKeyClose=1, titleOnly=w == 800 and h == 600, movable=0, title=_("Messages and events"), rect=ui.Rect((w - 800 - 4 * (w != 800)) / 2, (h - 600 - 4 * (h != 600)) / 2, 800 + 4 * (w != 800), 580 + 4 * (h != 600)), layoutManager=ui.SimpleGridLM(), ) self.win.subscribeAction('*', self) # forums ui.Listbox(self.win, layout=(0, 0, 10, 27), id="vForums", columns=((_("Channel"), "text", 5.5, ui.ALIGN_W), (_("#"), "tMsgs", 4.5, ui.ALIGN_E)), columnLabels=1, action="onForumSelected", sortable=0) # topics ui.Listbox(self.win, layout=(10, 0, 30, 15), id="vMessages", columns=( (_(" "), "tState", 1, ui.ALIGN_NONE), (_("Date"), "tDate", 4, ui.ALIGN_W), (_("Sender"), "tSender", 7, ui.ALIGN_W), (_("Subject"), "text", 0, ui.ALIGN_W), ), columnLabels=1, action="onMessageSelected", rmbAction="onPostMenu") # messages ui.Button(self.win, layout=(10, 15, 5, 1), text=_("To clipboard"), action="onToClipboard", id="vToClipboard", enabled=0) ui.Button(self.win, layout=(15, 15, 5, 1), text=_("New subject"), action="onNewTopic", id="vNewTopic", enabled=0) ui.Button(self.win, layout=(20, 15, 5, 1), text=_("Reply"), action="onReply", id="vReply", enabled=0) ui.Button(self.win, layout=(25, 15, 5, 1), text=_("Read all"), action="onAllReaded", id="vAllReaded", enabled=0) ui.Button(self.win, layout=(30, 15, 5, 1), text=_("Delete"), action="onDelete", id="vDelete", enabled=0) ui.Button(self.win, layout=(35, 15, 5, 1), text=_("Delete all"), action="onDeleteAll", id="vDeleteAll", enabled=0) s = ui.Scrollbar(self.win, layout=(39, 16, 1, 11)) t = ui.Text(self.win, layout=(10, 16, 29, 11), id="vMessage", editable=0) t.attachVScrollbar(s) # status bar ui.TitleButton(self.win, layout=(30, 27, 5, 1), text=_('Refresh'), action='onRefresh') ui.TitleButton(self.win, layout=(35, 27, 5, 1), text=_('Close'), action='onClose') ui.Title(self.win, id='vStatusBar', layout=(0, 27, 30, 1), align=ui.ALIGN_W) #@self.win.statusBar = self.win.vStatusBar # event menu self.eventPopup = ui.Menu(self.app, title=_("Message actions"), items=[ ui.Item(_("Show location"), action="onShowLoc"), ui.Item(_("Show source"), action="onShowSource"), ui.Item( _("Show location and delete msg"), action="onShowLocDel"), ui.Item(_("Show source and delete msg"), action="onShowSourceDel"), ui.Item(_("Delete"), action="onDelete"), ]) self.eventPopup.subscribeAction("*", self)
class NewTaskDlg: def __init__(self, app): self.app = app self.showStructures = 1 self.showShips = 0 self.showOther = 0 self.techID = 0 self.showLevels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 99] self.techInfoDlg = TechInfoDlg(app) self.constructionDlg = ConstructionDlg(app) self.confirmDlg = ConfirmDlg(app) self.createUI() self.win.setTagAttr('struct', 'visible', 1) self.win.setTagAttr('ship', 'visible', 0) # set default sorting for technologies self.win.vTechs.setSort("text") def display(self, caller, prodProd, structToDemolish=Const.OID_NONE): if gdata.config.defaults.reportfinalization != None: val = gdata.config.defaults.reportfinalization self.win.vReportFin.checked = val == 'yes' self.caller = caller self.systemID = caller.systemID self.planetID = caller.planetID self.playerID = client.getPlayerID() self.targetID = caller.planetID self.maxTechLevel = 0 self.quantity = 1 self.govTransferConfirm = False self.govTransferData = None self.prodProd = prodProd self.structToDemolish = structToDemolish self.showTechs() self.showSlots() self.win.show() gdata.updateDlgs.append(self) def hide(self): self.win.setStatus(_("Ready.")) if self in gdata.updateDlgs: gdata.updateDlgs.remove(self) self.win.hide() def update(self): if self.win.visible: self.quantity = int(self.win.vQuantity.text) if self.showShips: self.win.vInfo.enabled = Utils.enableConstruction(client) self.showTechs() self.showSlots() 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 def _filterStructure(self, tech): return ( (self.win.vMilitary.checked and tech.isMilitary) or (self.win.vBioProduction.checked and (getattr(tech, "prodBio", 0) or getattr(tech, "prodEnv", 0) > 0)) or (self.win.vEnProduction.checked and getattr(tech, "prodEn", 0)) or (self.win.vCPProduction.checked and getattr(tech, "prodProd", 0)) or (self.win.vRPProduction.checked and getattr(tech, "prodSci", 0)) or (self.win.vMorale.checked and getattr(tech, "moraleTrgt", 0))) def _filterShipSize(self, tech): return ((self.win.vSmall.checked and tech.combatClass == 0) or (self.win.vMedium.checked and tech.combatClass == 1) or (self.win.vLarge.checked and tech.combatClass == 2)) def _filterShipMilitary(self, tech): return ((self.win.vMilShip.checked and tech.isMilitary) or (self.win.vCivShip.checked and not tech.isMilitary)) def _showStructures(self): 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 items.append(self._processNonShips(tech)) return items def _showProjects(self): items = [] for techID in client.getPlayer().techs.keys(): tech = client.getTechInfo(techID) if tech.level not in self.showLevels or not tech.isProject: continue items.append(self._processNonShips(tech)) return items 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 def _processTarget(self, planet): ownerName = res.getUnknownName() ownerID = Const.OID_NONE if hasattr(planet, 'owner'): ownerID = planet.owner if planet.owner != Const.OID_NONE: ownerName = client.get(planet.owner, noUpdate=1).name if planet.plType in ("A", "G"): color = gdata.sevColors[gdata.DISABLED] else: color = res.getPlayerColor(ownerID) plname = getattr(planet, 'name', res.getUnknownName()) item = ui.Item(plname, text_raw=getattr(planet, 'plEn', plname), planetID=planet.oid, plOwner=ownerName, foreground=color) return item def showTechs(self): # techs items = [] if self.showStructures: items += self._showStructures() if self.showShips: items += self._showShips() if self.showOther: items += self._showProjects() # 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() # preserve selection for item in items: if self.techID == item.techID: self.win.vTechs.selectItem(item) break # tech level filter for i in range(1, 7): 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) for planetID in system.planets: planet = client.get(planetID, noUpdate=1) info.append(self._processTarget(planet)) self.win.vTargets.items = info self.win.vTargets.itemsChanged() for item in info: if self.targetID == item.planetID: self.win.vTargets.selectItem(item) break # quantity self.win.vQuantity.text = str(self.quantity) def showSlots(self): # techs items = [] techs = {} if self.showStructures: player = client.getPlayer() target = client.get(self.targetID, noUpdate=1) if hasattr(target, 'slots') and target.owner == player.oid: if len(target.slots) < target.plSlots: item = ui.Item(_("Free slot"), techID=0) items.append(item) for struct in target.slots: if not struct[Const.STRUCT_IDX_TECHID] in techs: techs[struct[Const.STRUCT_IDX_TECHID]] = 1 else: techs[struct[Const.STRUCT_IDX_TECHID]] += 1 for tech in techs.keys(): techInfo = client.getTechInfo(tech) item = ui.Item("%s (%d)" % (techInfo.name, techs[tech]), techID=tech) items.append(item) self.win.vTSlots.items = items self.win.vTSlots.itemsChanged() self.structToDemolish = Const.OID_NONE def onSelectPlanet(self, widget, action, data): self.quantity = int(self.win.vQuantity.text) self.targetID = data.planetID self.showTechs() self.showSlots() def onSelectSlot(self, widget, action, data): self.structToDemolish = data.techID def onSelectTech(self, widget, action, data): self.techID = data.techID def onToggleLevel(self, widget, action, data): i = widget.data if i in self.showLevels: self.showLevels.remove(i) else: self.showLevels.append(i) self.update() def onCancel(self, widget, action, data): self.hide() def onGovTransferConfirmed(self): # we assume player wants to build just one center - in opposite case, he may change quantity in the task itself self.win.vQuantity.text = str(1) self.govTransferConfirm = True self.onConstruct(*self.govTransferData) def onConstruct(self, widget, action, data): planet = client.get(self.planetID, noUpdate=1) player = client.getPlayer() if not self.techID: self.win.setStatus(_('Select technology to construct.')) return if not self.targetID: self.win.setStatus(_('Select planet to construct on.')) return try: self.quantity = int(self.win.vQuantity.text) except ValueError: self.win.setStatus(_('Specify quantity (1, 2, 3, ...).')) return # government centers have additional query and if confirmed, another round of this function is called if self.techID < 1000: tech = player.shipDesigns[self.techID] else: tech = client.getTechInfo(self.techID) if not getattr(tech, 'govPwr', 0) == 0 and not self.govTransferConfirm: # confirm dialog doesn't send through parameters, so we have to save them self.govTransferData = (widget, action, data) self.confirmDlg.display( _("Do you want to issue relocation of your government?"), _("Yes"), _("No"), self.onGovTransferConfirmed) else: try: self.win.setStatus( _('Executing START CONSTRUCTION command...')) planet.prodQueue, player.stratRes = client.cmdProxy.startConstruction( self.planetID, self.techID, self.quantity, self.targetID, self.techID < 1000, self.win.vReportFin.checked, self.structToDemolish) self.win.setStatus(_('Command has been executed.')) except GameException, e: self.win.setStatus(e.args[0]) return self.hide() self.caller.update()
def __init__(self, app): self.app = app self.confirmDlg = ConfirmDlg(app) self.createUI()
class LoginDlg: def __init__(self, app): self.app = app self.newAccDlg = NewAccDlg(app) self.confirmDlg = ConfirmDlg(app) self.firstlogin = True self.createUI() def display(self, caller = None, message = None): self.caller = caller self.win.vCreate.visible = gdata.config.game.accountcreated == None if gdata.config.game.lastlogin != None: self.win.vLogin.text = gdata.config.game.lastlogin if gdata.config.game.lastpassword: self.win.vPassword.text = gdata.config.game.lastpassword if gdata.config.game.lastpasswordcrypted: self.win.vPassword.text = binascii.a2b_base64(gdata.config.game.lastpasswordcrypted) if not gdata.config.game.lastgameid: gdata.config.game.lastgameid = 'Alpha' self.win.vMessage.text = message #if gdata.config.game.autologin != 'yes': # enable this to disable auto-login after change in options # self.firstlogin = false self.win.show() def hide(self): self.win.hide() def autoLogin(self): if self.firstlogin: self.firstlogin = False self.win.vMessage.text = _('Auto-login in progress ...') login = self.win.vLogin.text password = self.win.vPassword.text gameID = gdata.config.game.lastgameid self.doLogin(gameID,login,password) def onLogin(self, widget, action, data): self.firstlogin = False login = self.win.vLogin.text password = self.win.vPassword.text gameID = gdata.config.game.lastgameid self.win.vMessage.text = _('Login in progress ...') # self.win.hide() self.doLogin(gameID,login,password) def doLogin(self,gameID,login,password): result = client.login(gameID, login, password) self.win.hide() if result == 1: gdata.config.game.lastlogin = login # TODO: remove in 0.6 gdata.config.game.lastpassword = None # if gdata.savePassword: gdata.config.game.lastpasswordcrypted = binascii.b2a_base64(password).strip() else: gdata.config.game.lastpasswordcrypted = None gdata.config.game.lastgameid = gameID gdata.config.game.accountcreated = 1 # write configuration gdata.config.save('var/osci.ini') gdata.config.game.lastpasswordcrypted = binascii.b2a_base64(password).strip() # init ruleset Rules.initRules(os.path.join("res", "rules", client.rulesetName)) # check version if (client.lastClientVersion != version or client.lastClientRevision != revision) and version != (0,0,0,'a'): # wow, a different version! self.confirmDlg.display( _("Your client version does not match server version %d.%d.%d%s [Revision %d]. Do you want to continue?") % ( client.lastClientVersion[0], client.lastClientVersion[1], client.lastClientVersion[2], client.lastClientVersion[3], client.lastClientRevision, ), _('Yes'), _('No'), self.onContinueWithOld, self.app.exit) return # show main dialog if not gdata.mainGameDlg: gdata.mainGameDlg = MainGameDlg(self.app) gdata.mainGameDlg.display() client.updateDatabase() elif result == 2: pass else: # login failed self.win.vPassword.text = '' self.win.vMessage.text = _('Wrong login and/or password') self.win.show() def onCancel(self, widget, action, data): self.win.hide() if self.caller: self.caller.display() else: self.app.exit() def onContinueWithOld(self): # show main dialog self.win.hide() if not gdata.mainGameDlg: gdata.mainGameDlg = MainGameDlg(self.app) gdata.mainGameDlg.display() client.updateDatabase() def onCreateAccount(self, widget, action, data): self.win.hide() self.newAccDlg.display(self) def onOptions(self, widget, action, data): self.win.hide() gdata.config.game.lastpasswordcrypted = binascii.b2a_base64(self.win.vPassword.text).strip() OptionsDlg(gdata.app).display(self) def createUI(self): w, h = gdata.scrnSize self.win = ui.Window(self.app, modal = 1, movable = 0, title = _('Outer Space Login'), rect = ui.Rect((w - 424) / 2, (h - 124) / 2, 424, 124), layoutManager = ui.SimpleGridLM(), tabChange = True, ) self.win.subscribeAction('*', self) ui.Label(self.win, text = _('Login'), align = ui.ALIGN_E, layout = (5, 0, 6, 1) ) ui.Entry(self.win, id = 'vLogin', align = ui.ALIGN_W, layout = (11, 0, 10, 1), orderNo = 1 ) ui.Label(self.win, text = _('Password'), align = ui.ALIGN_E, layout = (5, 1, 6, 1), ) ui.Entry(self.win, id = 'vPassword', align = ui.ALIGN_W, showChar = '*', layout = (11, 1, 10, 1), orderNo = 2 ) ui.Button(self.win, layout = (11, 2, 10, 1), text = _("Options"), action = "onOptions", id = "vOptions") ui.Button(self.win, layout = (11, 3, 10, 1), text = _("New account"), action = "onCreateAccount", id = "vCreate") ui.Title(self.win, layout = (0, 4, 11, 1), id = 'vMessage', align = ui.ALIGN_W) ui.TitleButton(self.win, layout = (11, 4, 5, 1), text = _('Exit'), action = 'onCancel') loginBtn = ui.TitleButton(self.win, layout = (16, 4, 5, 1), text = _('Login'), action = 'onLogin') ui.Label(self.win, layout = (0, 0, 5, 4), icons = ((res.loginLogoImg, ui.ALIGN_W),)) self.win.acceptButton = loginBtn
class GalaxyRestartDlg: def __init__(self, app): self.app = app self.confirmDlg = ConfirmDlg(self.app) self.createUI() def display(self, restartAction = None): # show window self.restartAction = restartAction if not self.win.visible: self.win.show() def update(self): if self.win.visible: self.show() def show(self): pass def hide(self): self.win.setStatus(_("Ready.")) self.win.hide() def onRestart(self, widget, action, data): self.confirmDlg.display(_('Are you really really sure you want to restart this galaxy?'), _('No'), ('Yes'), cancelAction = self.onRealyRestart) def onRealyRestart(self): self.hide() if self.restartAction: self.restartAction(self.win.vMsg.text) def onClose(self, widget, action, data): self.hide() def createUI(self): screenWidth, screenHeight = gdata.scrnSize # size of dialog in layout metrics (for SimpleGridLM) cols = 25 rows = 20 # dialog width and height in pixels width = cols * 20 + 5 height = rows * 20 + 4 #creating dialog window self.win = ui.Window(self.app, modal = 1, escKeyClose = 1, movable = 0, title = _("Galaxy restart"), rect = ui.Rect((screenWidth - width) / 2, (screenHeight - height) / 2, width, height), layoutManager = ui.SimpleGridLM(), ) self.win.subscribeAction('*', self) # first row is window title rows -= 1 ui.Label(self.win, layout = (0, 0, cols, 1), text = _("If you are sure to restart this galaxy, click on Restart button."), align = ui.ALIGN_W) ui.Label(self.win, layout = (0, 1, cols, 1), text = _("You can enter message visible in restart announcement below."), align = ui.ALIGN_W) s = ui.Scrollbar(self.win, layout = (cols - 1, 2, 1, rows - 3)) t = ui.Text(self.win, layout = (0, 2, cols - 1, rows - 3), id = 'vMsg') t.attachVScrollbar(s) # dialog bottom line ui.Title(self.win, layout = (0, rows - 1, cols - 10, 1)) ui.TitleButton(self.win, layout = (cols - 10, rows - 1, 5, 1), text = _("Restart"), action = 'onRestart') ui.TitleButton(self.win, layout = (cols - 5, rows - 1, 5, 1), text = _("Cancel"), action = 'onClose')
class MainGameDlg: def __init__(self, app): self.app = app self.starSystemDlg = StarSystemDlg(self.app) self.fleetDlg = FleetDlg(self.app) self.researchDlg = ResearchDlg(self.app) self.confirmDlg = ConfirmDlg(self.app) self.diplomacyDlg = DiplomacyDlg.DiplomacyDlg(self.app) self.constructionDlg = ConstructionDlg(self.app) self.messagesDlg = MessagesDlg(self.app) self.planetsOverviewDlg = PlanetsOverviewDlg(self.app) self.globalQueuesDlg = GlobalQueuesDlg(self.app) self.systemOverviewDlg = SystemOverviewDlg(self.app) self.fleetsOverviewDlg = FleetsOverviewDlg(self.app) self.optionsDlg = OptionsDlg(self.app) self.searchDlg = SearchDlg(self.app) self.problemsDlg = ProblemsDlg.ProblemsDlg(self.app) self.empireOverviewDlg = EmpireOverviewDlg.EmpireOverviewDlg(self.app) self.galaxyRestartDlg = GalaxyRestartDlg(self.app) self.planetsAnalysisDlg = PlanetsAnalysisDlg(app) self.fleetsAnalysisDlg = FleetsAnalysisDlg(app) self.mapWidget = None self.createUI() self.centered = 0 def display(self): gdata.showBackground = 0 gdata.mainGameDlg = self self.win.show() # register for updates gdata.updateDlgs.append(self) #self.refocus() def refocus(self): #log.debug("refocusing") self.app.setFocus(self.mapWidget) def onCmdInProgress(self, inProgress): if inProgress: self.win.vTurn.background = (0xff, 0xff, 0x00) else: self.win.vTurn.background = None def hide(self): gdata.showBackground = 1 self.win.hide() gdata.mainGameDlg = None # unregister updates if self in gdata.updateDlgs: gdata.updateDlgs.remove(self) def onQuit(self, widget, action, data): self.app.setStatus(_('Logging out and exitting...')) self.app.exit() def onSelectMapObj(self, widget, action, data): self.win.vStarMap.highlightPos = None obj = client.get(data, noUpdate = 1) if obj == None: self.app.setStatus(_('Cannot select object on map')) return if obj.type in (T_PLANET, T_SYSTEM, T_WORMHOLE): self.starSystemDlg.display(data) elif obj.type == T_FLEET: self.fleetDlg.display(data) def onResearch(self, widget, action, data): self.researchDlg.display() def onDiplomacy(self, widget, action, data): self.diplomacyDlg.display() def onMessages(self, widget, action, data): self.messagesDlg.display() def onConstruction(self, widget, action, data): self.constructionDlg.display() def onPlanetsMenu(self, widget, action, data): self.systemPlanetMenu.show((16*20, 0)) def onPlanets(self, widget, action, data): self.planetsOverviewDlg.display() def onSystems(self, widget, action, data): self.systemOverviewDlg.display() def onPlanetAnalysis(self, widget, action, data): self.planetsAnalysisDlg.display() def onGlobalQueues(self, widget, action, data): self.globalQueuesDlg.display() def onFleetsMenu(self, widget, action, data): self.systemFleetMenu.show((20*20, 0)) def onFleets(self, widget, action, data): self.fleetsOverviewDlg.display() def onFleetAnalysis(self, widget, action, data): self.fleetsAnalysisDlg.display() def onOptions(self, widget, action, data): self.optionsDlg.display() def onProblems(self, widget, action, data): self.problemsDlg.display() def onOverview(self, widget, action, data): self.empireOverviewDlg.display() def onSearch(self, widget, action, data): self.searchDlg.display() def onStats(self, widget, action, data): for galaxyID in client.getPlayer().galaxies: url = 'http://%s/%s/galaxy%d.html' % ( gdata.config.game.server, gdata.config.game.lastgameid, galaxyID, ) webbrowser.open(url, new = 1) def onSponsor(self, widget, action, data): webbrowser.open("http://www.k2.cz/", new = 1) def onResign(self, widget, action, data): # swap yes and no self.confirmDlg.display(_('Are you sure to resign current game?'), _('No'), _('Yes'), cancelAction = self.onResignConfirmed) def onSaveStarmap(self, widget, action, data): self.confirmDlg.display(_('Save the current starmap view as an image?'), _('Yes'), _('No'), confirmAction = self.onSaveStarmapConfirm) 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) def onMenu(self, widget, action, data): w, h = gdata.scrnSize self.systemMenu.show((w - self.systemMenu.width * 20 - 4, 0)) def onResignConfirmed(self): client.cmdProxy.resign(client.getPlayerID()) client.db.clear() self.app.exit() def onRestartConfirmed(self, imperatorMsg): self.win.setStatus(_('Galaxy restart in progress...')) oldMsgHandler = client.cmdProxy.msgHandler client.cmdProxy.msgHandler = None client.cmdProxy.keepAliveTime = 60 * 60 # do not try to connect to server (one hour) client.cmdProxy.restartGalaxy(OID_UNIVERSE, client.getPlayer().galaxies[0], imperatorMsg) client.db.clear() client.cmdProxy.msgHandler = oldMsgHandler self.hide() self.app.exit() 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 def galaxyRestart(self, widget, action, data): shownFromMenu = bool(data) if client.db != None: player = client.getPlayer() if player.imperator > 2: self.systemMenu.items[3].enabled = True lastGalaxyRestartShown = gdata.config.game.lastGalaxyRestartShown if lastGalaxyRestartShown != None: localTime = time.time() storedTime = float(lastGalaxyRestartShown) if localTime - storedTime > 60 * 60 * 24 or shownFromMenu == True: gdata.config.game.lastGalaxyRestartShown = str(localTime) self.galaxyRestartDlg.display(restartAction = self.onRestartConfirmed) else: gdata.config.game.lastGalaxyRestartShown = str(time.time()) self.galaxyRestartDlg.display(restartAction = self.onRestartConfirmed) else: self.systemMenu.items[3].enabled = False if shownFromMenu == True: self.win.setStatus(_("Only imperator elected three times and more can restart galaxy.")) def updateMsgButton(self): if self.messagesDlg.newMsgs > 0: self.win.vMessages.foreground = gdata.sevColors[gdata.MAJ] else: self.win.vMessages.foreground = None def processKeyUp(self, evt): return ui.NoEvent def processKeyDown(self, evt): # Alt+M - Messages if evt.unicode == u'\x6D' and pygame.key.get_mods() & KMOD_ALT: self.messagesDlg.display() # Alt+R - Research elif evt.unicode == u'\x72' and pygame.key.get_mods() & KMOD_ALT: self.researchDlg.display() # Alt+D - Diplomacy elif evt.unicode == u'\x64' and pygame.key.get_mods() & KMOD_ALT: self.diplomacyDlg.display() # Alt+C - Constr elif evt.unicode == u'\x63' and pygame.key.get_mods() & KMOD_ALT: self.constructionDlg.display() # Alt+P - Planets elif evt.unicode == u'\x70' and pygame.key.get_mods() & KMOD_ALT: self.onPlanetsMenu(False,False,False) # use onPlanetsMenu rather than direct control # Alt+F - Fleets elif evt.unicode == u'\x66' and pygame.key.get_mods() & KMOD_ALT: self.onFleetsMenu(False,False,False) # use onFleetsMenu rather than direct control # Alt+O - Overview elif evt.unicode == u'\x6F' and pygame.key.get_mods() & KMOD_ALT: self.empireOverviewDlg.display() # Alt+B - Pro'b'lems elif evt.unicode == u'\x62' and pygame.key.get_mods() & KMOD_ALT: self.problemsDlg.display() # Alt+N - Me'n'u elif evt.unicode == u'\x6E' and pygame.key.get_mods() & KMOD_ALT: self.onMenu(False,False,False) # use onMenu rather than direct control def createUI(self): w, h = gdata.scrnSize lw, lh = w / 20, h / 20 self.win = ui.Window(self.app, modal = 1, decorated = 0, alwaysInBackground = 1, movable = 0, rect = ui.Rect(0, 0, w, h), layoutManager = ui.SimpleGridLM(), ) self.win.subscribeAction('*', self) # map self.mapWidget = StarMapWidget(self.win, id = 'vStarMap', action = 'onSelectMapObj', layout = (0, 1, lw, lh - 2) ) self.searchDlg.mapWidget = self.mapWidget self.win.callEventHandler = self.mapWidget self.mapWidget.callEventHandler = self # bottom ui.Label(self.win, id = 'vStatus', align = ui.ALIGN_W, layout = (0, lh - 1, lw - 16, 1), ) ui.ActiveLabel(self.win, id = "vSponsor", align = ui.ALIGN_W, icons = [(pygame.image.load("res/sponsor_logo_small.png"), ui.ALIGN_E)], layout = (lw - 12, lh - 1, 8, 1), action = "onSponsor", statustip = _("Server sponsored by K2 Software"), ) ui.Label(self.win, id = 'vTurn', align = ui.ALIGN_E, text = '????.??', font = 'normal-bold', layout = (lw - 4, lh - 1, 4, 1), ) # top ui.Button(self.win, layout = (0, 0, 4, 1), text = _('Messages'), action = 'onMessages', id = "vMessages") ui.Button(self.win, layout = (4, 0, 4, 1), text = _('Research'), action = 'onResearch') ui.Button(self.win, layout = (8, 0, 4, 1), text = _('Diplomacy'), id = "vDiplomacy", action = 'onDiplomacy', enabled = 0) ui.Button(self.win, layout = (12, 0, 4, 1), text = _('Constr'), id = "vConstruction", action = 'onConstruction', enabled = 0) ui.Button(self.win, layout = (16, 0, 4, 1), text = _('Planets'), id = "vPlanetsMenu", action = 'onPlanetsMenu', enabled = 1) ui.Button(self.win, layout = (20, 0, 4, 1), text = _('Fleets'), id = "vFleetsMenu", action = 'onFleetsMenu', enabled = 1) ui.Button(self.win, layout = (24, 0, 4, 1), text = _('Overview'), id = "vOverview", action = 'onOverview', enabled = 1) ui.Title(self.win, layout = (28, 0, lw - 37, 1)) ui.Button(self.win, layout = (lw - 9, 0, 4, 1), text = _('Problems'), action = 'onProblems') ui.Button(self.win, layout = (lw - 5, 0, 5, 1), text = _('Menu'), action = 'onMenu') self.app.statusBar = self.win.vStatus self.app.setStatus(_('Ready.')) # system menu self.systemMenu = ui.Menu(self.app, title = _("Menu"), width = 5, items = [ ui.Item(_("Find system"), action = "onSearch", hotkey = u'\x66'), # F ui.Item(_("Statistics"), action = "onStats", hotkey = u'\x73'), # S ui.Item(_("Save Starmap"), action = "onSaveStarmap", hotkey = u'\x76'), # V ui.Item(_("Galaxy restart"), action = "galaxyRestart", enabled = False, data = True), # no hotkey; if this position moved, you need to update restartGalaxy's "self.systemMenu.items" lines to reference new index position ui.Item(_("Options"), action = "onOptions", hotkey = u'\x6F'), # O ui.Item(_("--------"), enabled = False), ui.Item(_("Resign"), action = "onResign"), # no hotkey ui.Item(_("--------"), enabled = False), ui.Item(_("Quit"), action = "onQuit", hotkey = u'\x71'), # Q ] ) self.systemMenu.subscribeAction("*", self) self.systemFleetMenu = ui.Menu(self.app, title = _("Fleets"), width = 4, items = [ ui.Item(_("Fleet List"), action = "onFleets", hotkey = u'\x66'), # F ui.Item(_("Analysis"), action = "onFleetAnalysis", hotkey = u'\x61'), # A ] ) self.systemFleetMenu.subscribeAction("*", self) self.systemPlanetMenu = ui.Menu(self.app, title = _("Planets"), width = 5, items = [ ui.Item(_("Planet List"), action = "onPlanets", hotkey = u'\x70'), # P ui.Item(_("System List"), action = "onSystems", hotkey = u'\x73'), # S ui.Item(_("Global queues"), action = "onGlobalQueues"), ui.Item(_("Analysis"), action = "onPlanetAnalysis", hotkey = u'\x61'), #A ] ) self.systemPlanetMenu.subscribeAction("*", self)
class LoginDlg: def __init__(self, app): self.app = app self.newAccDlg = NewAccDlg(app) self.confirmDlg = ConfirmDlg(app) self.messageDlg = MessageBoxDlg(app) self.firstlogin = True self.createUI() def display(self, caller=None, message=None): self.caller = caller # Show the account creation if its not specified or if its 0 or False account_creation_visible = False try: if (gdata.config.game.accountcreated is None or bool(int(gdata.config.game.accountcreated)) is False): account_creation_visible = True except ValueError: account_creation_visible = False self.win.vCreate.visible = account_creation_visible if gdata.config.game.lastlogin != None: self.win.vLogin.text = gdata.config.game.lastlogin if gdata.config.game.lastpassword: self.win.vPassword.text = gdata.config.game.lastpassword if gdata.config.game.lastpasswordcrypted: self.win.vPassword.text = binascii.a2b_base64( gdata.config.game.lastpasswordcrypted) if not gdata.config.game.lastgameid: gdata.config.game.lastgameid = 'Alpha' self.win.vMessage.text = message #if gdata.config.game.autologin != 'yes': # enable this to disable auto-login after change in options # self.firstlogin = false self.win.vTargetServer.text = gdata.config.game.server self.win.show() def hide(self): self.win.hide() def autoLogin(self): if self.firstlogin: self.firstlogin = False self.win.vMessage.text = _('Auto-login in progress ...') login = self.win.vLogin.text password = self.win.vPassword.text gameID = gdata.config.game.lastgameid self.doLogin(gameID, login, password) def onLogin(self, widget, action, data): self.firstlogin = False login = self.win.vLogin.text password = self.win.vPassword.text gameID = gdata.config.game.lastgameid self.win.vMessage.text = _('Login in progress ...') # self.win.hide() self.doLogin(gameID, login, password) def doLogin(self, gameID, login, password): # Check if vTargetServer is empty self.win.vTargetServer.text = self.win.vTargetServer.text.strip( ).rstrip() if (len(self.win.vTargetServer.text) != 0): server_info = self.win.vTargetServer.text.split(":") server_port = 9080 if (len(server_info) == 2): try: server_port = int(server_info[1]) except ValueError: self.messageDlg.display( "The custom server specified doesn't appear to be valid.", "OK") return elif (len(server_info) > 2): self.messageDlg.display( "The custom server specified doesn't appear to be valid.", "OK") return server_host = server_info[0] gdata.config.game.server = "%s:%u" % (server_host, server_port) client.server = gdata.config.game.server result = client.login(gameID, login, password) self.win.hide() if result == 1: gdata.config.game.lastlogin = login # TODO: remove in 0.6 gdata.config.game.lastpassword = None # if gdata.savePassword: gdata.config.game.lastpasswordcrypted = binascii.b2a_base64( password).strip() else: gdata.config.game.lastpasswordcrypted = None gdata.config.game.lastgameid = gameID gdata.config.game.accountcreated = 1 # write configuration gdata.config.save('var/osci.ini') gdata.config.game.lastpasswordcrypted = binascii.b2a_base64( password).strip() # init ruleset Rules.initRules(os.path.join("res", "rules", client.rulesetName)) # check version if (client.lastClientVersion != version or client.lastClientRevision != revision ) and version != (0, 0, 0, 'a'): # wow, a different version! self.confirmDlg.display( _("Your client version does not match server version %d.%d.%d%s [Revision %d]. Do you want to continue?" ) % ( client.lastClientVersion[0], client.lastClientVersion[1], client.lastClientVersion[2], client.lastClientVersion[3], client.lastClientRevision, ), _('Yes'), _('No'), self.onContinueWithOld, self.app.exit) return # show main dialog if not gdata.mainGameDlg: gdata.mainGameDlg = MainGameDlg(self.app) gdata.mainGameDlg.display() client.updateDatabase() elif result == 2: pass else: # login failed self.win.vPassword.text = '' self.win.vMessage.text = _('Wrong login and/or password') self.win.show() def onCancel(self, widget, action, data): self.win.hide() if self.caller: self.caller.display() else: self.app.exit() def onContinueWithOld(self): # show main dialog self.win.hide() if not gdata.mainGameDlg: gdata.mainGameDlg = MainGameDlg(self.app) gdata.mainGameDlg.display() client.updateDatabase() def onCreateAccount(self, widget, action, data): self.win.hide() self.newAccDlg.display(self) def onOptions(self, widget, action, data): self.win.hide() gdata.config.game.lastpasswordcrypted = binascii.b2a_base64( self.win.vPassword.text).strip() OptionsDlg(gdata.app).display(self) def createUI(self): w, h = gdata.scrnSize self.win = ui.Window( self.app, modal=1, movable=0, title=_('Outer Space Login'), rect=ui.Rect((w - 424) / 2, (h - 124) / 2, 424, 145), layoutManager=ui.SimpleGridLM(), tabChange=True, ) self.win.subscribeAction('*', self) ui.Label(self.win, text=_('Login'), align=ui.ALIGN_E, layout=(5, 0, 6, 1)) ui.Entry(self.win, id='vLogin', align=ui.ALIGN_W, layout=(11, 0, 10, 1), orderNo=1) ui.Label( self.win, text=_('Password'), align=ui.ALIGN_E, layout=(5, 1, 6, 1), ) ui.Entry(self.win, id='vPassword', align=ui.ALIGN_W, showChar='*', layout=(11, 1, 10, 1), orderNo=2) # Add a target server entry ui.Label( self.win, text=_('Server'), align=ui.ALIGN_E, layout=(5, 2, 6, 1), ) ui.Entry(self.win, id='vTargetServer', align=ui.ALIGN_W, layout=(11, 2, 10, 1), orderNo=3) ui.Button(self.win, layout=(11, 3, 10, 1), text=_("Options"), action="onOptions", id="vOptions") ui.Button(self.win, layout=(11, 4, 10, 1), text=_("New account"), action="onCreateAccount", id="vCreate") ui.Title(self.win, layout=(0, 5, 11, 1), id='vMessage', align=ui.ALIGN_W) ui.TitleButton(self.win, layout=(11, 5, 5, 1), text=_('Exit'), action='onCancel') loginBtn = ui.TitleButton(self.win, layout=(16, 5, 5, 1), text=_('Login'), action='onLogin') ui.Label(self.win, layout=(0, 0, 5, 4), icons=((res.loginLogoImg, ui.ALIGN_W), )) self.win.acceptButton = loginBtn
def __init__(self, app): self.app = app self.createUI() self.confirmDlg = ConfirmDlg(app) self.confirmDlg.setTitle(_("No free starting position"))
class NewAccountDlg: """ Called for a new player.""" def __init__(self, app): self.app = app self.createUI() self.confirmDlg = ConfirmDlg(app) self.confirmDlg.setTitle(_("No free starting position")) def display(self, caller = None): self.caller = caller if self.show(): self.win.show() def hide(self): self.win.hide() def show(self): positions = client.cmdProxy.getStartingPositions() if not positions: # there are no positions -- pop up a dialog self.confirmDlg.display( _("We are sorry, but there are no starting positions available at this moment. Please, try again later."), _("Refresh"), _("Exit"), self.display, self.app.exit ) return False items = [] for objID, name, posType in positions: item = ui.Item(name, tObjID = objID, tPosType = posType) if posType == STARTPOS_NEWPLAYER: item.tPos = _('Independent player') elif posType == STARTPOS_AIPLAYER: item.tPos = _("Rebel faction") elif posType == STARTPOS_PIRATE: item.tPos = _("Pirate faction [VIP password needed]") else: item.tPos = _('Unknown. You cannot use this.') items.append(item) self.win.vPos.setItems(items) return True def onSelect(self, widget, action, data): if not self.win.vPos.selection: self.win.setStatus(_('Select position.')) return item = self.win.vPos.selection[0] if item.tPosType == STARTPOS_NEWPLAYER: self.win.setStatus(_('Executing CREATE NEW PLAYER command...')) playerID = client.cmdProxy.createNewPlayer(item.tObjID) self.win.setStatus(_('Command has been executed.')) self.hide() if not gdata.mainGameDlg: gdata.mainGameDlg = MainGameDlg(self.app) gdata.mainGameDlg.display() client.updateDatabase(clearDB = 1) elif item.tPosType == STARTPOS_AIPLAYER: self.win.setStatus(_('Executing TAKE OVER REBEL FACTION command...')) playerID = client.cmdProxy.takeOverAIPlayer(item.tObjID) self.win.setStatus(_('Command has been executed.')) self.hide() if not gdata.mainGameDlg: gdata.mainGameDlg = MainGameDlg(self.app) gdata.mainGameDlg.display() client.updateDatabase(clearDB = 1) elif item.tPosType == STARTPOS_PIRATE: password = self.win.vPassword.text if not password: self.win.setStatus(_("Supply VIP password, please.")) return self.win.setStatus(_('Executing TAKE OVER PIRATE FACTION command...')) try: playerID = client.cmdProxy.takeOverPirate(item.tObjID, password) except ige.SecurityException: self.win.setStatus(_("Supply valid VIP password.")) return self.win.setStatus(_('Command has been executed.')) self.hide() if not gdata.mainGameDlg: gdata.mainGameDlg = MainGameDlg(self.app) gdata.mainGameDlg.display() client.updateDatabase(clearDB = 1) def onCancel(self, widget, action, data): self.win.hide() if self.caller: self.caller.display() else: self.app.exit() def createUI(self): w, h = gdata.scrnSize self.win = ui.Window(self.app, modal = 1, movable = 0, title = _('Select starting position'), rect = ui.Rect((w - 424) / 2, (h - 264) / 2, 424, 264), layoutManager = ui.SimpleGridLM(), tabChange = True ) ui.Listbox(self.win, layout = (0, 0, 21, 10), id = 'vPos', columns = ((_('Galaxy'), 'text', 5, ui.ALIGN_W), (_('Position'), 'tPos', 0, ui.ALIGN_W)), columnLabels = 1) self.win.subscribeAction('*', self) ui.Label(self.win, layout = (0, 10, 5, 1), text = _("VIP Password:")) ui.Entry(self.win, layout = (5, 10, 5, 1), id = 'vPassword', align = ui.ALIGN_W, showChar = '*', orderNo = 1 ) ui.Title(self.win, layout = (0, 11, 13, 1), id = 'vStatusBar', align = ui.ALIGN_W) ui.TitleButton(self.win, layout = (13, 11, 4, 1), text = _('Exit'), action = 'onCancel') ui.TitleButton(self.win, layout = (17, 11, 4, 1), text = _('Select'), action = 'onSelect') self.win.statusBar = self.win.vStatusBar
class GalaxyRestartDlg: def __init__(self, app): self.app = app self.confirmDlg = ConfirmDlg(self.app) self.createUI() def display(self, restartAction=None): # show window self.restartAction = restartAction if not self.win.visible: self.win.show() def update(self): if self.win.visible: self.show() def show(self): pass def hide(self): self.win.setStatus(_("Ready.")) self.win.hide() def onRestart(self, widget, action, data): self.confirmDlg.display( _('Are you really really sure you want to restart this galaxy?'), _('No'), ('Yes'), cancelAction=self.onRealyRestart) def onRealyRestart(self): self.hide() if self.restartAction: self.restartAction(self.win.vMsg.text) def onClose(self, widget, action, data): self.hide() def createUI(self): screenWidth, screenHeight = gdata.scrnSize # size of dialog in layout metrics (for SimpleGridLM) cols = 25 rows = 20 # dialog width and height in pixels width = cols * 20 + 5 height = rows * 20 + 4 #creating dialog window self.win = ui.Window( self.app, modal=1, escKeyClose=1, movable=0, title=_("Galaxy restart"), rect=ui.Rect((screenWidth - width) / 2, (screenHeight - height) / 2, width, height), layoutManager=ui.SimpleGridLM(), ) self.win.subscribeAction('*', self) # first row is window title rows -= 1 ui.Label( self.win, layout=(0, 0, cols, 1), text= _("If you are sure to restart this galaxy, click on Restart button." ), align=ui.ALIGN_W) ui.Label( self.win, layout=(0, 1, cols, 1), text=_( "You can enter message visible in restart announcement below." ), align=ui.ALIGN_W) s = ui.Scrollbar(self.win, layout=(cols - 1, 2, 1, rows - 3)) t = ui.Text(self.win, layout=(0, 2, cols - 1, rows - 3), id='vMsg') t.attachVScrollbar(s) # dialog bottom line ui.Title(self.win, layout=(0, rows - 1, cols - 10, 1)) ui.TitleButton(self.win, layout=(cols - 10, rows - 1, 5, 1), text=_("Restart"), action='onRestart') ui.TitleButton(self.win, layout=(cols - 5, rows - 1, 5, 1), text=_("Cancel"), action='onClose')
class NewTaskDlg: def __init__(self, app): self.app = app self.showStructures = 1 self.showShips = 0 self.showOther = 0 self.techID = 0 self.showLevels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 99] self.techInfoDlg = TechInfoDlg(app) self.constructionDlg = ConstructionDlg(app) self.confirmDlg = ConfirmDlg(app) self.createUI() self.win.setTagAttr('struct', 'visible', 1) self.win.setTagAttr('ship', 'visible', 0) # set default sorting for technologies self.win.vTechs.setSort("text") def display(self, caller, prodProd, structToDemolish = OID_NONE): if gdata.config.defaults.reportfinalization != None: val = gdata.config.defaults.reportfinalization self.win.vReportFin.checked = val == 'yes' self.caller = caller self.systemID = caller.systemID self.planetID = caller.planetID self.playerID = client.getPlayerID() self.targetID = caller.planetID self.maxTechLevel = 0 self.quantity = 1 self.govTransferConfirm = False self.govTransferData = None self.prodProd = prodProd self.structToDemolish = structToDemolish self.showTechs() self.showSlots() self.win.show() gdata.updateDlgs.append(self) def hide(self): self.win.setStatus(_("Ready.")) if self in gdata.updateDlgs: gdata.updateDlgs.remove(self) self.win.hide() def update(self): if self.win.visible: self.quantity = int(self.win.vQuantity.text) if self.showShips: self.win.vInfo.enabled = Utils.enableConstruction(client) self.showTechs() self.showSlots() 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) def showSlots(self): # techs items = [] techs = {} if self.showStructures: player = client.getPlayer() target = client.get(self.targetID, noUpdate = 1) if hasattr(target, 'slots') and target.owner == player.oid: if len(target.slots) < target.plSlots: item = ui.Item(_("Free slot"), techID = 0) items.append(item) for struct in target.slots: if not struct[STRUCT_IDX_TECHID] in techs: techs[struct[STRUCT_IDX_TECHID]] = 1 else: techs[struct[STRUCT_IDX_TECHID]] += 1 for tech in techs.keys(): techInfo = client.getTechInfo(tech) item = ui.Item("%s (%d)" % (techInfo.name, techs[tech]), techID = tech) items.append(item) self.win.vTSlots.items = items self.win.vTSlots.itemsChanged() self.structToDemolish = OID_NONE def onSelectPlanet(self, widget, action, data): self.quantity = int(self.win.vQuantity.text) self.targetID = data.planetID self.showTechs() self.showSlots() def onSelectSlot(self, widget, action, data): self.structToDemolish = data.techID def onSelectTech(self, widget, action, data): self.techID = data.techID def onToggleLevel(self, widget, action, data): i = widget.data if i in self.showLevels: self.showLevels.remove(i) else: self.showLevels.append(i) self.update() def onCancel(self, widget, action, data): self.hide() def onGovTransferConfirmed(self): # we assume player wants to build just one center - in opposite case, he may change quantity in the task itself self.win.vQuantity.text = str(1) self.govTransferConfirm = True self.onConstruct(*self.govTransferData) def onConstruct(self, widget, action, data): planet = client.get(self.planetID, noUpdate = 1) player = client.getPlayer() if not self.techID: self.win.setStatus(_('Select technology to construct.')) return if not self.targetID: self.win.setStatus(_('Select planet to construct on.')) return try: self.quantity = int(self.win.vQuantity.text) except ValueError: self.win.setStatus(_('Specify quantity (1, 2, 3, ...).')) return # government centers have additional query and if confirmed, another round of this function is called if self.techID < 1000: tech = player.shipDesigns[self.techID] else: tech = client.getTechInfo(self.techID) if not getattr(tech, 'govPwr', 0) == 0 and not self.govTransferConfirm: # confirm dialog doesn't send through parameters, so we have to save them self.govTransferData = (widget, action, data) self.confirmDlg.display(_("Do you want to issue relocation of your government?"), _("Yes"), _("No"), self.onGovTransferConfirmed) else: try: self.win.setStatus(_('Executing START CONSTRUCTION command...')) planet.prodQueue, player.stratRes = client.cmdProxy.startConstruction(self.planetID, self.techID, self.quantity, self.targetID, self.techID < 1000, self.win.vReportFin.checked, self.structToDemolish) self.win.setStatus(_('Command has been executed.')) except GameException, e: self.win.setStatus(e.args[0]) return self.hide() self.caller.update()
class MessagesDlg: def __init__(self, app): self.app = app self.createUI() # self.selectedObjID = None self.selectedForum = None self.selectedTopic = None self.selectedType = None self.newMessageDlg = NewMessageDlg(app) self.newMsgs = 0 self.confirmDlg = ConfirmDlg(app) self.uignore = [] self.gignore = [] self.lignore = [] if gdata.config.ignore.universe: self.uignore = gdata.config.ignore.universe.split(',') if gdata.config.ignore.galaxy: self.gignore = gdata.config.ignore.galaxy.split(',') if gdata.config.ignore.local: self.lignore = gdata.config.ignore.local.split(',') def display(self): self.show() self.win.show() # register for updates if self not in gdata.updateDlgs: gdata.updateDlgs.append(self) def hide(self): self.win.setStatus(_("Ready.")) self.win.hide() # unregister updates if self in gdata.updateDlgs: gdata.updateDlgs.remove(self) def update(self): self.show() def show(self, updateForum = 1): self.newMsgs = 0 # player = client.getPlayer() objList = [player.oid] objList.extend(player.galaxies) objList.append(OID_UNIVERSE) # show forums items = [] colors = [gdata.sevColors[gdata.INFO], gdata.sevColors[gdata.MIN]] # Inbox msgs, new = self.getMsgsNumber(player.oid, "INBOX",'local') self.newMsgs += new spec = gdata.mailboxSpec[T_PLAYER, "INBOX"] item = ui.Item(_(spec[0]), tObjID = player.oid, tForum = "INBOX", tType = T_PLAYER, tMsgs = _("%d / %d") % (new, msgs), foreground = colors[new > 0]) items.append(item) # Events msgs, new = self.getMsgsNumber(player.oid, "EVENTS") self.newMsgs += new spec = gdata.mailboxSpec[T_PLAYER, "EVENTS"] eventsItem = ui.Item(_(spec[0]), tObjID = player.oid, tForum = "EVENTS", tType = T_PLAYER, tMsgs = _("%d / %d") % (new, msgs), foreground = colors[new > 0]) items.append(eventsItem) # Outbox msgs, new = self.getMsgsNumber(player.oid, "OUTBOX") self.newMsgs += new spec = gdata.mailboxSpec[T_PLAYER, "OUTBOX"] item = ui.Item(_(spec[0]), tObjID = player.oid, tForum = "OUTBOX", tType = T_PLAYER, tMsgs = _("%d / %d") % (new, msgs), foreground = colors[new > 0]) items.append(item) # galaxies for galaxyID in player.galaxies: galaxy = client.get(galaxyID) # folder item = ui.Item(_("Galaxy %s") % galaxy.name, tObjID = OID_NONE, tForum = "", tMsgs = "", foreground = colors[0]) items.append(item) # news msgs, new = self.getMsgsNumber(galaxyID, "NEWS") self.newMsgs += new spec = gdata.mailboxSpec[T_GALAXY, "NEWS"] item = ui.Item(" %s" % _(spec[0]), tObjID = galaxyID, tForum = "NEWS", tType = T_GALAXY, tMsgs = _("%d / %d") % (new, msgs), foreground = colors[new > 0]) items.append(item) # public msgs, new = self.getMsgsNumber(galaxyID, "PUBLIC",'galaxy') self.newMsgs += new spec = gdata.mailboxSpec[T_GALAXY, "PUBLIC"] item = ui.Item(" %s" % _(spec[0]), tObjID = galaxyID, tForum = "PUBLIC", tType = T_GALAXY, tMsgs = _("%d / %d") % (new, msgs), foreground = colors[new > 0]) items.append(item) # universe item = ui.Item(_("Outer Space"), tObjID = OID_NONE, tForum = "", tMsgs = "", foreground = colors[0]) items.append(item) # news msgs, new = self.getMsgsNumber(OID_UNIVERSE, "NEWS") self.newMsgs += new spec = gdata.mailboxSpec[T_UNIVERSE, "NEWS"] item = ui.Item(" %s" % _(spec[0]), tObjID = OID_UNIVERSE, tForum = "NEWS", tType = T_UNIVERSE, tMsgs = _("%d / %d") % (new, msgs), foreground = colors[new > 0]) items.append(item) # public msgs, new = self.getMsgsNumber(OID_UNIVERSE, "PUBLIC",'universe') self.newMsgs += new spec = gdata.mailboxSpec[T_UNIVERSE, "PUBLIC"] item = ui.Item(" %s" % _(spec[0]), tObjID = OID_UNIVERSE, tForum = "PUBLIC", tType = T_UNIVERSE, tMsgs = _("%d / %d") % (new, msgs), foreground = colors[new > 0]) items.append(item) # qa msgs, new = self.getMsgsNumber(OID_UNIVERSE, "QA",'universe') self.newMsgs += new spec = gdata.mailboxSpec[T_UNIVERSE, "QA"] item = ui.Item(" %s" % _(spec[0]), tObjID = OID_UNIVERSE, tForum = "QA", tType = T_UNIVERSE, tMsgs = _("%d / %d") % (new, msgs), foreground = colors[new > 0]) items.append(item) # ideas msgs, new = self.getMsgsNumber(OID_UNIVERSE, "IDEAS",'universe') self.newMsgs += new spec = gdata.mailboxSpec[T_UNIVERSE, "IDEAS"] item = ui.Item(" %s" % _(spec[0]), tObjID = OID_UNIVERSE, tForum = "IDEAS", tType = T_UNIVERSE, tMsgs = _("%d / %d") % (new, msgs), foreground = colors[new > 0]) items.append(item) # issues msgs, new = self.getMsgsNumber(OID_UNIVERSE, "ISSUES",'universe') self.newMsgs += new spec = gdata.mailboxSpec[T_UNIVERSE, "ISSUES"] item = ui.Item(" %s" % _(spec[0]), tObjID = OID_UNIVERSE, tForum = "ISSUES", tType = T_UNIVERSE, tMsgs = _("%d / %d") % (new, msgs), foreground = colors[new > 0]) items.append(item) # self.win.vForums.items = items self.win.vForums.itemsChanged() # find item to select found = 0 for item in items: if item.tObjID == self.selectedObjID and item.tForum == self.selectedForum: self.win.vForums.selectItem(item) found = 1 break if not found: self.win.vForums.selectItem(eventsItem) # display forum if updateForum: self.onForumSelected(None, None, None) # update mgs button gdata.mainGameDlg.updateMsgButton() def getMsgsNumber(self, objID, forum, forumtype='none'): try: messages = client.get(objID)._messages except AttributeError: log.debug("Suplying default messages for object", objID, forum) messages = {} new = 0 msgs = 0 for messageID in messages: message = messages[messageID] if forumtype == 'universe': if message["sender"] in self.uignore: continue; elif forumtype == 'galaxy': if message["sender"] in self.gignore: continue; elif forumtype == 'local': if message["sender"] in self.lignore: continue; if message["forum"] == forum: if message["readed"] == 0: new += 1 msgs += 1 return msgs, new def onForumSelected(self, widget, action, data): selItem = self.win.vForums.selection[0] if selItem.tObjID == OID_NONE: # select last valid for item in self.win.vForums.items: if item.tObjID == self.selectedObjID and \ item.tForum == self.selectedForum: self.win.vForums.selectItem(item) break return self.selectedObjID = selItem.tObjID self.selectedForum = selItem.tForum self.selectedType = selItem.tType self.win.vNewTopic.enabled = 1 self.win.vAllReaded.enabled = 1 self.win.vDeleteAll.enabled = 1 player = client.getPlayer() playerid = player.oid objMessages = client.get(selItem.tObjID)._messages ids = objMessages.keys() ids.sort() ids.reverse() topics = [] items = [] for messageID in ids: message = objMessages[messageID] if message["forum"] == selItem.tForum: # ignore by universe, local (private messages), or galaxy if selItem.tObjID == OID_UNIVERSE: if message["sender"] in self.uignore: continue; elif selItem.tObjID == playerid: if message["sender"] in self.lignore: continue; else: if message["sender"] in self.gignore: continue; # regenerate topics for messages with data if message.has_key("data") and message["topic"] == "EVENT": sourceID, msgID, locationID, turn, data = message["data"] message["topic"] = messages.getMsgText(msgID, data).split("\n")[0] topic = message["topic"] item = ui.Item(topic) if topic not in topics: topics.append(topic) #item = ui.Item(topic, tObjID = selItem.tObjID, tForum = selItem.tForum, # tMgsId = -1, font = "normal-bold") #items.append(item) if message.has_key("data"): sourceID, msgID, locationID, turn, data = message["data"] item.tLocationID = locationID item.tSourceID = sourceID obj = client.get(sourceID, noUpdate = 1, publicOnly = 1) #Custom name in "sender" if hasattr(obj,'customname') and obj.customname: item.tSender = _('"%s"') % obj.customname else: item.tSender = message["sender"] foreground = gdata.sevColors[messages.getMsgSeverity(msgID)] if message["readed"]: state = _(" ") else: state = _("N") else: item.tSender = message["sender"] if message["readed"]: foreground = gdata.sevColors[gdata.NONE] if message["replied"]: state = _("R") else: state = _(" ") else: foreground = gdata.sevColors[gdata.MIN] state = _("N") date = time.strftime(_("%m-%d %H:%M"), time.localtime(message["time"])) #if date == time.strftime(_("%Y-%m-%d"), time.localtime()): # date = time.strftime(_("%H:%M"), time.localtime(message["time"])) item.tObjID = selItem.tObjID item.tForum = selItem.tForum item.tMsgID = messageID item.foreground = foreground item.tState = state item.tDate = date item.tDate_raw = message["time"] item.tType = selItem.tType items.append(item) self.win.vMessages.items = items self.win.vMessages.itemsChanged() if self.selectedForum != "EVENTS": # reset messages scrollbar position self.win.vMessages.bar.slider.position = 0 self.win.vMessages.itemsChanged() self.win.vMessage.text = [""] self.win.vReply.enabled = 0 self.win.vNewTopic.enabled = gdata.mailboxSpec[selItem.tType, selItem.tForum][1] != None self.win.vDelete.enabled = len(self.win.vMessages.selection) > 0 def onMessageSelected(self, widget, action, data): selItem = self.win.vMessages.selection[0] selItem.tState = " " message = client.get(selItem.tObjID)._messages[selItem.tMsgID] if "data" not in message: selItem.foreground = gdata.sevColors[gdata.NONE] self.win.vMessages.itemsChanged() message["readed"] = 1 text = [] if message.has_key("data"): text = messages.getFullMessageText(message).split("\n") if message.has_key("text"): text.extend(message["text"].split("\n")) self.win.vMessage.text = text self.win.vMessage.offsetRow = 0 self.win.vMessage.vertScrollbar.slider.position = 0 self.win.vReply.enabled = gdata.mailboxSpec[selItem.tType, selItem.tForum][1] != None self.win.vDelete.enabled = 1 self.win.vToClipboard.enabled = 1 self.show(updateForum = 0) def onToClipboard(self, widget, action, data): self.win.vMessage.toClipboard() def onNewTopic(self, widget, action, data): self.newMessageDlg.display(self, self.selectedObjID, self.selectedType, self.selectedForum) def onReply(self, widget, action, data): selItem = self.win.vMessages.selection[0] topic = client.get(selItem.tObjID)._messages[selItem.tMsgID]["topic"] self.newMessageDlg.display(self, self.selectedObjID, self.selectedType, self.selectedForum, selItem.tMsgID) def onRefresh(self, widget, action, data): client.getMessages() self.update() def onDelete(self, widget, action, data): selItem = self.win.vMessages.selection[0] i = 0 # magic 14 is the amount of message topics shown at a time sliderMaxPos = len(self.win.vMessages.items) - 14 sliderPos = int(self.win.vMessages.bar.slider.position) for candidate in self.win.vMessages.items: if candidate == selItem: break i += 1 del client.get(selItem.tObjID)._messages[selItem.tMsgID] self.update() if i >= len(self.win.vMessages.items): i -= 1 if sliderPos >= sliderMaxPos and sliderMaxPos > 0: # deleting when scrolled the list down all the way sliderPos = sliderMaxPos - 1 if i - abs(sliderPos) > 14 - 1 or i < sliderPos: # center vMessages on selected message sliderPos = i - 7 if sliderPos < 0: sliderPos = 0 if sliderPos >= sliderMaxPos: sliderPos = sliderMaxPos - 1 if i < 0: # no more messages to be shown return self.win.vMessages.selectItem(self.win.vMessages.items[i]) self.onMessageSelected(None, None, None) self.win.vMessages.bar.slider.position = sliderPos self.win.vMessages.itemsChanged() def onDeleteAll(self, widget, action, data): self.confirmDlg.display(_("Delete all messages in this mailbox?"), _("Yes"), _("No"), self.onDeleteAllConfirmed) def onDeleteAllConfirmed(self): obj = client.get(self.selectedObjID) # must make list (changing directory) for messageID in obj._messages.keys(): message = obj._messages[messageID] if message["forum"] == self.selectedForum: del obj._messages[messageID] self.update() def onAllReaded(self, widget, action, data): obj = client.get(self.selectedObjID) for messageID in obj._messages: message = obj._messages[messageID] if message["forum"] == self.selectedForum: message["readed"] = 1 self.update() def onPostMenu(self, widget, action, data): selItem = self.win.vMessages.selection[0] if hasattr(selItem, "tLocationID"): self.eventPopup.show() def onShowLoc(self, widget, action, data): item = self.win.vMessages.selection[0] if item.tLocationID != OID_NONE: obj = client.get(item.tLocationID, noUpdate = 1) if hasattr(obj, "x"): gdata.mainGameDlg.win.vStarMap.highlightPos = (obj.x, obj.y) gdata.mainGameDlg.win.vStarMap.setPos(obj.x, obj.y) self.hide() return if item.tForum == "EVENTS" and re.match(('^%s(.*)')%(_('Research completed:')),item.text): gdata.mainGameDlg.researchDlg.display() return self.win.setStatus(_("Cannot show location")) def onShowLocDel(self, widget, action, data): self.onShowLoc(widget, action, data) self.onDelete(widget, action, data) def onShowSource(self, widget, action, data): item = self.win.vMessages.selection[0] if item.tForum == "EVENTS" and re.match(('^%s(.*)')%(_('Research completed:')),item.text): gdata.mainGameDlg.researchDlg.display() return if item.tSourceID != OID_NONE: gdata.mainGameDlg.onSelectMapObj(None, None, item.tSourceID) #self.hide() return self.win.setStatus(_("Cannot show location")) def onShowSourceDel(self, widget, action, data): self.onShowSource(widget, action, data) self.onDelete(widget, action, data) def onClose(self, widget, action, data): self.hide() def createUI(self): w, h = gdata.scrnSize self.win = ui.Window(self.app, modal = 1, escKeyClose = 1, titleOnly = w == 800 and h == 600, movable = 0, title = _("Messages and events"), rect = ui.Rect((w - 800 - 4 * (w != 800)) / 2, (h - 600 - 4 * (h != 600)) / 2, 800 + 4 * (w != 800), 580 + 4 * (h != 600)), layoutManager = ui.SimpleGridLM(), ) self.win.subscribeAction('*', self) # forums ui.Listbox(self.win, layout = (0, 0, 10, 27), id = "vForums", columns = ((_("Channel"), "text", 5.5, ui.ALIGN_W), (_("#"), "tMsgs", 4.5, ui.ALIGN_E)), columnLabels = 1, action = "onForumSelected", sortable = 0) # topics ui.Listbox(self.win, layout = (10, 0, 30, 15), id = "vMessages", columns = ( (_(" "), "tState", 1, ui.ALIGN_NONE), (_("Date"), "tDate", 4, ui.ALIGN_W), (_("Sender"), "tSender", 7, ui.ALIGN_W), (_("Subject"), "text", 0, ui.ALIGN_W), ), columnLabels = 1, action = "onMessageSelected", rmbAction = "onPostMenu") # messages ui.Button(self.win, layout = (10, 15, 5, 1), text = _("To clipboard"), action = "onToClipboard", id = "vToClipboard", enabled = 0) ui.Button(self.win, layout = (15, 15, 5, 1), text = _("New subject"), action = "onNewTopic", id = "vNewTopic", enabled = 0) ui.Button(self.win, layout = (20, 15, 5, 1), text = _("Reply"), action = "onReply", id = "vReply", enabled = 0) ui.Button(self.win, layout = (25, 15, 5, 1), text = _("Read all"), action = "onAllReaded", id = "vAllReaded", enabled = 0) ui.Button(self.win, layout = (30, 15, 5, 1), text = _("Delete"), action = "onDelete", id = "vDelete", enabled = 0) ui.Button(self.win, layout = (35, 15, 5, 1), text = _("Delete all"), action = "onDeleteAll", id = "vDeleteAll", enabled = 0) s = ui.Scrollbar(self.win, layout = (39, 16, 1, 11)) t = ui.Text(self.win, layout = (10, 16, 29, 11), id = "vMessage", editable = 0) t.attachVScrollbar(s) # status bar ui.TitleButton(self.win, layout = (30, 27, 5, 1), text = _('Refresh'), action = 'onRefresh') ui.TitleButton(self.win, layout = (35, 27, 5, 1), text = _('Close'), action = 'onClose') ui.Title(self.win, id = 'vStatusBar', layout = (0, 27, 30, 1), align = ui.ALIGN_W) #@self.win.statusBar = self.win.vStatusBar # event menu self.eventPopup = ui.Menu(self.app, title = _("Message actions"), items = [ ui.Item(_("Show location"), action = "onShowLoc"), ui.Item(_("Show source"), action = "onShowSource"), ui.Item(_("Show location and delete msg"), action = "onShowLocDel"), ui.Item(_("Show source and delete msg"), action = "onShowSourceDel"), ui.Item(_("Delete"), action = "onDelete"), ] ) self.eventPopup.subscribeAction("*", self)
class StructTaskDlg: def __init__(self, app): self.app = app self.showStructures = 1 self.showShips = 0 self.showOther = 0 self.techID = 0 self.sort = 'type' self.showLevels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.techInfoDlg = TechInfoDlg(app) self.confirmDlg = ConfirmDlg(app) self.createUI() def display(self, caller, planetID, extraSlot=False, structToDemolish=Const.OID_NONE): if gdata.config.defaults.reportfinalization != None: val = gdata.config.defaults.reportfinalization self.win.vReportFin.checked = val == 'yes' self.caller = caller self.systemID = caller.systemID self.planetID = caller.planetID self.playerID = client.getPlayerID() self.sourceID = caller.planetID self.extraSlot = extraSlot self.maxTechLevel = 0 self.quantity = 1 self.govTransferConfirm = False self.govTransferData = None self.structToDemolish = structToDemolish self.win.vPlanets.selectItem(None) self.showPlanets() self.showTechs() self.win.show() gdata.updateDlgs.append(self) def hide(self): self.win.setStatus(_("Ready.")) if self in gdata.updateDlgs: gdata.updateDlgs.remove(self) self.win.hide() def update(self): if self.win.visible: self.quantity = int(self.win.vQuantity.text) self.showPlanets() self.showTechs() def showPlanets(self): info = [] system = client.get(self.systemID, noUpdate=1) select = None playerID = client.getPlayerID() firstEnabled = None if hasattr(system, 'planets'): for planetID in system.planets: # get planet planet = client.get(planetID, noUpdate=1) # only player owned planets can be source planets enabled = getattr(planet, "owner") == playerID buttonText = "%s / %s" % (getattr(planet, 'name', res.getUnknownName()), getattr(planet, "effProdProd", "?")) item = ui.Item(buttonText, planetID=planetID, enabled=enabled, align=ui.ALIGN_NONE) info.append(item) # remember first players planet if enabled and firstEnabled == None: firstEnabled = item # select actual planet as source only if player owns it if planetID == self.sourceID and enabled: select = item # set as selected source first players planet if select == None: select = firstEnabled self.sourceID = firstEnabled.planetID self.win.vPlanets.items = info self.win.vPlanets.itemsChanged() self.win.vPlanets.selectItem(select) def _filterStructure(self, tech): return ( (self.win.vMilitary.checked and tech.isMilitary) or (self.win.vBioProduction.checked and (getattr(tech, "prodBio", 0) or getattr(tech, "prodEnv", 0) > 0)) or (self.win.vEnProduction.checked and getattr(tech, "prodEn", 0)) or (self.win.vCPProduction.checked and getattr(tech, "prodProd", 0)) or (self.win.vRPProduction.checked and getattr(tech, "prodSci", 0)) or (self.win.vMorale.checked and getattr(tech, "moraleTrgt", 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 def showTechs(self): sourcePlanet = client.get(self.sourceID, noUpdate=1) prodProd = getattr(sourcePlanet, "effProdProd", 0) items = self._showStructures(prodProd) # 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() # 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) def onSelectPlanet(self, widget, action, data): if data == None: for item in self.win.vPlanets.items: if self.sourceID == item.planetID: self.win.vPlanets.selectItem(item) break return self.quantity = int(self.win.vQuantity.text) self.sourceID = data.planetID self.showTechs() def onToggleLevel(self, widget, action, data): i = widget.data if i in self.showLevels: self.showLevels.remove(i) else: self.showLevels.append(i) self.update() def onCancel(self, widget, action, data): self.hide() def onGovTransferConfirmed(self): # we assume player wants to build just one center - in opposite case, he may change quantity in the task itself self.win.vQuantity.text = str(1) self.govTransferConfirm = True self.onConstruct(*self.govTransferData) def onConstruct(self, widget, action, data): if not data: self.win.setStatus(_('Select technology to construct.')) return if not self.sourceID: self.sourceID = self.planetID try: self.quantity = int(self.win.vQuantity.text) except ValueError: self.win.setStatus(_('Specify quantity (1, 2, 3, ...).')) return # government centers have additional query and if confirmed, another round of this function is called tech = client.getTechInfo(data.techID) if tech.govPwr and not self.govTransferConfirm: # confirm dialog doesn't send through parameters, so we have to save them self.govTransferData = (widget, action, data) self.confirmDlg.display( _("Do you want to issue relocation of your government?"), _("Yes"), _("No"), self.onGovTransferConfirmed) else: try: self.win.setStatus( _('Executing START CONSTRUCTION command...')) planet = client.get(self.sourceID, noUpdate=1) player = client.getPlayer() if self.extraSlot: # check required special resources, if not available, do not continue # (without check, server start slot expansion but not the tech) specialResources = player.stratRes for sr in tech.buildSRes: if specialResources.get(sr, 0) < self.quantity: self.win.setStatus( _('You do not own required strategic resource(s)' )) return else: specialResources[sr] = specialResources.get( sr, 0) - self.quantity for i in range(1, self.quantity + 1): # as we need two slots instead of one, check whether is task queue short # enough (ie 8 tasks max) if len(planet.prodQueue) > 8: self.win.setStatus(_('Queue is full')) return client.cmdProxy.startConstruction( self.sourceID, Rules.Tech.ADDSLOT3, 1, self.planetID, False, self.win.vReportFin.checked, Const.OID_NONE) planet.prodQueue, player.stratRes = client.cmdProxy.startConstruction( self.sourceID, data.techID, 1, self.planetID, data.techID < 1000, self.win.vReportFin.checked, self.structToDemolish) else: planet.prodQueue, player.stratRes = client.cmdProxy.startConstruction( self.sourceID, data.techID, self.quantity, self.planetID, data.techID < 1000, self.win.vReportFin.checked, self.structToDemolish) self.win.setStatus(_('Command has been executed.')) except GameException, e: self.win.setStatus(e.args[0]) return self.win.vTechs.selectItem(None) self.hide() self.caller.update()
class PlayerSelectDlg: """ Called for selection of active or picking a new player.""" def __init__(self, app): self.app = app self.wantsNew = False self.needsPassword = False self.previousSelection = None # this is to fix connection lost/relog usability issue self.createUI() self.passwordDlg = PasswordDlg(app) self.confirmDlg = ConfirmDlg(app) self.confirmDlg.setTitle(_("No free starting position")) def display(self, caller = None): self.caller = caller if gdata.mainGameDlg and self.previousSelection: # this means connection dropped and we relogged # let's go straight to the previously selected game self._selectPlayer(self.previousSelection) return if self.show(): self.win.show() def hide(self): self.win.hide() def show(self): items = [] items.extend(self.showActivePlayers()) if self.wantsNew: items.extend(self.showStartPositions()) self.win.vPos.setItems(items) return True def showActivePlayers(self): dataActive = client.cmdProxy.getActivePositions() items = [] for playerID, galaxyName, playerType in dataActive: item = ui.Item(galaxyName, type = 'Active', tObjID = playerID, tPosType = Const.PLAYER_SELECT_CONTINUE) if playerType == Const.T_PLAYER: item.tPos = _('Continue playing.') elif playerType == Const.T_PIRPLAYER: item.tPos = _('Yarr!') else: item.tPos = _('Unknown type of player.') items.append(item) if not items: item = ui.Item('', type = '', tObjID = 'No active players', tPosType = None) item.tPos = 'No Active Player' items.append(item) return items def showStartPositions(self): dataStart = client.cmdProxy.getStartingPositions() items = [] for objID, galaxyName, posType in dataStart: item = ui.Item(galaxyName, type = _('Open'), tObjID = objID, tPosType = posType) if posType == Const.PLAYER_SELECT_NEWPLAYER: item.tPos = _('Independent player') elif posType == Const.PLAYER_SELECT_AIPLAYER: item.tPos = _("Rebel faction") elif posType == Const.PLAYER_SELECT_PIRATE: item.tPos = _("Pirate faction [VIP password needed]") else: item.tPos = _('Unknown. You cannot use this.') items.append(item) return items def onSelect(self, widget, action, data): if not self.win.vPos.selection: self.win.setStatus(_('Select position.')) return item = self.win.vPos.selection[0] if item.tPosType == Const.PLAYER_SELECT_CONTINUE: playerID = item.tObjID elif item.tPosType == Const.PLAYER_SELECT_NEWPLAYER: self.win.setStatus(_('Executing CREATE NEW PLAYER command...')) playerID = client.cmdProxy.createNewPlayer(item.tObjID) self.win.setStatus(_('Command has been executed.')) elif item.tPosType == Const.PLAYER_SELECT_AIPLAYER: self.win.setStatus(_('Executing TAKE OVER REBEL FACTION command...')) playerID = client.cmdProxy.takeOverAIPlayer(item.tObjID) self.win.setStatus(_('Command has been executed.')) elif item.tPosType == Const.PLAYER_SELECT_PIRATE: playerID = self.passwordDlg.display(lambda x: self._takeOverPirate(item.tObjID, x)) return else: return self._selectPlayer(playerID) def _takeOverPirate(self, positionID, password): self.win.setStatus(_('Executing TAKE OVER PIRATE FACTION command...')) try: playerID = client.cmdProxy.takeOverPirate(positionID, password) except ige.SecurityException: self.win.setStatus(_("Supply valid VIP password.")) return self.win.setStatus(_('Command has been executed.')) self._selectPlayer(playerID) def _selectPlayer(self, playerID): self.win.setStatus(_('Executing SELECT PLAYER command...')) client.cmdProxy.selectPlayer(playerID) self.previousSelection = playerID self.win.setStatus(_('Command has been executed.')) self.hide() if not gdata.mainGameDlg: gdata.mainGameDlg = MainGameDlg(self.app) gdata.mainGameDlg.display() client.updateDatabase() def onToggleNew(self, widget, action, data): self.wantsNew = not self.wantsNew if self.wantsNew: self.win.vToggle.text = _('Hide Open Slots') else: self.win.vToggle.text = _('Show Open Slots') self.win.vPos.unselectAll() self.needsPassword = False # there is a bug which prevents redraw for mere text change self.win.vToggle.visible = 0 self.win.vToggle.visible = 1 self.show() def onListSelect(self, widget, action, data): if data.tPosType == Const.PLAYER_SELECT_CONTINUE: playerID = data.tObjID self._selectPlayer(playerID) needsPassword = data.tPosType == Const.PLAYER_SELECT_PIRATE dirty = False if needsPassword != self.needsPassword: self.needsPassword = needsPassword def onBooking(self, widget, action, data): self.win.hide() self.win.setStatus(_('Command has been executed.')) BookingDlg(gdata.app).display(self) def onCancel(self, widget, action, data): self.win.hide() self.app.exit() def createUI(self): w, h = gdata.scrnSize self.win = ui.Window(self.app, modal = 1, movable = 0, title = _('Select gaming session'), rect = ui.Rect((w - 564) / 2, (h - 264) / 2, 564, 264), layoutManager = ui.SimpleGridLM(), tabChange = True ) ui.Listbox(self.win, layout = (0, 0, 28, 10), id = 'vPos', columns = ((_('Type'), 'type', 4, ui.ALIGN_W), (_('Galaxy'), 'text', 8, ui.ALIGN_W), (_('Position'), 'tPos', 0, ui.ALIGN_W)), action = 'onListSelect', columnLabels = 1) self.win.subscribeAction('*', self) ui.Button(self.win, layout = (20, 10, 8, 1), text = _('Book New Game'), action = 'onBooking', tooltipTitle = _("New galaxy"), tooltip = _("Allows you to either start new single player galaxy, or get in a queue for\ngame with other players. That game will start when queue fills the capacity,\nand will show up in this dialog as active.\n\nYou can queue for multiple galaxies. Only single player games has account limit.")) ui.Button(self.win, layout = (0, 10, 8, 1), id = 'vToggle', text = _('Show Open Slots'), action = 'onToggleNew', tooltipTitle = _("Open slots"), tooltip = _("Slots available in already running galaxies, there is no telling\nwhat state the game or the empire is in.")) ui.Title(self.win, layout = (0, 11, 20, 1), id = 'vStatusBar', align = ui.ALIGN_W) ui.TitleButton(self.win, layout = (20, 11, 4, 1), text = _('Exit'), action = 'onCancel') ui.TitleButton(self.win, layout = (24, 11, 4, 1), text = _('Select'), action = 'onSelect') self.win.statusBar = self.win.vStatusBar
class LoginDlg: def __init__(self, app): self.app = app self.newAccDlg = NewAccDlg(app) self.confirmDlg = ConfirmDlg(app) self.firstlogin = True self.versionChecked = False self.createUI() def display(self, caller=None, message=None): self.caller = caller # get game names from the server try: self.gameIDs = client.cmdProxy.getRegisteredGames() except IClientException: # server is probably down, what to do? self.gameIDs = {"UNDEFINED": "Not available"} except KeyError: # server does not support this call self.gameIDs = {"Alpha": "Alpha"} # show / hide new account button self.win.vCreate.visible = gdata.config.game.accountcreated == None # fill in default values if gdata.config.game.lastlogin != None: self.win.vLogin.text = gdata.config.game.lastlogin if gdata.config.game.lastpassword: self.win.vPassword.text = gdata.config.game.lastpassword if gdata.config.game.lastpasswordcrypted: self.win.vPassword.text = binascii.a2b_base64(gdata.config.game.lastpasswordcrypted) if not gdata.config.game.lastgameid: gdata.config.game.lastgameid = "Alpha" if gdata.config.game.lastgameid not in self.gameIDs: # use first gameid returned by server gdata.config.game.lastgameid = sorted(self.gameIDs.keys())[0] self.win.vUniverse.text = self.gameIDs[gdata.config.game.lastgameid] self.win.vUniverse.data = gdata.config.game.lastgameid # disable Universe selection if there's just one universe on the server self.win.vUniverse.enabled = len(self.gameIDs) > 1 self.win.vMessage.text = message # if gdata.config.game.autologin != 'yes': # enable this to disable auto-login after change in options # self.firstlogin = false self.win.show() if gdata.config.game.autologin == "yes": self.autoLogin() def hide(self): self.win.hide() def autoLogin(self): if self.firstlogin: self.firstlogin = False self.win.vMessage.text = _("Auto-login in progress ...") login = self.win.vLogin.text password = self.win.vPassword.text gameID = self.win.vUniverse.data self.doLogin(gameID, login, password) def onLogin(self, widget, action, data): self.firstlogin = False login = self.win.vLogin.text password = self.win.vPassword.text gameID = self.win.vUniverse.data self.win.vMessage.text = _("Login in progress ...") # self.win.hide() self.doLogin(gameID, login, password) def doLogin(self, gameID, login, password): result = client.login(gameID, login, password) self.win.hide() if result == 1: gdata.config.game.lastlogin = login # TODO: remove in 0.6 gdata.config.game.lastpassword = None # if gdata.savePassword: gdata.config.game.lastpasswordcrypted = binascii.b2a_base64(password).strip() else: gdata.config.game.lastpasswordcrypted = None gdata.config.game.lastgameid = gameID gdata.config.game.accountcreated = 1 # write configuration gdata.config.save() gdata.config.game.lastpasswordcrypted = binascii.b2a_base64(password).strip() # check version log.debug("Comparing server and client versions", client.serverVersion, version) if client.serverVersion != version and not self.versionChecked: # don't check next time in this session self.versionChecked = True # wow, a different version! self.confirmDlg.display( _("Your client version does not match server version %d.%d.%d%s. Do you want to continue?") % ( client.serverVersion["major"], client.serverVersion["minor"], client.serverVersion["revision"], client.serverVersion["status"], ), _("Yes"), _("No"), self.onContinueWithOld, self.app.exit, ) return # show main dialog if not gdata.mainGameDlg: gdata.mainGameDlg = MainGameDlg(self.app) gdata.mainGameDlg.display() client.updateDatabase() elif result == 2: pass else: # login failed self.win.vPassword.text = "" self.win.vMessage.text = _("Wrong login and/or password") self.win.show() def onCancel(self, widget, action, data): self.win.hide() if self.caller: self.caller.display() else: self.app.exit() def onContinueWithOld(self): # show main dialog self.win.hide() if not gdata.mainGameDlg: gdata.mainGameDlg = MainGameDlg(self.app) gdata.mainGameDlg.display() client.updateDatabase() def onCreateAccount(self, widget, action, data): self.win.hide() self.newAccDlg.display(self) def onOptions(self, widget, action, data): self.win.hide() gdata.config.game.lastpasswordcrypted = binascii.b2a_base64(self.win.vPassword.text).strip() OptionsDlg(gdata.app).display(self) def onUniverse(self, widget, action, data): # create menu items = list() index = 0 for gameID in sorted(self.gameIDs.keys()): item = ui.Item(self.gameIDs[gameID], data=gameID, action="onUniverseSelected") items.append(item) index += 1 self.universeMenu.items = items # show self.universeMenu.show((self.win.rect.x + 11 * 20 + 2, self.win.rect.y + 20 + 2)) def onUniverseSelected(self, widget, action, data): self.win.vUniverse.text = self.gameIDs[data] self.win.vUniverse.data = data def createUI(self): w, h = gdata.scrnSize self.win = ui.Window( self.app, modal=1, movable=0, title=_("Outer Space Login"), rect=ui.Rect((w - 424) / 2, (h - 144) / 2, 424, 144), layoutManager=ui.SimpleGridLM(), tabChange=True, ) self.win.subscribeAction("*", self) ui.Label(self.win, text=_("Universe"), align=ui.ALIGN_E, layout=(5, 0, 6, 1)) ui.Button(self.win, id="vUniverse", align=ui.ALIGN_W, layout=(11, 0, 10, 1), action="onUniverse") ui.Label(self.win, text=_("Login"), align=ui.ALIGN_E, layout=(5, 1, 6, 1)) ui.Entry(self.win, id="vLogin", align=ui.ALIGN_W, layout=(11, 1, 10, 1), orderNo=1) ui.Label(self.win, text=_("Password"), align=ui.ALIGN_E, layout=(5, 2, 6, 1)) ui.Entry(self.win, id="vPassword", align=ui.ALIGN_W, showChar="*", layout=(11, 2, 10, 1), orderNo=2) ui.Button(self.win, layout=(11, 3, 10, 1), text=_("Options"), action="onOptions", id="vOptions") ui.Button(self.win, layout=(11, 4, 10, 1), text=_("New account"), action="onCreateAccount", id="vCreate") ui.Title(self.win, layout=(0, 5, 11, 1), id="vMessage", align=ui.ALIGN_W) ui.TitleButton(self.win, layout=(11, 5, 5, 1), text=_("Exit"), action="onCancel") loginBtn = ui.TitleButton(self.win, layout=(16, 5, 5, 1), text=_("Login"), action="onLogin") ui.Label(self.win, layout=(0, 0, 5, 4), icons=((res.loginLogoImg, ui.ALIGN_W),)) self.win.acceptButton = loginBtn # Universe selection self.universeMenu = ui.Menu(self.app, title=_("Universes"), width=10) self.universeMenu.subscribeAction("*", self)
class NewAccountDlg: """ Called for a new player.""" def __init__(self, app): self.app = app self.createUI() self.confirmDlg = ConfirmDlg(app) self.confirmDlg.setTitle(_("No free starting position")) def display(self, caller=None): self.caller = caller if self.show(): self.win.show() def hide(self): self.win.hide() def show(self): positions = client.cmdProxy.getStartingPositions() if not positions: # there are no positions -- pop up a dialog self.confirmDlg.display( _("We are sorry, but there are no starting positions available at this moment. Please, try again later." ), _("Refresh"), _("Exit"), self.display, self.app.exit) return False items = [] for objID, name, posType in positions: item = ui.Item(name, tObjID=objID, tPosType=posType) if posType == STARTPOS_NEWPLAYER: item.tPos = _('Independent player') elif posType == STARTPOS_AIPLAYER: item.tPos = _("Rebel faction") elif posType == STARTPOS_PIRATE: item.tPos = _("Pirate faction [VIP password needed]") else: item.tPos = _('Unknown. You cannot use this.') items.append(item) self.win.vPos.setItems(items) return True def onSelect(self, widget, action, data): if not self.win.vPos.selection: self.win.setStatus(_('Select position.')) return item = self.win.vPos.selection[0] if item.tPosType == STARTPOS_NEWPLAYER: self.win.setStatus(_('Executing CREATE NEW PLAYER command...')) playerID = client.cmdProxy.createNewPlayer(item.tObjID) self.win.setStatus(_('Command has been executed.')) self.hide() if not gdata.mainGameDlg: gdata.mainGameDlg = MainGameDlg(self.app) gdata.mainGameDlg.display() client.updateDatabase(clearDB=1) elif item.tPosType == STARTPOS_AIPLAYER: self.win.setStatus( _('Executing TAKE OVER REBEL FACTION command...')) playerID = client.cmdProxy.takeOverAIPlayer(item.tObjID) self.win.setStatus(_('Command has been executed.')) self.hide() if not gdata.mainGameDlg: gdata.mainGameDlg = MainGameDlg(self.app) gdata.mainGameDlg.display() client.updateDatabase(clearDB=1) elif item.tPosType == STARTPOS_PIRATE: password = self.win.vPassword.text if not password: self.win.setStatus(_("Supply VIP password, please.")) return self.win.setStatus( _('Executing TAKE OVER PIRATE FACTION command...')) try: playerID = client.cmdProxy.takeOverPirate( item.tObjID, password) except ige.SecurityException: self.win.setStatus(_("Supply valid VIP password.")) return self.win.setStatus(_('Command has been executed.')) self.hide() if not gdata.mainGameDlg: gdata.mainGameDlg = MainGameDlg(self.app) gdata.mainGameDlg.display() client.updateDatabase(clearDB=1) def onCancel(self, widget, action, data): self.win.hide() if self.caller: self.caller.display() else: self.app.exit() def createUI(self): w, h = gdata.scrnSize self.win = ui.Window(self.app, modal=1, movable=0, title=_('Select starting position'), rect=ui.Rect((w - 424) / 2, (h - 264) / 2, 424, 264), layoutManager=ui.SimpleGridLM(), tabChange=True) ui.Listbox(self.win, layout=(0, 0, 21, 10), id='vPos', columns=((_('Galaxy'), 'text', 5, ui.ALIGN_W), (_('Position'), 'tPos', 0, ui.ALIGN_W)), columnLabels=1) self.win.subscribeAction('*', self) ui.Label(self.win, layout=(0, 10, 5, 1), text=_("VIP Password:")) ui.Entry(self.win, layout=(5, 10, 5, 1), id='vPassword', align=ui.ALIGN_W, showChar='*', orderNo=1) ui.Title(self.win, layout=(0, 11, 13, 1), id='vStatusBar', align=ui.ALIGN_W) ui.TitleButton(self.win, layout=(13, 11, 4, 1), text=_('Exit'), action='onCancel') ui.TitleButton(self.win, layout=(17, 11, 4, 1), text=_('Select'), action='onSelect') self.win.statusBar = self.win.vStatusBar
class MainGameDlg: def __init__(self, app): self.app = app self.starSystemDlg = StarSystemDlg(self.app) self.fleetDlg = FleetDlg(self.app) self.researchDlg = ResearchDlg(self.app) self.confirmDlg = ConfirmDlg(self.app) self.diplomacyDlg = DiplomacyDlg.DiplomacyDlg(self.app) self.constructionDlg = ConstructionDlg(self.app) self.messagesDlg = MessagesDlg(self.app) self.planetsOverviewDlg = PlanetsOverviewDlg(self.app) self.globalQueuesDlg = GlobalQueuesDlg(self.app) self.systemOverviewDlg = SystemOverviewDlg(self.app) self.fleetsOverviewDlg = FleetsOverviewDlg(self.app) self.optionsDlg = OptionsDlg(self.app) self.searchDlg = SearchDlg(self.app) self.problemsDlg = ProblemsDlg.ProblemsDlg(self.app) self.empireOverviewDlg = EmpireOverviewDlg.EmpireOverviewDlg(self.app) self.galaxyFinishDlg = GalaxyFinishDlg(self.app) self.planetsAnalysisDlg = PlanetsAnalysisDlg(app) self.fleetsAnalysisDlg = FleetsAnalysisDlg(app) self.mapWidget = None self.createUI() self.centered = 0 def display(self): self.app.showBackground = False gdata.mainGameDlg = self self.win.show() # register for updates gdata.updateDlgs.append(self) #self.refocus() def refocus(self): #log.debug("refocusing") self.app.setFocus(self.mapWidget) def onCmdInProgress(self, inProgress): if inProgress: self.win.vTurn.background = (0xff, 0xff, 0x00) else: self.win.vTurn.background = None def hide(self): self.app.showBackground = True self.win.hide() gdata.mainGameDlg = None # unregister updates if self in gdata.updateDlgs: gdata.updateDlgs.remove(self) def onExit(self, widget, action, data): self.app.setStatus(_('Exitting a session...')) self.hide() self.app.exitLocal() def onSelectMapObj(self, widget, action, data): self.win.vStarMap.highlightPos = None obj = client.get(data, noUpdate=1) if obj == None: self.app.setStatus(_('Cannot select object on map')) return if obj.type in (Const.T_PLANET, Const.T_SYSTEM, Const.T_WORMHOLE): self.starSystemDlg.onSelectMapObj(None, None, data) elif obj.type == Const.T_FLEET: self.fleetDlg.display(data) def onResearch(self, widget, action, data): self.researchDlg.display() def onDiplomacy(self, widget, action, data): self.diplomacyDlg.display() def onMessages(self, widget, action, data): self.messagesDlg.display() def onConstruction(self, widget, action, data): self.constructionDlg.display() def onPlanetsMenu(self, widget, action, data): self.systemPlanetMenu.show((16 * 20, 0)) def onPlanets(self, widget, action, data): self.planetsOverviewDlg.display() def onSystems(self, widget, action, data): self.systemOverviewDlg.display() def onPlanetAnalysis(self, widget, action, data): self.planetsAnalysisDlg.display() def onGlobalQueues(self, widget, action, data): self.globalQueuesDlg.display() def onFleetsMenu(self, widget, action, data): self.systemFleetMenu.show((20 * 20, 0)) def onFleets(self, widget, action, data): self.fleetsOverviewDlg.display() def onFleetAnalysis(self, widget, action, data): self.fleetsAnalysisDlg.display() def onOptions(self, widget, action, data): self.optionsDlg.display() def onProblems(self, widget, action, data): self.problemsDlg.display() def onOverview(self, widget, action, data): self.empireOverviewDlg.display() def onSearch(self, widget, action, data): self.searchDlg.display() def onStats(self, widget, action, data): url = 'http://%s/%s/galaxy%d.html' % ( gdata.config.game.server, gdata.config.game.lastgameid, client.getPlayer().galaxy, ) webbrowser.open(url, new=1) def onResign(self, widget, action, data): # swap yes and no self.confirmDlg.display(_('Are you sure to resign current game?'), _('No'), _('Yes'), cancelAction=self.onResignConfirmed) def onSaveView(self, widget, action, data): self.confirmDlg.display( _('Save the current starmap view as an image?'), _('Yes'), _('No'), confirmAction=self.onSaveViewConfirm) def onSaveViewConfirm(self): turn = client.getTurn() name = 'view_' + res.formatTime(turn, '_') full_name = os.path.join(gdata.config.game.screenshot_dir, name) savedas = self.mapWidget.save(full_name, chronicle_shot=False) self.confirmDlg.display(_('File saved as %s' % savedas), _('OK'), False) def onSaveStarmap(self, widget, action, data): self.confirmDlg.display(_('Save whole galaxy starmap as an image?'), _('Yes'), _('No'), confirmAction=self.onSaveStarmapConfirm) 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 onMenu(self, widget, action, data): w, h = gdata.scrnSize self.systemMenu.show((w - self.systemMenu.width * 20 - 4, 0)) def onResignConfirmed(self): client.cmdProxy.resign(client.getPlayerID()) client.db.clear() self.app.exitLocal() def onToggleTime(self, widget, action, data): galaxyID = client.getPlayer().galaxy galaxy = client.get(galaxyID) galaxy.timeEnabled = client.cmdProxy.toggleTime(galaxyID) self.alterMenu(None, None, False) def onFinishConfirmedSingle(self): self.onFinishConfirmed(None, Const.SCENARIO_SINGLE) def onFinishConfirmedOuterspace(self, imperatorMsg): self.onFinishConfirmed(imperatorMsg, Const.SCENARIO_OUTERSPACE) def onFinishConfirmed(self, imperatorMsg, scenario): self.win.setStatus(_('Galaxy finish in progress...')) oldMsgHandler = client.cmdProxy.msgHandler client.cmdProxy.msgHandler = None client.cmdProxy.keepAliveTime = 60 * 60 # do not try to connect to server (one hour) if scenario == Const.SCENARIO_SINGLE: client.cmdProxy.deleteSingle(client.getPlayer().galaxy) elif scenario == Const.SCENARIO_OUTERSPACE: client.cmdProxy.finishGalaxyImperator(Const.OID_UNIVERSE, client.getPlayer().galaxy, imperatorMsg) else: return client.db.clear() client.cmdProxy.msgHandler = oldMsgHandler self.hide() self.app.exitLocal() 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 def alterMenu(self, widget, action, data): """ Update menu according to current situation, being different in singleplayer or when player is imperator of competitive galaxy, or player has no rights to finish galaxy at all. """ if client.db != None: player = client.getPlayer() galaxy = client.get(player.galaxy) # player can restart (finish) it's own singleplayer galaxy anytime if galaxy.scenario == Const.SCENARIO_SINGLE: # depends on state of galaxy if not galaxy.timeEnabled: self.systemMenu.items[7].text = _("Resume galaxy") else: self.systemMenu.items[7].text = _("Pause galaxy") self.systemMenu.items[7].action = "onToggleTime" self.systemMenu.items[6].enabled = True self.systemMenu.items[7].enabled = True elif galaxy.scenario == Const.SCENARIO_OUTERSPACE: # standard behavior if player.imperator > 2: # player is imperator for more than two weeks - has right to finish galaxy self.systemMenu.items[6].enabled = True else: # no right to finish galaxy self.systemMenu.items[6].enabled = False # you cannot resign when time is stopped if galaxy.timeEnabled: self.systemMenu.items[7].enabled = True else: self.systemMenu.items[7].enabled = False def galaxyFinishButton(self, widget, action, data): player = client.getPlayer() galaxy = client.get(player.galaxy) if galaxy.scenario == Const.SCENARIO_OUTERSPACE and player.imperator > 2: localTime = time.time() gdata.config.game.lastGalaxyFinishShown = str(localTime) self.galaxyFinishDlg.display( finishAction=self.onFinishConfirmedOuterspace) elif galaxy.scenario == Const.SCENARIO_SINGLE: self.confirmDlg.display(_( 'Are you really really sure you want to finish this single player galaxy of yours? You won\'t be able to get back.' ), _('Finish'), _('No'), confirmAction=self.onFinishConfirmedSingle) def galaxyFinishPopup(self, widget, action, data): """ Pop up dialog to finish galaxy in case player is eligible imperator of competitive galaxy. Do this once per day. """ if client.db != None: player = client.getPlayer() galaxy = client.get(player.galaxy) if galaxy.scenario == Const.SCENARIO_OUTERSPACE and player.imperator > 2: lastGalaxyFinishShown = gdata.config.game.lastGalaxyFinishShown if lastGalaxyFinishShown != None: localTime = time.time() storedTime = float(lastGalaxyFinishShown) if localTime - storedTime > 60 * 60 * 24: gdata.config.game.lastGalaxyFinishShown = str( localTime) self.galaxyFinishDlg.display( finishAction=self.onFinishConfirmedOuterspace) else: gdata.config.game.lastGalaxyFinishShown = str(time.time()) self.galaxyFinishDlg.display( finishAction=self.onFinishConfirmedOuterspace) def updateMsgButton(self): if self.messagesDlg.newMsgs > 0: self.win.vMessages.foreground = gdata.sevColors[gdata.MAJ] else: self.win.vMessages.foreground = None def processKeyUp(self, evt): if evt.key == pygame.K_F12 and pygame.key.get_mods( ) & pygame.KMOD_CTRL: self.onExit(None, None, None) return ui.NoEvent def processKeyDown(self, evt): # Alt+M - Messages if evt.unicode == u'\x6D' and pygame.key.get_mods() & pygame.KMOD_ALT: self.messagesDlg.display() # Alt+R - Research elif evt.unicode == u'\x72' and pygame.key.get_mods( ) & pygame.KMOD_ALT: self.researchDlg.display() # Alt+D - Diplomacy elif evt.unicode == u'\x64' and pygame.key.get_mods( ) & pygame.KMOD_ALT: self.diplomacyDlg.display() # Alt+C - Constr elif evt.unicode == u'\x63' and pygame.key.get_mods( ) & pygame.KMOD_ALT: self.constructionDlg.display() # Alt+P - Planets elif evt.unicode == u'\x70' and pygame.key.get_mods( ) & pygame.KMOD_ALT: self.onPlanetsMenu( False, False, False) # use onPlanetsMenu rather than direct control # Alt+F - Fleets elif evt.unicode == u'\x66' and pygame.key.get_mods( ) & pygame.KMOD_ALT: self.onFleetsMenu( False, False, False) # use onFleetsMenu rather than direct control # Alt+O - Overview elif evt.unicode == u'\x6F' and pygame.key.get_mods( ) & pygame.KMOD_ALT: self.empireOverviewDlg.display() # Alt+B - Pro'b'lems elif evt.unicode == u'\x62' and pygame.key.get_mods( ) & pygame.KMOD_ALT: self.problemsDlg.display() # Alt+N - Me'n'u elif evt.unicode == u'\x6E' and pygame.key.get_mods( ) & pygame.KMOD_ALT: self.onMenu(False, False, False) # use onMenu rather than direct control def createUI(self): w, h = gdata.scrnSize lw, lh = w / 20, h / 20 self.win = ui.Window( self.app, modal=1, decorated=0, alwaysInBackground=1, movable=0, rect=ui.Rect(0, 0, w, h), layoutManager=ui.SimpleGridLM(), ) self.win.subscribeAction('*', self) # map self.mapWidget = StarMapWidget(self.win, id='vStarMap', action='onSelectMapObj', layout=(0, 1, lw, lh - 2)) self.searchDlg.mapWidget = self.mapWidget self.win.callEventHandler = self.mapWidget self.mapWidget.callEventHandler = self # bottom ui.Label( self.win, id='vStatus', align=ui.ALIGN_W, layout=(0, lh - 1, lw - 16, 1), ) ui.Label( self.win, id='vTurn', align=ui.ALIGN_E, text='????.??', font='normal-bold', layout=(lw - 4, lh - 1, 4, 1), ) # top ui.Button(self.win, layout=(0, 0, 4, 1), text=_('Messages'), action='onMessages', id="vMessages") ui.Button(self.win, layout=(4, 0, 4, 1), text=_('Research'), action='onResearch') ui.Button(self.win, layout=(8, 0, 4, 1), text=_('Diplomacy'), id="vDiplomacy", action='onDiplomacy', enabled=0) ui.Button(self.win, layout=(12, 0, 4, 1), text=_('Constr'), id="vConstruction", action='onConstruction', enabled=0) ui.Button(self.win, layout=(16, 0, 4, 1), text=_('Planets'), id="vPlanetsMenu", action='onPlanetsMenu', enabled=1) ui.Button(self.win, layout=(20, 0, 4, 1), text=_('Fleets'), id="vFleetsMenu", action='onFleetsMenu', enabled=1) ui.Button(self.win, layout=(24, 0, 4, 1), text=_('Overview'), id="vOverview", action='onOverview', enabled=1) ui.Title(self.win, layout=(28, 0, lw - 37, 1)) ui.Button(self.win, layout=(lw - 9, 0, 4, 1), text=_('Problems'), action='onProblems') ui.Button(self.win, layout=(lw - 5, 0, 5, 1), text=_('Menu'), action='onMenu') self.app.statusBar = self.win.vStatus self.app.setStatus(_('Ready.')) # system menu self.systemMenu = ui.Menu( self.app, title=_("Menu"), width=5, items=[ ui.Item(_("Find system"), action="onSearch", hotkey=u'\x66'), # F ui.Item(_("Statistics"), action="onStats", hotkey=u'\x73'), # S ui.Item(_("Save View"), action="onSaveView", hotkey=u'\x76'), # V ui.Item(_("Save Starmap"), action="onSaveStarmap"), ui.Item(_("Options"), action="onOptions", hotkey=u'\x6F'), # O ui.Item(_("--------"), enabled=False), ui.Item( _("Finish galaxy"), action="galaxyFinishButton", enabled=False, data=True ), # no hotkey; if this position moved, you need to update finishGalaxy's "self.systemMenu.items" lines to reference new index position ui.Item(_("Resign"), action="onResign"), # no hotkey ui.Item(_("--------"), enabled=False), ui.Item(_("Exit"), action="onExit", hotkey=u'\x71'), # Q (also directly CTRL+F12) ]) self.systemMenu.subscribeAction("*", self) self.systemFleetMenu = ui.Menu( self.app, title=_("Fleets"), width=4, items=[ ui.Item(_("Fleet List"), action="onFleets", hotkey=u'\x66'), # F ui.Item(_("Analysis"), action="onFleetAnalysis", hotkey=u'\x61'), # A ]) self.systemFleetMenu.subscribeAction("*", self) self.systemPlanetMenu = ui.Menu( self.app, title=_("Planets"), width=5, items=[ ui.Item(_("Planet List"), action="onPlanets", hotkey=u'\x70'), # P ui.Item(_("System List"), action="onSystems", hotkey=u'\x73'), # S ui.Item(_("Global queues"), action="onGlobalQueues"), ui.Item(_("Analysis"), action="onPlanetAnalysis", hotkey=u'\x61'), #A ]) self.systemPlanetMenu.subscribeAction("*", self)
def __init__(self, app): self.app = app self.confirmDlg = ConfirmDlg(self.app) self.createUI()
class MainGameDlg: def __init__(self, app): self.app = app self.starSystemDlg = StarSystemDlg(self.app) self.fleetDlg = FleetDlg(self.app) self.researchDlg = ResearchDlg(self.app) self.confirmDlg = ConfirmDlg(self.app) self.diplomacyDlg = DiplomacyDlg.DiplomacyDlg(self.app) self.constructionDlg = ConstructionDlg(self.app) self.messagesDlg = MessagesDlg(self.app) self.planetsOverviewDlg = PlanetsOverviewDlg(self.app) self.systemOverviewDlg = SystemOverviewDlg(self.app) self.fleetsOverviewDlg = FleetsOverviewDlg(self.app) self.optionsDlg = OptionsDlg(self.app) self.searchDlg = SearchDlg(self.app) self.problemsDlg = ProblemsDlg.ProblemsDlg(self.app) self.empireOverviewDlg = EmpireOverviewDlg.EmpireOverviewDlg(self.app) self.galaxyRestartDlg = GalaxyRestartDlg(self.app) self.planetsAnalysisDlg = PlanetsAnalysisDlg(app) self.fleetsAnalysisDlg = FleetsAnalysisDlg(app) self.mapWidget = None self.createUI() self.centered = 0 def display(self): gdata.showBackground = 0 gdata.mainGameDlg = self self.win.show() # register for updates gdata.updateDlgs.append(self) #self.refocus() def refocus(self): #log.debug("refocusing") self.app.setFocus(self.mapWidget) def onCmdInProgress(self, inProgress): if inProgress: self.win.vTurn.background = (0xff, 0xff, 0x00) else: self.win.vTurn.background = None def hide(self): gdata.showBackground = 1 self.win.hide() gdata.mainGameDlg = None # unregister updates if self in gdata.updateDlgs: gdata.updateDlgs.remove(self) def onQuit(self, widget, action, data): self.app.setStatus(_('Logging out and exitting...')) self.app.exit() def onSelectMapObj(self, widget, action, data): self.win.vStarMap.highlightPos = None obj = client.get(data, noUpdate = 1) if obj == None: self.app.setStatus(_('Cannot select object on map')) return if obj.type in (T_PLANET, T_SYSTEM, T_WORMHOLE): self.starSystemDlg.display(data) elif obj.type == T_FLEET: self.fleetDlg.display(data) def onResearch(self, widget, action, data): self.researchDlg.display() def onDiplomacy(self, widget, action, data): self.diplomacyDlg.display() def onMessages(self, widget, action, data): self.messagesDlg.display() def onConstruction(self, widget, action, data): self.constructionDlg.display() def onPlanetsMenu(self, widget, action, data): self.systemPlanetMenu.show((16*20, 0)) def onPlanets(self, widget, action, data): self.planetsOverviewDlg.display() def onSystems(self, widget, action, data): self.systemOverviewDlg.display() def onPlanetAnalysis(self, widget, action, data): self.planetsAnalysisDlg.display() def onPlanetAnalysis(self, widget, action, data): self.planetsAnalysisDlg.display() def onFleetsMenu(self, widget, action, data): self.systemFleetMenu.show((20*20, 0)) def onFleets(self, widget, action, data): self.fleetsOverviewDlg.display() def onFleetAnalysis(self, widget, action, data): self.fleetsAnalysisDlg.display() def onOptions(self, widget, action, data): self.optionsDlg.display() def onProblems(self, widget, action, data): self.problemsDlg.display() def onOverview(self, widget, action, data): self.empireOverviewDlg.display() def onSearch(self, widget, action, data): self.searchDlg.display() def onStats(self, widget, action, data): for galaxyID in client.getPlayer().galaxies: url = 'http://%s/%s/galaxy%d.html' % ( gdata.config.game.server, gdata.config.game.lastgameid, galaxyID, ) webbrowser.open(url, new = 1) def onResign(self, widget, action, data): # swap yes and no self.confirmDlg.display(_('Are you sure to resign current game?'), _('No'), _('Yes'), cancelAction = self.onResignConfirmed) def onSaveStarmap(self, widget, action, data): self.confirmDlg.display(_('Save the current starmap view as an image?'), _('Yes'), _('No'), confirmAction = self.onSaveStarmapConfirm) 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) def onMenu(self, widget, action, data): w, h = gdata.scrnSize self.systemMenu.show((w - self.systemMenu.width * 20 - 4, 0)) def onResignConfirmed(self): client.cmdProxy.resign(client.getPlayerID()) client.db.clear() self.app.exit() def onRestartConfirmed(self, imperatorMsg): self.win.setStatus(_('Galaxy restart in progress...')) oldMsgHandler = client.cmdProxy.msgHandler client.cmdProxy.msgHandler = None client.cmdProxy.keepAliveTime = 60 * 60 # do not try to connect to server (one hour) client.cmdProxy.restartGalaxy(OID_UNIVERSE, client.getPlayer().galaxies[0], imperatorMsg) client.db.clear() client.cmdProxy.msgHandler = oldMsgHandler self.hide() self.app.exit() 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 def galaxyRestart(self, widget, action, data): shownFromMenu = bool(data) if client.db != None: player = client.getPlayer() if player.imperator > 2: self.systemMenu.items[3].enabled = True lastGalaxyRestartShown = gdata.config.game.lastGalaxyRestartShown if lastGalaxyRestartShown != None: localTime = time.time() storedTime = float(lastGalaxyRestartShown) if localTime - storedTime > 60 * 60 * 24 or shownFromMenu == True: gdata.config.game.lastGalaxyRestartShown = str(localTime) self.galaxyRestartDlg.display(restartAction = self.onRestartConfirmed) else: gdata.config.game.lastGalaxyRestartShown = str(time.time()) self.galaxyRestartDlg.display(restartAction = self.onRestartConfirmed) else: self.systemMenu.items[3].enabled = False if shownFromMenu == True: self.win.setStatus(_("Only imperator elected three times and more can restart galaxy.")) def updateMsgButton(self): if self.messagesDlg.newMsgs > 0: self.win.vMessages.foreground = gdata.sevColors[gdata.MAJ] else: self.win.vMessages.foreground = None def processKeyUp(self, evt): return ui.NoEvent def processKeyDown(self, evt): # Alt+M - Messages if evt.unicode == u'\x6D' and pygame.key.get_mods() & KMOD_ALT: self.messagesDlg.display() # Alt+R - Research elif evt.unicode == u'\x72' and pygame.key.get_mods() & KMOD_ALT: self.researchDlg.display() # Alt+D - Diplomacy elif evt.unicode == u'\x64' and pygame.key.get_mods() & KMOD_ALT: self.diplomacyDlg.display() # Alt+C - Constr elif evt.unicode == u'\x63' and pygame.key.get_mods() & KMOD_ALT: self.constructionDlg.display() # Alt+P - Planets elif evt.unicode == u'\x70' and pygame.key.get_mods() & KMOD_ALT: self.onPlanetsMenu(False,False,False) # use onPlanetsMenu rather than direct control # Alt+F - Fleets elif evt.unicode == u'\x66' and pygame.key.get_mods() & KMOD_ALT: self.onFleetsMenu(False,False,False) # use onFleetsMenu rather than direct control # Alt+O - Overview elif evt.unicode == u'\x6F' and pygame.key.get_mods() & KMOD_ALT: self.empireOverviewDlg.display() # Alt+B - Pro'b'lems elif evt.unicode == u'\x62' and pygame.key.get_mods() & KMOD_ALT: self.problemsDlg.display() # Alt+N - Me'n'u elif evt.unicode == u'\x6E' and pygame.key.get_mods() & KMOD_ALT: self.onMenu(False,False,False) # use onMenu rather than direct control def createUI(self): w, h = gdata.scrnSize lw, lh = w / 20, h / 20 self.win = ui.Window(self.app, modal = 1, decorated = 0, alwaysInBackground = 1, movable = 0, rect = ui.Rect(0, 0, w, h), layoutManager = ui.SimpleGridLM(), ) self.win.subscribeAction('*', self) # map self.mapWidget = StarMapWidget(self.win, id = 'vStarMap', action = 'onSelectMapObj', layout = (0, 1, lw, lh - 2) ) self.searchDlg.mapWidget = self.mapWidget self.win.callEventHandler = self.mapWidget self.mapWidget.callEventHandler = self # bottom ui.Label(self.win, id = 'vStatus', align = ui.ALIGN_W, layout = (0, lh - 1, lw - 16, 1), ) ui.Label(self.win, id = 'vTurn', align = ui.ALIGN_E, text = '????.??', font = 'normal-bold', layout = (lw - 4, lh - 1, 4, 1), ) # top ui.Button(self.win, layout = (0, 0, 4, 1), text = _('Messages'), action = 'onMessages', id = "vMessages") ui.Button(self.win, layout = (4, 0, 4, 1), text = _('Research'), action = 'onResearch') ui.Button(self.win, layout = (8, 0, 4, 1), text = _('Diplomacy'), id = "vDiplomacy", action = 'onDiplomacy', enabled = 0) ui.Button(self.win, layout = (12, 0, 4, 1), text = _('Constr'), id = "vConstruction", action = 'onConstruction', enabled = 0) ui.Button(self.win, layout = (16, 0, 4, 1), text = _('Planets'), id = "vPlanetsMenu", action = 'onPlanetsMenu', enabled = 1) ui.Button(self.win, layout = (20, 0, 4, 1), text = _('Fleets'), id = "vFleetsMenu", action = 'onFleetsMenu', enabled = 1) ui.Button(self.win, layout = (24, 0, 4, 1), text = _('Overview'), id = "vOverview", action = 'onOverview', enabled = 1) ui.Title(self.win, layout = (28, 0, lw - 37, 1)) ui.Button(self.win, layout = (lw - 9, 0, 4, 1), text = _('Problems'), action = 'onProblems') ui.Button(self.win, layout = (lw - 5, 0, 5, 1), text = _('Menu'), action = 'onMenu') self.app.statusBar = self.win.vStatus self.app.setStatus(_('Ready.')) # system menu self.systemMenu = ui.Menu(self.app, title = _("Menu"), width = 5, items = [ ui.Item(_("Find system"), action = "onSearch", hotkey = u'\x66'), # F ui.Item(_("Statistics"), action = "onStats", hotkey = u'\x73'), # S ui.Item(_("Save Starmap"), action = "onSaveStarmap", hotkey = u'\x76'), # V ui.Item(_("Galaxy restart"), action = "galaxyRestart", enabled = False, data = True), # no hotkey; if this position moved, you need to update restartGalaxy's "self.systemMenu.items" lines to reference new index position ui.Item(_("Options"), action = "onOptions", hotkey = u'\x6F'), # O ui.Item(_("--------"), enabled = False), ui.Item(_("Resign"), action = "onResign"), # no hotkey ui.Item(_("--------"), enabled = False), ui.Item(_("Quit"), action = "onQuit", hotkey = u'\x71'), # Q ] ) self.systemMenu.subscribeAction("*", self) self.systemFleetMenu = ui.Menu(self.app, title = _("Fleets"), width = 4, items = [ ui.Item(_("Fleet List"), action = "onFleets", hotkey = u'\x66'), # F ui.Item(_("Analysis"), action = "onFleetAnalysis", hotkey = u'\x61'), # A ] ) self.systemFleetMenu.subscribeAction("*", self) self.systemPlanetMenu = ui.Menu(self.app, title = _("Planets"), width = 4, items = [ ui.Item(_("Planet List"), action = "onPlanets", hotkey = u'\x70'), # P ui.Item(_("System List"), action = "onSystems", hotkey = u'\x73'), # S ui.Item(_("Analysis"), action = "onPlanetAnalysis", hotkey = u'\x61'), #A ] ) self.systemPlanetMenu.subscribeAction("*", self)
class StructTaskDlg: def __init__(self, app): self.app = app self.showStructures = 1 self.showShips = 0 self.showOther = 0 self.techID = 0 self.sort = 'type' self.showLevels = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] self.techInfoDlg = TechInfoDlg(app) self.confirmDlg = ConfirmDlg(app) self.createUI() def display(self, caller, planetID, extraSlot = False, structToDemolish = OID_NONE): if gdata.config.defaults.reportfinalization != None: val = gdata.config.defaults.reportfinalization self.win.vReportFin.checked = val == 'yes' self.caller = caller self.systemID = caller.systemID self.planetID = caller.planetID self.playerID = client.getPlayerID() self.sourceID = caller.planetID self.extraSlot = extraSlot self.maxTechLevel = 0 self.quantity = 1 self.govTransferConfirm = False self.govTransferData = None self.structToDemolish = structToDemolish self.win.vPlanets.selectItem(None) self.showPlanets() self.showTechs() self.win.show() gdata.updateDlgs.append(self) def hide(self): self.win.setStatus(_("Ready.")) if self in gdata.updateDlgs: gdata.updateDlgs.remove(self) self.win.hide() def update(self): if self.win.visible: self.quantity = int(self.win.vQuantity.text) self.showPlanets() self.showTechs() def showPlanets(self): info = [] system = client.get(self.systemID, noUpdate = 1) select = None playerID = client.getPlayerID() firstEnabled = None if hasattr(system, 'planets'): for planetID in system.planets: # get planet planet = client.get(planetID, noUpdate = 1) # only player owned planets can be source planets enabled = getattr(planet, "owner") == playerID buttonText = "%s / %s" % (getattr(planet, 'name', res.getUnknownName()), getattr(planet, "effProdProd", "?")) item = ui.Item( buttonText, planetID = planetID, enabled = enabled, align = ui.ALIGN_NONE, ) info.append(item) # remember first players planet if enabled and firstEnabled == None: firstEnabled = item # select actual planet as source only if player owns it if planetID == self.sourceID and enabled: select = item # set as selected source first players planet if select == None: select = firstEnabled self.sourceID = firstEnabled.planetID self.win.vPlanets.items = info self.win.vPlanets.itemsChanged() self.win.vPlanets.selectItem(select) 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) def onSelectPlanet(self, widget, action, data): if data == None: for item in self.win.vPlanets.items: if self.sourceID == item.planetID: self.win.vPlanets.selectItem(item) break return self.quantity = int(self.win.vQuantity.text) self.sourceID = data.planetID self.showTechs() def onToggleLevel(self, widget, action, data): i = widget.data if i in self.showLevels: self.showLevels.remove(i) else: self.showLevels.append(i) self.update() def onCancel(self, widget, action, data): self.hide() def onGovTransferConfirmed(self): # we assume player wants to build just one center - in opposite case, he may change quantity in the task itself self.win.vQuantity.text = str(1) self.govTransferConfirm = True self.onConstruct(*self.govTransferData) def onConstruct(self, widget, action, data): if not data: self.win.setStatus(_('Select technology to construct.')) return if not self.sourceID: self.sourceID = self.planetID try: self.quantity = int(self.win.vQuantity.text) except ValueError: self.win.setStatus(_('Specify quantity (1, 2, 3, ...).')) return # government centers have additional query and if confirmed, another round of this function is called tech = client.getTechInfo(data.techID) if tech.govPwr and not self.govTransferConfirm: # confirm dialog doesn't send through parameters, so we have to save them self.govTransferData = (widget, action, data) self.confirmDlg.display(_("Do you want to issue relocation of your government?"), _("Yes"), _("No"), self.onGovTransferConfirmed) else: try: self.win.setStatus(_('Executing START CONSTRUCTION command...')) planet = client.get(self.sourceID, noUpdate = 1) player = client.getPlayer() if self.extraSlot: # check required special resources, if not available, do not continue # (without check, server start slot expansion but not the tech) specialResources = player.stratRes for sr in tech.buildSRes: if specialResources.get(sr, 0) < self.quantity: self.win.setStatus(_('You do not own required strategic resource(s)')) return else: specialResources[sr] = specialResources.get(sr, 0) - self.quantity for i in range(1, self.quantity + 1): # as we need two slots instead of one, check whether is task queue short # enough (ie 8 tasks max) if len(planet.prodQueue) > 8: self.win.setStatus(_('Queue is full')) return client.cmdProxy.startConstruction(self.sourceID, Rules.Tech.ADDSLOT3, 1, self.planetID, False, self.win.vReportFin.checked, OID_NONE) planet.prodQueue, player.stratRes = client.cmdProxy.startConstruction(self.sourceID, data.techID, 1, self.planetID, data.techID < 1000, self.win.vReportFin.checked, self.structToDemolish) else: planet.prodQueue, player.stratRes = client.cmdProxy.startConstruction(self.sourceID, data.techID, self.quantity, self.planetID, data.techID < 1000, self.win.vReportFin.checked, self.structToDemolish) self.win.setStatus(_('Command has been executed.')) except GameException, e: self.win.setStatus(e.args[0]) return self.hide() self.caller.update()
class MainGameDlg: def __init__(self, app): self.app = app self.starSystemDlg = StarSystemDlg(self.app) self.fleetDlg = FleetDlg(self.app) self.researchDlg = ResearchDlg(self.app) self.confirmDlg = ConfirmDlg(self.app) self.diplomacyDlg = DiplomacyDlg.DiplomacyDlg(self.app) self.constructionDlg = ConstructionDlg(self.app) self.messagesDlg = MessagesDlg(self.app) self.planetsOverviewDlg = PlanetsOverviewDlg(self.app) self.globalQueuesDlg = GlobalQueuesDlg(self.app) self.systemOverviewDlg = SystemOverviewDlg(self.app) self.fleetsOverviewDlg = FleetsOverviewDlg(self.app) self.optionsDlg = OptionsDlg(self.app) self.searchDlg = SearchDlg(self.app) self.problemsDlg = ProblemsDlg.ProblemsDlg(self.app) self.empireOverviewDlg = EmpireOverviewDlg.EmpireOverviewDlg(self.app) self.galaxyFinishDlg = GalaxyFinishDlg(self.app) self.planetsAnalysisDlg = PlanetsAnalysisDlg(app) self.fleetsAnalysisDlg = FleetsAnalysisDlg(app) self.mapWidget = None self.createUI() self.centered = 0 def display(self): self.app.showBackground = False gdata.mainGameDlg = self self.win.show() # register for updates gdata.updateDlgs.append(self) #self.refocus() def refocus(self): #log.debug("refocusing") self.app.setFocus(self.mapWidget) def onCmdInProgress(self, inProgress): if inProgress: self.win.vTurn.background = (0xff, 0xff, 0x00) else: self.win.vTurn.background = None def hide(self): self.app.showBackground = True self.win.hide() gdata.mainGameDlg = None # unregister updates if self in gdata.updateDlgs: gdata.updateDlgs.remove(self) def onExit(self, widget, action, data): self.app.setStatus(_('Exitting a session...')) self.hide() self.app.exitLocal() def onSelectMapObj(self, widget, action, data): self.win.vStarMap.highlightPos = None obj = client.get(data, noUpdate = 1) if obj == None: self.app.setStatus(_('Cannot select object on map')) return if obj.type in (Const.T_PLANET, Const.T_SYSTEM, Const.T_WORMHOLE): self.starSystemDlg.onSelectMapObj(None, None, data) elif obj.type == Const.T_FLEET: self.fleetDlg.display(data) def onResearch(self, widget, action, data): self.researchDlg.display() def onDiplomacy(self, widget, action, data): self.diplomacyDlg.display() def onMessages(self, widget, action, data): self.messagesDlg.display() def onConstruction(self, widget, action, data): self.constructionDlg.display() def onPlanetsMenu(self, widget, action, data): self.systemPlanetMenu.show((16*20, 0)) def onPlanets(self, widget, action, data): self.planetsOverviewDlg.display() def onSystems(self, widget, action, data): self.systemOverviewDlg.display() def onPlanetAnalysis(self, widget, action, data): self.planetsAnalysisDlg.display() def onGlobalQueues(self, widget, action, data): self.globalQueuesDlg.display() def onFleetsMenu(self, widget, action, data): self.systemFleetMenu.show((20*20, 0)) def onFleets(self, widget, action, data): self.fleetsOverviewDlg.display() def onFleetAnalysis(self, widget, action, data): self.fleetsAnalysisDlg.display() def onOptions(self, widget, action, data): self.optionsDlg.display() def onProblems(self, widget, action, data): self.problemsDlg.display() def onOverview(self, widget, action, data): self.empireOverviewDlg.display() def onSearch(self, widget, action, data): self.searchDlg.display() def onStats(self, widget, action, data): url = 'http://%s/%s/galaxy%d.html' % ( gdata.config.game.server, gdata.config.game.lastgameid, client.getPlayer().galaxy, ) webbrowser.open(url, new = 1) def onResign(self, widget, action, data): # swap yes and no self.confirmDlg.display(_('Are you sure to resign current game?'), _('No'), _('Yes'), cancelAction = self.onResignConfirmed) def onSaveView(self, widget, action, data): self.confirmDlg.display(_('Save the current starmap view as an image?'), _('Yes'), _('No'), confirmAction = self.onSaveViewConfirm) def onSaveViewConfirm(self): turn = client.getTurn() name = 'view_' + res.formatTime(turn,'_') full_name = os.path.join(gdata.config.game.screenshot_dir, name) savedas = self.mapWidget.save(full_name, chronicle_shot=False) self.confirmDlg.display(_('File saved as %s' % savedas), _('OK'), False) def onSaveStarmap(self, widget, action, data): self.confirmDlg.display(_('Save whole galaxy starmap as an image?'), _('Yes'), _('No'), confirmAction = self.onSaveStarmapConfirm) 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 onMenu(self, widget, action, data): w, h = gdata.scrnSize self.systemMenu.show((w - self.systemMenu.width * 20 - 4, 0)) def onResignConfirmed(self): client.cmdProxy.resign(client.getPlayerID()) client.db.clear() self.app.exitLocal() def onToggleTime(self, widget, action, data): galaxyID = client.getPlayer().galaxy galaxy = client.get(galaxyID) galaxy.timeEnabled = client.cmdProxy.toggleTime(galaxyID) self.alterMenu(None, None, False) def onFinishConfirmedSingle(self): self.onFinishConfirmed(None, Const.SCENARIO_SINGLE) def onFinishConfirmedOuterspace(self, imperatorMsg): self.onFinishConfirmed(imperatorMsg, Const.SCENARIO_OUTERSPACE) def onFinishConfirmed(self, imperatorMsg, scenario): self.win.setStatus(_('Galaxy finish in progress...')) oldMsgHandler = client.cmdProxy.msgHandler client.cmdProxy.msgHandler = None client.cmdProxy.keepAliveTime = 60 * 60 # do not try to connect to server (one hour) if scenario == Const.SCENARIO_SINGLE: client.cmdProxy.deleteSingle(client.getPlayer().galaxy) elif scenario == Const.SCENARIO_OUTERSPACE: client.cmdProxy.finishGalaxyImperator(Const.OID_UNIVERSE, client.getPlayer().galaxy, imperatorMsg) else: return client.db.clear() client.cmdProxy.msgHandler = oldMsgHandler self.hide() self.app.exitLocal() 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 def alterMenu(self, widget, action, data): """ Update menu according to current situation, being different in singleplayer or when player is imperator of competitive galaxy, or player has no rights to finish galaxy at all. """ if client.db != None: player = client.getPlayer() galaxy = client.get(player.galaxy) # player can restart (finish) it's own singleplayer galaxy anytime if galaxy.scenario == Const.SCENARIO_SINGLE: # depends on state of galaxy if not galaxy.timeEnabled: self.systemMenu.items[7].text = _("Resume galaxy") else: self.systemMenu.items[7].text = _("Pause galaxy") self.systemMenu.items[7].action = "onToggleTime" self.systemMenu.items[6].enabled = True self.systemMenu.items[7].enabled = True elif galaxy.scenario == Const.SCENARIO_OUTERSPACE: # standard behavior if player.imperator > 2: # player is imperator for more than two weeks - has right to finish galaxy self.systemMenu.items[6].enabled = True else: # no right to finish galaxy self.systemMenu.items[6].enabled = False # you cannot resign when time is stopped if galaxy.timeEnabled: self.systemMenu.items[7].enabled = True else: self.systemMenu.items[7].enabled = False def galaxyFinishButton(self, widget, action, data): player = client.getPlayer() galaxy = client.get(player.galaxy) if galaxy.scenario == Const.SCENARIO_OUTERSPACE and player.imperator > 2: localTime = time.time() gdata.config.game.lastGalaxyFinishShown = str(localTime) self.galaxyFinishDlg.display(finishAction = self.onFinishConfirmedOuterspace) elif galaxy.scenario == Const.SCENARIO_SINGLE: self.confirmDlg.display(_('Are you really really sure you want to finish this single player galaxy of yours? You won\'t be able to get back.'), _('Finish'), _('No'), confirmAction = self.onFinishConfirmedSingle) def galaxyFinishPopup(self, widget, action, data): """ Pop up dialog to finish galaxy in case player is eligible imperator of competitive galaxy. Do this once per day. """ if client.db != None: player = client.getPlayer() galaxy = client.get(player.galaxy) if galaxy.scenario == Const.SCENARIO_OUTERSPACE and player.imperator > 2: lastGalaxyFinishShown = gdata.config.game.lastGalaxyFinishShown if lastGalaxyFinishShown != None: localTime = time.time() storedTime = float(lastGalaxyFinishShown) if localTime - storedTime > 60 * 60 * 24: gdata.config.game.lastGalaxyFinishShown = str(localTime) self.galaxyFinishDlg.display(finishAction = self.onFinishConfirmedOuterspace) else: gdata.config.game.lastGalaxyFinishShown = str(time.time()) self.galaxyFinishDlg.display(finishAction = self.onFinishConfirmedOuterspace) def updateMsgButton(self): if self.messagesDlg.newMsgs > 0: self.win.vMessages.foreground = gdata.sevColors[gdata.MAJ] else: self.win.vMessages.foreground = None def processKeyUp(self, evt): if evt.key == pygame.K_F12 and pygame.key.get_mods() & pygame.KMOD_CTRL: self.onExit(None, None, None) return ui.NoEvent def processKeyDown(self, evt): # Alt+M - Messages if evt.unicode == u'\x6D' and pygame.key.get_mods() & pygame.KMOD_ALT: self.messagesDlg.display() # Alt+R - Research elif evt.unicode == u'\x72' and pygame.key.get_mods() & pygame.KMOD_ALT: self.researchDlg.display() # Alt+D - Diplomacy elif evt.unicode == u'\x64' and pygame.key.get_mods() & pygame.KMOD_ALT: self.diplomacyDlg.display() # Alt+C - Constr elif evt.unicode == u'\x63' and pygame.key.get_mods() & pygame.KMOD_ALT: self.constructionDlg.display() # Alt+P - Planets elif evt.unicode == u'\x70' and pygame.key.get_mods() & pygame.KMOD_ALT: self.onPlanetsMenu(False,False,False) # use onPlanetsMenu rather than direct control # Alt+F - Fleets elif evt.unicode == u'\x66' and pygame.key.get_mods() & pygame.KMOD_ALT: self.onFleetsMenu(False,False,False) # use onFleetsMenu rather than direct control # Alt+O - Overview elif evt.unicode == u'\x6F' and pygame.key.get_mods() & pygame.KMOD_ALT: self.empireOverviewDlg.display() # Alt+B - Pro'b'lems elif evt.unicode == u'\x62' and pygame.key.get_mods() & pygame.KMOD_ALT: self.problemsDlg.display() # Alt+N - Me'n'u elif evt.unicode == u'\x6E' and pygame.key.get_mods() & pygame.KMOD_ALT: self.onMenu(False,False,False) # use onMenu rather than direct control def createUI(self): w, h = gdata.scrnSize lw, lh = w / 20, h / 20 self.win = ui.Window(self.app, modal = 1, decorated = 0, alwaysInBackground = 1, movable = 0, rect = ui.Rect(0, 0, w, h), layoutManager = ui.SimpleGridLM(), ) self.win.subscribeAction('*', self) # map self.mapWidget = StarMapWidget(self.win, id = 'vStarMap', action = 'onSelectMapObj', layout = (0, 1, lw, lh - 2) ) self.searchDlg.mapWidget = self.mapWidget self.win.callEventHandler = self.mapWidget self.mapWidget.callEventHandler = self # bottom ui.Label(self.win, id = 'vStatus', align = ui.ALIGN_W, layout = (0, lh - 1, lw - 16, 1), ) ui.Label(self.win, id = 'vTurn', align = ui.ALIGN_E, text = '????.??', font = 'normal-bold', layout = (lw - 4, lh - 1, 4, 1), ) # top ui.Button(self.win, layout = (0, 0, 4, 1), text = _('Messages'), action = 'onMessages', id = "vMessages") ui.Button(self.win, layout = (4, 0, 4, 1), text = _('Research'), action = 'onResearch') ui.Button(self.win, layout = (8, 0, 4, 1), text = _('Diplomacy'), id = "vDiplomacy", action = 'onDiplomacy', enabled = 0) ui.Button(self.win, layout = (12, 0, 4, 1), text = _('Constr'), id = "vConstruction", action = 'onConstruction', enabled = 0) ui.Button(self.win, layout = (16, 0, 4, 1), text = _('Planets'), id = "vPlanetsMenu", action = 'onPlanetsMenu', enabled = 1) ui.Button(self.win, layout = (20, 0, 4, 1), text = _('Fleets'), id = "vFleetsMenu", action = 'onFleetsMenu', enabled = 1) ui.Button(self.win, layout = (24, 0, 4, 1), text = _('Overview'), id = "vOverview", action = 'onOverview', enabled = 1) ui.Title(self.win, layout = (28, 0, lw - 37, 1)) ui.Button(self.win, layout = (lw - 9, 0, 4, 1), text = _('Problems'), action = 'onProblems') ui.Button(self.win, layout = (lw - 5, 0, 5, 1), text = _('Menu'), action = 'onMenu') self.app.statusBar = self.win.vStatus self.app.setStatus(_('Ready.')) # system menu self.systemMenu = ui.Menu(self.app, title = _("Menu"), width = 5, items = [ ui.Item(_("Find system"), action = "onSearch", hotkey = u'\x66'), # F ui.Item(_("Statistics"), action = "onStats", hotkey = u'\x73'), # S ui.Item(_("Save View"), action = "onSaveView", hotkey = u'\x76'), # V ui.Item(_("Save Starmap"), action = "onSaveStarmap"), ui.Item(_("Options"), action = "onOptions", hotkey = u'\x6F'), # O ui.Item(_("--------"), enabled = False), ui.Item(_("Finish galaxy"), action = "galaxyFinishButton", enabled = False, data = True), # no hotkey; if this position moved, you need to update finishGalaxy's "self.systemMenu.items" lines to reference new index position ui.Item(_("Resign"), action = "onResign"), # no hotkey ui.Item(_("--------"), enabled = False), ui.Item(_("Exit"), action = "onExit", hotkey = u'\x71'), # Q (also directly CTRL+F12) ] ) self.systemMenu.subscribeAction("*", self) self.systemFleetMenu = ui.Menu(self.app, title = _("Fleets"), width = 4, items = [ ui.Item(_("Fleet List"), action = "onFleets", hotkey = u'\x66'), # F ui.Item(_("Analysis"), action = "onFleetAnalysis", hotkey = u'\x61'), # A ] ) self.systemFleetMenu.subscribeAction("*", self) self.systemPlanetMenu = ui.Menu(self.app, title = _("Planets"), width = 5, items = [ ui.Item(_("Planet List"), action = "onPlanets", hotkey = u'\x70'), # P ui.Item(_("System List"), action = "onSystems", hotkey = u'\x73'), # S ui.Item(_("Global queues"), action = "onGlobalQueues"), ui.Item(_("Analysis"), action = "onPlanetAnalysis", hotkey = u'\x61'), #A ] ) self.systemPlanetMenu.subscribeAction("*", self)