osci.dialog.MainGameDlg.MainGameDlg.__init__()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 23
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 23
nop 2
dl 0
loc 23
rs 9.328
c 0
b 0
f 0
1
#
2
#  Copyright 2001 - 2016 Ludek Smid [http://www.ospace.net/]
3
#
4
#  This file is part of Outer Space.
5
#
6
#  Outer Space is free software; you can redistribute it and/or modify
7
#  it under the terms of the GNU General Public License as published by
8
#  the Free Software Foundation; either version 2 of the License, or
9
#  (at your option) any later version.
10
#
11
#  Outer Space is distributed in the hope that it will be useful,
12
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
13
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
#  GNU General Public License for more details.
15
#
16
#  You should have received a copy of the GNU General Public License
17
#  along with Outer Space; if not, write to the Free Software
18
#  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19
#
20
21
import pygameui as ui
22
from osci import gdata, client, res
23
from osci.StarMapWidget import StarMapWidget
24
from StarSystemDlg import StarSystemDlg
25
from FleetDlg import FleetDlg
26
from ResearchDlg import ResearchDlg
27
from MessagesDlg import MessagesDlg
28
from ConstructionDlg import ConstructionDlg
29
from PlanetsOverviewDlg import PlanetsOverviewDlg
30
from SystemOverviewDlg import SystemOverviewDlg
31
from GlobalQueuesDlg import GlobalQueuesDlg
32
from FleetsOverviewDlg import FleetsOverviewDlg
33
from PlanetsAnalysisDlg import PlanetsAnalysisDlg
34
from FleetsAnalysisDlg import FleetsAnalysisDlg
35
from GalaxyFinishDlg import GalaxyFinishDlg
36
from ConfirmDlg import ConfirmDlg
37
from OptionsDlg import OptionsDlg
38
from SearchDlg import SearchDlg
39
import ProblemsDlg
40
import DiplomacyDlg
41
import EmpireOverviewDlg
42
import ige.ospace.Const as Const
43
from ige import log
44
import resources
45
import webbrowser, pygame
46
import time
47
import os.path
48
import Utils
49
50
class MainGameDlg:
51
52
    def __init__(self, app):
53
        self.app = app
54
        self.starSystemDlg = StarSystemDlg(self.app)
55
        self.fleetDlg = FleetDlg(self.app)
56
        self.researchDlg = ResearchDlg(self.app)
57
        self.confirmDlg = ConfirmDlg(self.app)
58
        self.diplomacyDlg = DiplomacyDlg.DiplomacyDlg(self.app)
59
        self.constructionDlg = ConstructionDlg(self.app)
60
        self.messagesDlg = MessagesDlg(self.app)
61
        self.planetsOverviewDlg = PlanetsOverviewDlg(self.app)
62
        self.globalQueuesDlg = GlobalQueuesDlg(self.app)
63
        self.systemOverviewDlg = SystemOverviewDlg(self.app)
64
        self.fleetsOverviewDlg = FleetsOverviewDlg(self.app)
65
        self.optionsDlg = OptionsDlg(self.app)
66
        self.searchDlg = SearchDlg(self.app)
67
        self.problemsDlg = ProblemsDlg.ProblemsDlg(self.app)
68
        self.empireOverviewDlg = EmpireOverviewDlg.EmpireOverviewDlg(self.app)
69
        self.galaxyFinishDlg = GalaxyFinishDlg(self.app)
70
        self.planetsAnalysisDlg = PlanetsAnalysisDlg(app)
71
        self.fleetsAnalysisDlg = FleetsAnalysisDlg(app)
72
        self.mapWidget = None
73
        self.createUI()
74
        self.centered = 0
75
76
    def display(self):
77
        self.app.showBackground = False
78
        gdata.mainGameDlg = self
79
        self.win.show()
80
        # register for updates
81
        gdata.updateDlgs.append(self)
82
        #self.refocus()
83
84
    def refocus(self):
85
        #log.debug("refocusing")
86
        self.app.setFocus(self.mapWidget)
87
88
    def onCmdInProgress(self, inProgress):
89
        if inProgress:
90
            self.win.vTurn.background = (0xff, 0xff, 0x00)
91
        else:
92
            self.win.vTurn.background = None
93
94
    def hide(self):
95
        self.app.showBackground = True
96
        self.win.hide()
97
        gdata.mainGameDlg = None
98
        # unregister updates
99
        if self in gdata.updateDlgs:
100
            gdata.updateDlgs.remove(self)
101
102
    def onExit(self, widget, action, data):
