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

FleetsOverviewDlg._analyzeRelations()   F

Complexity

Conditions 21

Size

Total Lines 37
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 21
eloc 30
nop 3
dl 0
loc 37
rs 0
c 0
b 0
f 0

How to fix   Complexity   

Complexity

Complex classes like osci.dialog.FleetsOverviewDlg.FleetsOverviewDlg._analyzeRelations() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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 show(self):
94
        player = client.getPlayer()
95
        items = []
96
        for fleetID in client.db.keys():
97
            fleet = client.get(fleetID, noUpdate = 1)
98
            # skip non-fleets
99
            if not hasattr(fleet, "type") or fleet.type != Const.T_FLEET:
100
                continue
101
            fgColor = self._analyzeRelations(player.oid, fleet)
102
            if fgColor is None:
103
                # nothing to show
104
                continue
105
106
            if hasattr(fleet, 'owner') and player.oid != fleet.owner:
107
                owner = getattr(client.get(fleet.owner, noUpdate = 1), "name", res.getUnknownName())
108
                ownerName = " (%s)" % owner
109
                ownerNameTip = owner
110
                ownerTipTitle = _("Owner")
111
            else:
112
                ownerName = ""
113
                ownerNameTip = ""
114
                ownerTipTitle = ""
115
116
            # check position of fleet
117
            system = None
118
            systemName = "-"
119
            if hasattr(fleet, 'orbiting') and fleet.orbiting:
120
                system = client.get(fleet.orbiting, noUpdate = 1)
121
                systemName = getattr(system, "name", res.getUnknownName())
122
            elif hasattr(fleet, 'closeSystem'):
123
                system = client.get(fleet.closeSystem, noUpdate = 1)
124
                systemName = _("%s (dst)") % getattr(system, "name", res.getUnknownName())
125
126
            # get fleet current action and target of action
127
            order = "-"
128
            targetName = "-"
129
            if hasattr(fleet, 'actions') and fleet.actionIndex < len(fleet.actions):
130
                action, target, data  = fleet.actions[fleet.actionIndex]
131
                if action == Const.FLACTION_REDIRECT and not redirects:
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable redirects does not seem to be defined.
Loading history...
132
                    continue
133
                order = gdata.fleetActions[action]
134
                if target != Const.OID_NONE:
135
                    targetName = getattr(client.get(target, noUpdate = 1), 'name', res.getUnknownName())
136
                    order = "%s %s" % (order, targetName)
137
            # eta
138
            if hasattr(fleet, "eta"): eta = res.formatTime(fleet.eta)
139
            else: eta = "?"
140
141
            # fuel
142
            if hasattr(fleet, "storEn"):
143
                if fleet.maxEn > 0: fuel = 100 * fleet.storEn / fleet.maxEn
144
                else: fuel = 0
145
            else:
146
                fuel = "?"
147
148
            # operational time
149
            if hasattr(fleet, 'storEn') and hasattr(fleet, 'operEn'):
150
                turns = 100000
151
                if fleet.operEn > 0: turns = fleet.storEn / fleet.operEn
152
                rawRange = turns * fleet.speed / Rules.turnsPerDay
153
                range = "%.2f" % rawRange
154
                opTime = res.formatTime(turns)
155
            else:
156
                rawRange = 0
157
                range = "?"
158
                opTime = "?"
159
160
            # last upgrade
161
            if hasattr(fleet, "lastUpgrade"):
162
                lastUpgrade = res.formatTime(fleet.lastUpgrade)
163
            else:
164
                lastUpgrade = "?"
165
166
            if hasattr(fleet,'customname') and fleet.customname:
167
                fleetname = fleet.customname
168
            else:
169
                fleetname = getattr(fleet, 'name', res.getUnknownName())
170
171
            # create ListBox Item for fleet
172
            item = ui.Item(
173
                "%s %s" % (fleetname, ownerName),
174
                tooltipTitle = ownerTipTitle,
175
                tooltip = ownerNameTip,
176
                tLocation = systemName,
177
                tOrder = order,
178
                tMP = getattr(fleet, "combatPwr", "?"),
179
                tETA = eta,
180
                tETA_raw = getattr(fleet, "eta", 0),
181
                tSignature = getattr(fleet, "signature", "?"),
182
                tFuel = fuel,
183
                tOpTime = opTime,
184
                tRange = range,
185
                tRange_raw = rawRange,
186
                tLastUpgrade = lastUpgrade,
187
                tFleetID = fleetID,
188
                foreground = fgColor)
189
            items.append(item)
190
191
        self.win.vFleets.items = items
192
        self.win.vFleets.itemsChanged()
193
194
    def onSelectFleet(self, widget, action, data):
195
        item = self.win.vFleets.selection[0]
