Passed
Pull Request — master (#291)
by Marek
01:40
created

FleetsOverviewDlg._populateLocation()   A

Complexity

Conditions 4

Size

Total Lines 9
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 9
nop 3
dl 0
loc 9
rs 9.95
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.StarMapWidget import StarMapWidget
23
from osci import gdata, res, client
24
import ige.ospace.Const as Const
25
from ige.ospace import Rules
26
import math
27
28
class FleetsOverviewDlg:
29
30
    def __init__(self, app):
31
        self.app = app
32
        self.createUI()
33
34
    def display(self):
35
        if gdata.config.defaults.showredirects != None:
36
            val = gdata.config.defaults.showredirects
37
            self.win.vRedirects.checked = val == 'yes'
38
39
        self.show()
40
        self.win.show()
41
        # register for updates
42
        if self not in gdata.updateDlgs:
43
            gdata.updateDlgs.append(self)
44
45
    def hide(self):
46
        self.win.setStatus(_("Ready."))
47
        self.win.hide()
48
        # unregister updates
49
        if self in gdata.updateDlgs:
50
            gdata.updateDlgs.remove(self)
51
52
    def update(self):
53
        self.show()
54
55
    def _analyzeRelations(self, playerID, fleet):
56
        # this evaluates color, and if it should be shown at all
57
        # get check box selections
58
        mine = self.win.vMine.checked
59
        enemy = self.win.vEnemy.checked
60
        unfriendly = self.win.vUnfriendy.checked
61
        neutral = self.win.vNeutral.checked
62
        friendly = self.win.vFriendly.checked
63
        allied = self.win.vAllied.checked
64
        redirects = self.win.vRedirects.checked
65
66
        # check fleet color and decide if display the fleet
67
        if hasattr(fleet, 'owner'):
68
            plRelation = client.getRelationTo(fleet.owner)
69
            fgColor = res.getPlayerColor(fleet.owner)
70
            ok = 0
71
            if mine and fleet.owner == playerID:
72
                ok = 1
73
            elif enemy and plRelation >= Const.REL_ENEMY_LO and plRelation < Const.REL_ENEMY_HI:
74
                ok = 1
75
            elif unfriendly and plRelation >= Const.REL_UNFRIENDLY_LO and plRelation < Const.REL_UNFRIENDLY_HI:
76
                ok = 1
77
            elif neutral and plRelation >= Const.REL_NEUTRAL_LO and plRelation < Const.REL_NEUTRAL_HI:
78
                ok = 1
79
            elif friendly and plRelation >= Const.REL_FRIENDLY_LO and plRelation < Const.REL_FRIENDLY_HI:
80
                ok = 1
81
            elif allied and plRelation >= Const.REL_ALLY_LO and plRelation < Const.REL_ALLY_HI:
82
                ok = 1
83
84
            if not ok:
85
                return None
86
        else:
87
            if not enemy:
88
                return None
89
            # with no owner assume enemy
90
            fgColor = res.getFFColorCode(0) #enemy
91
        return fgColor
92
93
    def _populateName(self, fleet):
94
        return fleet.customname if hasattr(fleet,'customname') and fleet.customname else \
95
               getattr(fleet, 'name', res.getUnknownName())
96
97
    def _populatePopup(self, playerID, fleet):
98
        if hasattr(fleet, 'owner') and playerID != fleet.owner:
99
            owner = getattr(client.get(fleet.owner, noUpdate = 1), "name", res.getUnknownName())
100
            ownerName = " (%s)" % owner
101
            ownerNameTip = owner
102
            ownerTipTitle = _("Owner")
103
        else:
104
            ownerName = ""
105
            ownerNameTip = ""
106
            ownerTipTitle = ""
107
        return ownerName, ownerNameTip, ownerTipTitle
108
109
    def _populateLocation(self, playerID, fleet):
110
        systemName = "-"
111
        if hasattr(fleet, 'orbiting') and fleet.orbiting:
112
            system = client.get(fleet.orbiting, noUpdate = 1)
113
            systemName = getattr(system, "name", res.getUnknownName())
114
        elif hasattr(fleet, 'closeSystem'):
115
            system = client.get(fleet.closeSystem, noUpdate = 1)
116
            systemName = _("%s (dst)") % getattr(system, "name", res.getUnknownName())
117
        return systemName
118
119
    def _populateOrder(self, fleet):
120
        # get fleet current action and target of action
121
        order = "-"
122
        targetName = "-"
123
        if hasattr(fleet, 'actions') and fleet.actionIndex < len(fleet.actions):
124
            action, target, data  = fleet.actions[fleet.actionIndex]
125
            if action == Const.FLACTION_REDIRECT and not self.win.vRedirects.checked:
126
                # ok, not interested then
127
                return None
128
            order = gdata.fleetActions[action]
129
            if target != Const.OID_NONE:
130
                targetName = getattr(client.get(target, noUpdate = 1), 'name', res.getUnknownName())
131
                order = "%s %s" % (order, targetName)
132
        return order
133
134
    def _populateEta(self, fleet):
135
        return res.formatTime(fleet.eta) if hasattr(fleet, "eta") else "?"
136
137
    def _populateFuel(self, fleet):
138
        if hasattr(fleet, "storEn"):
139
            fuel = 100 * fleet.storEn / fleet.maxEn if fleet.maxEn > 0 else 0
140
        else:
141
            fuel = "?"
142
        return fuel
143
144
    def _populateOpTime(self, fleet):
145
        if hasattr(fleet, 'storEn') and hasattr(fleet, 'operEn'):
146
            turns = fleet.storEn / fleet.operEn if fleet.operEn > 0 else 100000
147
            rawRange = turns * fleet.speed / Rules.turnsPerDay
148
            _range = "%.2f" % rawRange
149
            opTime = res.formatTime(turns)
150
        else:
151
            rawRange = 0
152
            _range = "?"
153
            opTime = "?"
154
        return opTime, _range, rawRange
155
156
    def _populateLastUpgrade(self, fleet):
157
        return res.formatTime(fleet.lastUpgrade) if hasattr(fleet, "lastUpgrade") else "?"
158
159
    def show(self):
160
        player = client.getPlayer()
161
        items = []
162
        for fleetID in client.db.keys():
163
            fleet = client.get(fleetID, noUpdate = 1)
164
            # skip non-fleets
165
            if not hasattr(fleet, "type") or fleet.type != Const.T_FLEET:
166
                continue
167
168
            fgColor = self._analyzeRelations(player.oid, fleet)
169
            if fgColor is None:
170
                # nothing to show
171
                continue
172
173
            order = self._populateOrder(fleet)
174
            if order is None:
175
                # nothing to show - redirect, which is not ticked
176
                continue
177
178
            ownerName, ownerNameTip, ownerTipTitle = self._populatePopup(player.oid, fleet)
179
            opTime, _range, rawRange = self._populateOpTime(fleet)
180
181
            # create ListBox Item for fleet
182
            item = ui.Item(
183
                "%s %s" % (self._populateName(fleet), ownerName),
184
                tooltipTitle = ownerTipTitle,
185
                tooltip = ownerNameTip,
186
                tLocation = self._populateLocation(player.oid,fleet),
187
                tOrder = self._populateOrder(fleet),
188
                tMP = getattr(fleet, "combatPwr", "?"),
189
                tETA = self._populateEta(fleet),
190
                tETA_raw = getattr(fleet, "eta", 0),
191
                tSignature = getattr(fleet, "signature", "?"),
192
                tFuel = self._populateFuel(fleet),
193
                tOpTime = opTime,
194
                tRange = _range,
195
                tRange_raw = rawRange,
196
                tLastUpgrade = self._populateLastUpgrade(fleet),
197
                tFleetID = fleetID,
198
                foreground = fgColor)
199
            items.append(item)
200
201
        self.win.vFleets.items = items
202
        self.win.vFleets.itemsChanged()
203
204
    def onSelectFleet(self, widget, action, data):
205
        item = self.win.vFleets.selection[0]
206
        fleet = client.get(item.tFleetID, noUpdate = 1)
207
        if hasattr(fleet, "owner") and fleet.owner == client.getPlayerID():
208
            # show dialog
209
            gdata.mainGameDlg.onSelectMapObj(None, None, item.tFleetID)
210
        else:
211
            # center fleet on map
212
            if hasattr(fleet, "x"):
213
                gdata.mainGameDlg.win.vStarMap.highlightPos = (fleet.x, fleet.y)
214
                gdata.mainGameDlg.win.vStarMap.setPos(fleet.x, fleet.y)
215
                self.hide()
216
                return
217
            self.win.setStatus(_("Cannot show location"))
218
219
    def onShowLocation(self, widget, action, data):
220
        item = self.win.vFleets.selection[0]
221
        fleet = client.get(item.tFleetID, noUpdate = 1)
222
        # center on map
223
        if hasattr(fleet, "x"):
224
            gdata.mainGameDlg.win.vStarMap.highlightPos = (fleet.x, fleet.y)
225
            gdata.mainGameDlg.win.vStarMap.setPos(fleet.x, fleet.y)
226
            self.hide()
227
            return
228
        self.win.setStatus(_("Cannot show location"))
229
230
    def onToggleCondition(self, widget, action, data):
231
        self.update()
232
233
    def onClose(self, widget, action, data):
234
        self.hide()
235
236
    def createUI(self):
237
        w, h = gdata.scrnSize
238
        self.win = ui.Window(self.app,
239
            modal = 1,
240
            escKeyClose = 1,
241
            titleOnly = w == 800 and h == 600,
242
            movable = 0,
243
            title = _('Fleets Overview'),
244
            rect = ui.Rect((w - 800 - 4 * (w != 800)) / 2, (h - 600 - 4 * (h != 600)) / 2, 800 + 4 * (w != 800), 580 + 4 * (h != 600)),
245
            layoutManager = ui.SimpleGridLM(),
246
        )
247
        self.win.subscribeAction('*', self)
248
        # playets listbox
249
        ui.Listbox(self.win, layout = (0, 0, 40, 26), id = 'vFleets',
250
            columns = [
251
                (_('Fleet'), 'text', 5, ui.ALIGN_W),
252
                (_('Location'), 'tLocation', 6.5, ui.ALIGN_W),
253
                (_('Current order'), 'tOrder', 7, ui.ALIGN_W),
254
                (_('ETA'), 'tETA', 3, ui.ALIGN_E),
255
                (_('Fuel %'), 'tFuel', 3, ui.ALIGN_E),
256
                (_('Op. time'), 'tOpTime', 3, ui.ALIGN_E),
257
                (_('Range'), 'tRange', 3, ui.ALIGN_E),
258
                (_('MP'), 'tMP', 3, ui.ALIGN_E),
259
                (_('Sign'), 'tSignature', 2, ui.ALIGN_E),
260
                (_("Last upgr."), "tLastUpgrade", 3.5, ui.ALIGN_E),
261
            ],
262
            columnLabels = 1, action = 'onSelectFleet', rmbAction = "onShowLocation")
263
264
        ui.Check(self.win, layout = (0, 26, 5, 1), text = _('Mine'), id = "vMine",
265
            checked = 1, action = "onToggleCondition")
266
        ui.Check(self.win, layout = (5, 26, 5, 1), text = _('Enemy'), id = "vEnemy",
267
            checked = 0, action = "onToggleCondition")
268
        ui.Check(self.win, layout = (10, 26, 5, 1), text = _('Unfriendly'), id = "vUnfriendy",
269
            checked = 0, action = "onToggleCondition")
270
        ui.Check(self.win, layout = (15, 26, 5, 1), text = _('Neutral'), id = "vNeutral",
271
            checked = 0, action = "onToggleCondition")
272
        ui.Check(self.win, layout = (20, 26, 5, 1), text = _('Friendly'), id = "vFriendly",
273
            checked = 0, action = "onToggleCondition")
274
        ui.Check(self.win, layout = (25, 26, 5, 1), text = _('Allied'), id = "vAllied",
275
            checked = 0, action = "onToggleCondition")
276
        ui.Check(self.win, layout = (34, 26, 6, 1), text = _('Show redirects'), id = "vRedirects",
277
            checked = 0, action = "onToggleCondition")
278
        # status bar + submit/cancel
279
        ui.TitleButton(self.win, layout = (35, 27, 5, 1), text = _('Close'), action = 'onClose')
280
        ui.Title(self.win, id = 'vStatusBar', layout = (0, 27, 35, 1), align = ui.ALIGN_W)
281
        #self.win.statusBar = self.win.vStatusBar
282