103
        self.app.setStatus(_('Exitting a session...'))
104
        self.hide()
105
        self.app.exitLocal()
106
107
    def onSelectMapObj(self, widget, action, data):
108
        self.win.vStarMap.highlightPos = None
109
        obj = client.get(data, noUpdate = 1)
110
        if obj == None:
111
            self.app.setStatus(_('Cannot select object on map'))
112
            return
113
        if obj.type in (Const.T_PLANET, Const.T_SYSTEM, Const.T_WORMHOLE):
114
            self.starSystemDlg.onSelectMapObj(None, None, data)
115
        elif obj.type == Const.T_FLEET:
116
            self.fleetDlg.display(data)
117
118
    def onResearch(self, widget, action, data):
119
        self.researchDlg.display()
120
121
    def onDiplomacy(self, widget, action, data):
122
        self.diplomacyDlg.display()
123
124
    def onMessages(self, widget, action, data):
125
        self.messagesDlg.display()
126
127
    def onConstruction(self, widget, action, data):
128
        self.constructionDlg.display()
129
130
    def onPlanetsMenu(self, widget, action, data):
131
        self.systemPlanetMenu.show((16*20, 0))
132
133
    def onPlanets(self, widget, action, data):
134
        self.planetsOverviewDlg.display()
135
136
    def onSystems(self, widget, action, data):
137
        self.systemOverviewDlg.display()
138
139
    def onPlanetAnalysis(self, widget, action, data):
140
        self.planetsAnalysisDlg.display()
141
142
    def onGlobalQueues(self, widget, action, data):
143
        self.globalQueuesDlg.display()
144
145
    def onFleetsMenu(self, widget, action, data):
146
        self.systemFleetMenu.show((20*20, 0))
147
148
    def onFleets(self, widget, action, data):
149
        self.fleetsOverviewDlg.display()
150
151
    def onFleetAnalysis(self, widget, action, data):
152
        self.fleetsAnalysisDlg.display()
153
154
    def onOptions(self, widget, action, data):
155
        self.optionsDlg.display()
156
157
    def onProblems(self, widget, action, data):
158
        self.problemsDlg.display()
159
160
    def onOverview(self, widget, action, data):
161
        self.empireOverviewDlg.display()
162
163
    def onSearch(self, widget, action, data):
164
        self.searchDlg.display()
165
166
    def onStats(self, widget, action, data):
167
        url = 'http://%s/%s/galaxy%d.html' % (
168
            gdata.config.game.server,
169
            gdata.config.game.lastgameid,
170
            client.getPlayer().galaxy,
171
        )
172
        webbrowser.open(url, new = 1)
173
174
    def onResign(self, widget, action, data):
175
        # swap yes and no
176
        self.confirmDlg.display(_('Are you sure to resign current game?'), _('No'),
177
            _('Yes'), cancelAction = self.onResignConfirmed)
178
179
    def onSaveView(self, widget, action, data):
180
        self.confirmDlg.display(_('Save the current starmap view as an image?'), _('Yes'),
181
            _('No'), confirmAction = self.onSaveViewConfirm)
182
183
    def onSaveViewConfirm(self):
184
        turn = client.getTurn()
185
        name = 'view_' + res.formatTime(turn,'_')
186
        full_name = os.path.join(gdata.config.game.screenshot_dir, name)
187
        savedas = self.mapWidget.save(full_name, chronicle_shot=False)
188
        self.confirmDlg.display(_('File saved as %s' % savedas), _('OK'), False)
189
190
    def onSaveStarmap(self, widget, action, data):
191
        self.confirmDlg.display(_('Save whole galaxy starmap as an image?'), _('Yes'),
192
            _('No'), confirmAction = self.onSaveStarmapConfirm)
193
194
    def onSaveStarmapConfirm(self):
195
        turn = client.getTurn()
196
        name = 'starmap_' + res.formatTime(turn,'_')
197
        full_name = os.path.join(gdata.config.game.screenshot_dir, name)
198
        savedas = self.mapWidget.save(full_name, chronicle_shot=True)
199
        self.confirmDlg.display(_('File saved as %s' % savedas), _('OK'), False)
200
201
    def onMenu(self, widget, action, data):
202
        w, h = gdata.scrnSize
203
        self.systemMenu.show((w - self.systemMenu.width * 20 - 4, 0))
204
205
    def onResignConfirmed(self):
206
        client.cmdProxy.resign(client.getPlayerID())
207
        client.db.clear()
208
        self.app.exitLocal()
209
210
    def onToggleTime(self, widget, action, data):
