Passed
Pull Request — master (#291)
by Marek
02:20
created

FleetsOverviewDlg._populateEta()   A

Complexity

Conditions 2

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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