196
        fleet = client.get(item.tFleetID, noUpdate = 1)
197
        if hasattr(fleet, "owner") and fleet.owner == client.getPlayerID():
198
            # show dialog
199
            gdata.mainGameDlg.onSelectMapObj(None, None, item.tFleetID)
200
        else:
201
            # center fleet on map
202
            if hasattr(fleet, "x"):
203
                gdata.mainGameDlg.win.vStarMap.highlightPos = (fleet.x, fleet.y)
204
                gdata.mainGameDlg.win.vStarMap.setPos(fleet.x, fleet.y)
205
                self.hide()
206
                return
207
            self.win.setStatus(_("Cannot show location"))
208
209
    def onShowLocation(self, widget, action, data):
210
        item = self.win.vFleets.selection[0]
211
        fleet = client.get(item.tFleetID, noUpdate = 1)
212
        # center on map
213
        if hasattr(fleet, "x"):
214
            gdata.mainGameDlg.win.vStarMap.highlightPos = (fleet.x, fleet.y)
215
            gdata.mainGameDlg.win.vStarMap.setPos(fleet.x, fleet.y)
216
            self.hide()
217
            return
218
        self.win.setStatus(_("Cannot show location"))
219
220
    def onToggleCondition(self, widget, action, data):
221
        self.update()
222
223
    def onClose(self, widget, action, data):
224
        self.hide()
225
226
    def createUI(self):
227
        w, h = gdata.scrnSize
228
        self.win = ui.Window(self.app,
229
            modal = 1,
230
            escKeyClose = 1,
231
            titleOnly = w == 800 and h == 600,
232
            movable = 0,
233
            title = _('Fleets Overview'),
234
            rect = ui.Rect((w - 800 - 4 * (w != 800)) / 2, (h - 600 - 4 * (h != 600)) / 2, 800 + 4 * (w != 800), 580 + 4 * (h != 600)),
235
            layoutManager = ui.SimpleGridLM(),
236
        )
237
        self.win.subscribeAction('*', self)
238
        # playets listbox
239
        ui.Listbox(self.win, layout = (0, 0, 40, 26), id = 'vFleets',
240
            columns = [
241
                (_('Fleet'), 'text', 5, ui.ALIGN_W),
242
                (_('Location'), 'tLocation', 6.5, ui.ALIGN_W),
243
                (_('Current order'), 'tOrder', 7, ui.ALIGN_W),
244
                (_('ETA'), 'tETA', 3, ui.ALIGN_E),
245
                (_('Fuel %'), 'tFuel', 3, ui.ALIGN_E),
246
                (_('Op. time'), 'tOpTime', 3, ui.ALIGN_E),
247
                (_('Range'), 'tRange', 3, ui.ALIGN_E),
248
                (_('MP'), 'tMP', 3, ui.ALIGN_E),
249
                (_('Sign'), 'tSignature', 2, ui.ALIGN_E),
250
                (_("Last upgr."), "tLastUpgrade", 3.5, ui.ALIGN_E),
251
            ],
252
            columnLabels = 1, action = 'onSelectFleet', rmbAction = "onShowLocation")
253
254
        ui.Check(self.win, layout = (0, 26, 5, 1), text = _('Mine'), id = "vMine",
255
            checked = 1, action = "onToggleCondition")
256
        ui.Check(self.win, layout = (5, 26, 5, 1), text = _('Enemy'), id = "vEnemy",
257
            checked = 0, action = "onToggleCondition")
258
        ui.Check(self.win, layout = (10, 26, 5, 1), text = _('Unfriendly'), id = "vUnfriendy",
259
            checked = 0, action = "onToggleCondition")
260
        ui.Check(self.win, layout = (15, 26, 5, 1), text = _('Neutral'), id = "vNeutral",
261
            checked = 0, action = "onToggleCondition")
262
        ui.Check(self.win, layout = (20, 26, 5, 1), text = _('Friendly'), id = "vFriendly",
263
            checked = 0, action = "onToggleCondition")
264
        ui.Check(self.win, layout = (25, 26, 5, 1), text = _('Allied'), id = "vAllied",
265
            checked = 0, action = "onToggleCondition")
266
        ui.Check(self.win, layout = (34, 26, 6, 1), text = _('Show redirects'), id = "vRedirects",
267
            checked = 0, action = "onToggleCondition")
268
        # status bar + submit/cancel
269
        ui.TitleButton(self.win, layout = (35, 27, 5, 1), text = _('Close'), action = 'onClose')
270
        ui.Title(self.win, id = 'vStatusBar', layout = (0, 27, 35, 1), align = ui.ALIGN_W)
271
        #self.win.statusBar = self.win.vStatusBar
272