211
        galaxyID = client.getPlayer().galaxy
212
        galaxy = client.get(galaxyID)
213
        galaxy.timeEnabled = client.cmdProxy.toggleTime(galaxyID)
214
        self.alterMenu(None, None, False)
215
216
    def onFinishConfirmedSingle(self):
217
        self.onFinishConfirmed(None, Const.SCENARIO_SINGLE)
218
219
    def onFinishConfirmedOuterspace(self, imperatorMsg):
220
        self.onFinishConfirmed(imperatorMsg, Const.SCENARIO_OUTERSPACE)
221
222
    def onFinishConfirmed(self, imperatorMsg, scenario):
223
        self.win.setStatus(_('Galaxy finish in progress...'))
224
        oldMsgHandler = client.cmdProxy.msgHandler
225
        client.cmdProxy.msgHandler = None
226
        client.cmdProxy.keepAliveTime = 60 * 60 # do not try to connect to server (one hour)
227
        if scenario == Const.SCENARIO_SINGLE:
228
            client.cmdProxy.deleteSingle(client.getPlayer().galaxy)
229
        elif scenario == Const.SCENARIO_OUTERSPACE:
230
            client.cmdProxy.finishGalaxyImperator(Const.OID_UNIVERSE, client.getPlayer().galaxy, imperatorMsg)
231
        else:
232
            return
233
        client.db.clear()
234
        client.cmdProxy.msgHandler = oldMsgHandler
235
        self.hide()
236
        self.app.exitLocal()
237
238
    def update(self,configUpdated=False):
239
        self.galaxyFinishPopup(None, None, False)
240
        self.alterMenu(None, None, False)
241
        player = client.getPlayer()
242
        turn = client.getTurn()
243
        self.win.vTurn.text = res.formatTime(turn)
244
        if configUpdated:
245
            self.win.vStarMap.updateConfigModes()
246
        self.win.vStarMap.precompute()
247
        # center of 1st player star
248
        if not self.centered:
249
            player = client.getPlayer()
250
            if player.planets:
251
                planet = client.get(player.planets[0])
252
                self.win.vStarMap.setPos(planet.x, planet.y)
253
            elif player.fleets:
254
                fleet = client.get(player.fleets[0])
255
                self.win.vStarMap.setPos(fleet.x, fleet.y)
256
            self.centered = 1
257
            self.refocus() #only fire off when dialog first updated
258
        # enable/disable construction
259
        self.win.vConstruction.enabled = Utils.enableConstruction(client)
260
        # enable/disable diplomacy
261
        #if player.diplomacyRels:
262
        self.win.vDiplomacy.enabled = 1
263
        #else:
264
        #    self.win.vDiplomacy.enabled = 0
265
        # highlight messages button?
266
        self.messagesDlg.update()
267
        if self.messagesDlg.newMsgs > 0:
268
            self.win.vMessages.foreground = gdata.sevColors[gdata.MAJ]
269
        else:
270
            self.win.vMessages.foreground = None
271
272
273
    def alterMenu(self, widget, action, data):
274
        """ Update menu according to current situation, being different in singleplayer
275
        or when player is imperator of competitive galaxy, or player has no rights to
276
        finish galaxy at all.
277
        """
278
        if client.db != None:
279
            player = client.getPlayer()
280
            galaxy = client.get(player.galaxy)
281
            # player can restart (finish) it's own singleplayer galaxy anytime
282
            if galaxy.scenario == Const.SCENARIO_SINGLE:
283
                # depends on state of galaxy
284
                if not galaxy.timeEnabled:
285
                    self.systemMenu.items[7].text = _("Resume galaxy")
286
                else:
287
                    self.systemMenu.items[7].text = _("Pause galaxy")
288
                self.systemMenu.items[7].action = "onToggleTime"
289
                self.systemMenu.items[6].enabled = True
290
                self.systemMenu.items[7].enabled = True
291
292
            elif galaxy.scenario == Const.SCENARIO_OUTERSPACE:
293
                # standard behavior
294
                if player.imperator > 2:
295
                    # player is imperator for more than two weeks - has right to finish galaxy
296
                    self.systemMenu.items[6].enabled = True
297
                else:
298
                    # no right to finish galaxy
299
                    self.systemMenu.items[6].enabled = False
300
                # you cannot resign when time is stopped
301
                if galaxy.timeEnabled:
302
                    self.systemMenu.items[7].enabled = True
303
                else:
304
                    self.systemMenu.items[7].enabled = False
305
306
307
    def galaxyFinishButton(self, widget, action, data):
308
        player = client.getPlayer()
309
        galaxy = client.get(player.galaxy)
310
        if galaxy.scenario == Const.SCENARIO_OUTERSPACE and player.imperator > 2:
311
            localTime = time.time()
312
            gdata.config.game.lastGalaxyFinishShown = str(localTime)
313
            self.galaxyFinishDlg.display(finishAction = self.onFinishConfirmedOuterspace)
314
        elif galaxy.scenario == Const.SCENARIO_SINGLE:
315
            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)
316
317
318
    def galaxyFinishPopup(self, widget, action, data):
319
        """ Pop up dialog to finish galaxy in case player is eligible imperator of competitive
320
        galaxy. Do this once per day.
321
        """
322
        if client.db != None:
323
            player = client.getPlayer()
324
            galaxy = client.get(player.galaxy)
325
            if galaxy.scenario == Const.SCENARIO_OUTERSPACE and player.imperator > 2:
326
                lastGalaxyFinishShown = gdata.config.game.lastGalaxyFinishShown
327
                if lastGalaxyFinishShown != None:
328
                    localTime = time.time()
329
                    storedTime = float(lastGalaxyFinishShown)
330
                    if localTime - storedTime > 60 * 60 * 24:
331
                        gdata.config.game.lastGalaxyFinishShown = str(localTime)
332
                        self.galaxyFinishDlg.display(finishAction = self.onFinishConfirmedOuterspace)
333
                else:
334
                    gdata.config.game.lastGalaxyFinishShown = str(time.time())
335
                    self.galaxyFinishDlg.display(finishAction = self.onFinishConfirmedOuterspace)
336
337
    def updateMsgButton(self):
338
        if self.messagesDlg.newMsgs > 0:
339
            self.win.vMessages.foreground = gdata.sevColors[gdata.MAJ]
340
        else:
341
            self.win.vMessages.foreground = None
342
343
    def processKeyUp(self, evt):
344
        if evt.key == pygame.K_F12 and pygame.key.get_mods() & pygame.KMOD_CTRL:
345
            self.onExit(None, None, None)
346
        return ui.NoEvent
347
348
349
    def processKeyDown(self, evt):
350
        # Alt+M - Messages
351
        if evt.unicode == u'\x6D' and pygame.key.get_mods() & pygame.KMOD_ALT:
352
            self.messagesDlg.display()
353
        # Alt+R - Research
354
        elif evt.unicode == u'\x72' and pygame.key.get_mods() & pygame.KMOD_ALT:
355
            self.researchDlg.display()
356
        # Alt+D - Diplomacy
357
        elif evt.unicode == u'\x64' and pygame.key.get_mods() & pygame.KMOD_ALT:
358
            self.diplomacyDlg.display()
359
        # Alt+C - Constr
360
        elif evt.unicode == u'\x63' and pygame.key.get_mods() & pygame.KMOD_ALT:
361
            self.constructionDlg.display()
362
        # Alt+P - Planets
363
        elif evt.unicode == u'\x70' and pygame.key.get_mods() & pygame.KMOD_ALT:
364
            self.onPlanetsMenu(False,False,False) # use onPlanetsMenu rather than direct control
365
        # Alt+F - Fleets
366
        elif evt.unicode == u'\x66' and pygame.key.get_mods() & pygame.KMOD_ALT:
367
            self.onFleetsMenu(False,False,False) # use onFleetsMenu rather than direct control
368
        # Alt+O - Overview
369
        elif evt.unicode == u'\x6F' and pygame.key.get_mods() & pygame.KMOD_ALT:
370
            self.empireOverviewDlg.display()
371
        # Alt+B - Pro'b'lems
372
        elif evt.unicode == u'\x62' and pygame.key.get_mods() & pygame.KMOD_ALT:
373
            self.problemsDlg.display()
374
        # Alt+N - Me'n'u
375
        elif evt.unicode == u'\x6E' and pygame.key.get_mods() & pygame.KMOD_ALT:
376
            self.onMenu(False,False,False) # use onMenu rather than direct control
377
378
    def createUI(self):
379
        w, h = gdata.scrnSize
380
        lw, lh = w / 20, h / 20
381
        self.win = ui.Window(self.app,
382
            modal = 1,
383
            decorated = 0,
384
            alwaysInBackground = 1,
385
            movable = 0,
386
            rect = ui.Rect(0, 0, w, h),
387
            layoutManager = ui.SimpleGridLM(),
388
        )
389
        self.win.subscribeAction('*', self)
390
        # map
391
        self.mapWidget = StarMapWidget(self.win,
392
            id = 'vStarMap',
393
            action = 'onSelectMapObj',
394
            layout = (0, 1, lw, lh - 2)
395
        )
396
        self.searchDlg.mapWidget = self.mapWidget
397
        self.win.callEventHandler = self.mapWidget
398
        self.mapWidget.callEventHandler = self
399
        # bottom
400
        ui.Label(self.win,
401
            id = 'vStatus',
402
            align = ui.ALIGN_W,
403
            layout = (0, lh - 1, lw - 16, 1),
404
        )
405
        ui.Label(self.win,
406
            id = 'vTurn',
407
            align = ui.ALIGN_E,
408
            text = '????.??',
409
            font = 'normal-bold',
410
            layout = (lw - 4, lh - 1, 4, 1),
411
        )
412
        # top
413
        ui.Button(self.win, layout = (0, 0, 4, 1), text = _('Messages'),
414
            action = 'onMessages', id = "vMessages")
415
        ui.Button(self.win, layout = (4, 0, 4, 1), text = _('Research'),
416
            action = 'onResearch')
417
        ui.Button(self.win, layout = (8, 0, 4, 1), text = _('Diplomacy'),
418
            id = "vDiplomacy", action = 'onDiplomacy', enabled = 0)
419
        ui.Button(self.win, layout = (12, 0, 4, 1), text = _('Constr'),
420
            id = "vConstruction", action = 'onConstruction', enabled = 0)
421
        ui.Button(self.win, layout = (16, 0, 4, 1), text = _('Planets'),
422
            id = "vPlanetsMenu", action = 'onPlanetsMenu', enabled = 1)
423
        ui.Button(self.win, layout = (20, 0, 4, 1), text = _('Fleets'),
424
            id = "vFleetsMenu", action = 'onFleetsMenu', enabled = 1)
425
        ui.Button(self.win, layout = (24, 0, 4, 1), text = _('Overview'),
426
            id = "vOverview", action = 'onOverview', enabled = 1)
427
        ui.Title(self.win, layout = (28, 0, lw - 37, 1))
428
        ui.Button(self.win, layout = (lw - 9, 0, 4, 1), text = _('Problems'),
429
            action = 'onProblems')
430
        ui.Button(self.win, layout = (lw - 5, 0, 5, 1), text = _('Menu'),
431
            action = 'onMenu')
432
        self.app.statusBar = self.win.vStatus
433
        self.app.setStatus(_('Ready.'))
434
        # system menu
435
        self.systemMenu = ui.Menu(self.app, title = _("Menu"),
436
            width = 5,
437
            items = [
438
                ui.Item(_("Find system"), action = "onSearch", hotkey = u'\x66'), # F
439
                ui.Item(_("Statistics"), action = "onStats", hotkey = u'\x73'), # S
440
                ui.Item(_("Save View"), action = "onSaveView", hotkey = u'\x76'), # V
441
                ui.Item(_("Save Starmap"), action = "onSaveStarmap"),
442
                ui.Item(_("Options"), action = "onOptions", hotkey = u'\x6F'), # O
443
                ui.Item(_("--------"), enabled = False),
444
                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
445
                ui.Item(_("Resign"), action = "onResign"), # no hotkey
446
                ui.Item(_("--------"), enabled = False),
447
                ui.Item(_("Exit"), action = "onExit", hotkey = u'\x71'), # Q (also directly CTRL+F12)
448
            ]
449
        )
450
        self.systemMenu.subscribeAction("*", self)
451
        self.systemFleetMenu = ui.Menu(self.app, title = _("Fleets"),
452
            width = 4,
453
            items = [
454
                ui.Item(_("Fleet List"), action = "onFleets", hotkey = u'\x66'), # F
455
                ui.Item(_("Analysis"), action = "onFleetAnalysis", hotkey = u'\x61'), # A
456
            ]
457
        )
458
        self.systemFleetMenu.subscribeAction("*", self)
459
        self.systemPlanetMenu = ui.Menu(self.app, title = _("Planets"),
460
            width = 5,
461
            items = [
462
                ui.Item(_("Planet List"), action = "onPlanets", hotkey = u'\x70'), # P
463
                ui.Item(_("System List"), action = "onSystems", hotkey = u'\x73'), # S
464
                ui.Item(_("Global queues"), action = "onGlobalQueues"),
465
                ui.Item(_("Analysis"), action = "onPlanetAnalysis", hotkey = u'\x61'), #A
466
            ]
467
        )
468
        self.systemPlanetMenu.subscribeAction("*", self)
469