Completed
Pull Request — master (#188)
by Marek
01:58
created

ige.ospace.IGalaxy.IGalaxy._isEligibleEnableTime()   B

Complexity

Conditions 5

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 10
nop 3
dl 0
loc 13
rs 8.5454
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 os.path
22
import time
23
import copy
24
import random
25
26
from xml.dom.minidom import Node, parse
27
28
import ige
29
import IPlayer
30
import IAIPlayer
31
import IAIEDENPlayer
32
import IAIMutantPlayer
33
import IAIPiratePlayer
34
import IAIRenegadePlayer
35
import Rules
36
import Scanner
37
import Utils
38
39
from Const import *
40
from ige import log
41
from ige.IObject import IObject
42
from ige.IDataHolder import IDataHolder
43
from ige.IObject import public
44
from ISystem import ISystem
45
from Rules import Tech
46
47
48
class IGalaxy(IObject):
49
50
    typeID = T_GALAXY
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable T_GALAXY does not seem to be defined.
Loading history...
51
    forums = {"PUBLIC": 112, "NEWS": 112}
52
53
    def init(self, obj):
54
        IObject.init(self, obj)
55
        #
56
        obj.name = ""
57
        obj.owner = OID_NONE
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable OID_NONE does not seem to be defined.
Loading history...
58
        obj.x = 0.0
59
        obj.y = 0.0
60
        obj.radius = 0.0
61
        obj.centerWeight = 250.0
62
        obj.systems = []
63
        obj.startingPos = []
64
        obj.numOfStartPos = 0
65
        obj.timeEnabled = None # none instead of False, to know when first enablement is happening
66
        obj.timePaused = False # this is only used for player-initiated pause, prevents autoenablement
67
        obj.creationTurn = 0
68
        obj.imperator = OID_NONE
69
        obj.description = ""
70
        obj.scenario = SCENARIO_NONE
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable SCENARIO_NONE does not seem to be defined.
Loading history...
71
        obj.scenarioData = IDataHolder()
72
        # electromagnetic radiation
73
        obj.emrLevel = 1.0
74
        obj.emrTrend = 1.0
75
        obj.emrTime = 0
76
        # galaxy keeps track of it's own time as well (because of pauses)
77
        obj.galaxyTurn = 0
78
79
    def update(self, tran, obj):
80
        # check existence of all systems
81
        if 0:
82
            for systemID in obj.systems:
83
                if not tran.db.has_key(systemID):
84
                    log.debug("CONSISTENCY - system %d from galaxy %d does not exists" % (systemID, obj.oid))
85
                elif tran.db[systemID].type not in (T_SYSTEM, T_WORMHOLE):
86
                    log.debug("CONSISTENCY - system %d from galaxy %d is not a T_SYSTEM or T_WORMHOLE" % (systemID, obj.oid))
87
        # validate starting positions
88
        for planetID in obj.startingPos[:]:
89
            if not tran.db.has_key(planetID):
90
                log.debug("REMOVING nonexistent obj from start pos", planetID)
91
                obj.startingPos.remove(planetID)
92
                continue
93
            planet = tran.db[planetID]
94
            if planet.type != T_PLANET:
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable T_PLANET does not seem to be defined.
Loading history...
95
                log.debug("REMOVING ??? from start pos", planetID)
96
                obj.startingPos.remove(planetID)
97
        # check compOf
98
        if not tran.db.has_key(obj.compOf) or tran.db[obj.compOf].type != T_UNIVERSE:
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable T_UNIVERSE does not seem to be defined.
Loading history...
99
            log.debug("CONSISTENCY invalid compOf for galaxy", obj.oid, obj.compOf)
100
        # TODO: remove after 0.5.72
101
        if not hasattr(obj, 'scenario'):
102
            if obj.isSingle:
103
                obj.scenario = SCENARIO_SINGLE
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable SCENARIO_SINGLE does not seem to be defined.
Loading history...
104
            else:
105
                obj.scenario = SCENARIO_OUTERSPACE
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable SCENARIO_OUTERSPACE does not seem to be defined.
Loading history...
106
        if not hasattr(obj, 'scenarioData'):
107
            obj.scenarioData = IDataHolder()
108
        if obj.scenario == SCENARIO_SINGLE and not getattr(obj, 'owner', OID_NONE):
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable OID_NONE does not seem to be defined.
Loading history...
109
            # singleplayer galaxy owner being the only player present
110
            players = set([])
111
            for systemID in obj.systems:
112
                for planetID in tran.db[systemID].planets:
113
                    players |= set([tran.db[planetID].owner])
114
            for playerID in players - set([OID_NONE]):
115
                player = tran.db[playerID]
116
                if player.type in [T_PLAYER, T_PIRPLAYER]:
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable T_PLAYER does not seem to be defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable T_PIRPLAYER does not seem to be defined.
Loading history...
117
                    obj.owner = playerID
118
                    break
119
        # TODO: remove after 0.5.73
120
        if not hasattr(obj, 'galaxyTurn'):
121
            obj.galaxyTurn = 0
122
        obj.timeEnabled = bool(obj.timeEnabled)
123
124
125
    update.public = 0
126
127
    def getReferences(self, tran, obj):
128
        return obj.systems
129
130
    getReferences.public = 0
131
132
    @staticmethod
133
    def getFreeStartingPosition(db, obj):
134
        while 1:
135
            planetID = random.choice(obj.startingPos)
136
            obj.startingPos.remove(planetID)
137
            log.debug('Starting point', planetID)
138
            log.debug('Starting point - owner', db[planetID].owner)
139
            if db[planetID].owner == OID_NONE:
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable OID_NONE does not seem to be defined.
Loading history...
140
                return planetID
141
            if not obj.startingPos:
142
                raise ige.GameException('No free starting point in the galaxy.')
143
144
    @public(AL_ADMIN)
145
    def processINITPhase(self, tran, obj, data):
146
        if not obj.timeEnabled:
147
            return
148
        # compute emr level
149
        turn = tran.db[OID_UNIVERSE].turn
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable OID_UNIVERSE does not seem to be defined.
Loading history...
150
        # galaxy keeps track of it's own time (because of pauses)
151
        obj.galaxyTurn += 1
152
        obj.emrTime -= 1
153
        if obj.emrTime <= 0:
154
            modulo = turn % Rules.emrPeriod
155
            for season in Rules.emrSeasons:
156
                if modulo >= season.startTime and modulo <= season.endTime:
157
                    log.debug("EMR - season", season.name)
158
                    obj.emrTrend = Utils.rand(int(season.emrLevelMin * 100), int(season.emrLevelMax * 100) + 1) / 100.0
159
                    obj.emrTime = Utils.rand(Rules.emrMinDuration, Rules.emrMaxDuration)
160
                    log.debug("EMR - trend, time", obj.emrTrend, obj.emrTime)
161
                    message = {
162
                        "sender": "GNC",
163
                        "senderID": obj.oid,
164
                        "forum": "NEWS",
165
                        "data": (obj.oid, MSG_GNC_EMR_FORECAST, obj.oid, turn, (obj.emrTrend, obj.emrTime)),
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable MSG_GNC_EMR_FORECAST does not seem to be defined.
Loading history...
166
                        "topic": "EVENT",
167
                    }
168
                    self.cmd(obj).sendMsg(tran, obj, message)
169
                    break
170
        elif obj.emrLevel >= obj.emrTrend:
171
            obj.emrLevel -= Utils.rand(1, 6) / 100.0
172
        elif obj.emrLevel <= obj.emrTrend:
173
            obj.emrLevel += Utils.rand(1, 6) / 100.0
174
        # remove old messages
175
        self.cmd(obj).deleteOldMsgs(tran, obj)
176
        return obj.systems
177
178
    @public(AL_ADMIN)
179
    def processPRODPhase(self, tran, obj, data):
180
        if not obj.timeEnabled:
181
            return
182
        return obj.systems
183
184
    @public(AL_ADMIN)
185
    def processACTIONPhase(self, tran, obj, data):
186
        if not obj.timeEnabled:
187
            return
188
        return obj.systems
189
190
    @public(AL_ADMIN)
191
    def processSCAN2Phase(self, tran, obj, data):
192
        # data == True means forced scan (first after generating the galaxy)
193
        if not obj.timeEnabled and not data:
194
            return
195
        # compute scanner for all objects on the map
196
        playerMap = Scanner.computeMap(self, tran, obj)
197
        # distribute map
198
        for playerID, map in playerMap.iteritems():
199
            player = tran.db[playerID]
200
            self.cmd(player).mergeScannerMap(tran, player, map)
201
        return
202
203
    @public(AL_ADMIN)
204
    def processBATTLEPhase(self, tran, obj, data):
205
        if not obj.timeEnabled:
206
            return
207
        return obj.systems
208
209
    @public(AL_ADMIN)
210
    def processFINALPhase(self, tran, obj, data):
211
        if not obj.timeEnabled:
212
            return
213
        # validate starting positions
214
        remove = []
215
        for planetID in obj.startingPos:
216
            planet = tran.db[planetID]
217
            if planet.owner != OID_NONE:
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable OID_NONE does not seem to be defined.
Loading history...
218
                remove.append(planetID)
219
        for planetID in remove:
220
            obj.startingPos.remove(planetID)
221
        return obj.systems
222
223
    @public(AL_ADMIN)
224
    def processFINAL2Phase(self, tran, obj, data):
225
        if not obj.timeEnabled:
226
            return
227
        # save history file
228
        turn = tran.db[OID_UNIVERSE].turn
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable OID_UNIVERSE does not seem to be defined.
Loading history...
229
        # TODO: reneable history when it's optimized
230
        if turn % 6 == 0 and False:
231
            log.debug("Saving history for galaxy", obj.oid, obj.name)
232
            fh = open(os.path.join(tran.config.configDir,"history/galaxy%d-%06d.xml" % (obj.oid, turn), "w+"))
233
            print >>fh, '<?xml version="1.0" encoding="UTF-8"?>'
234
            print >>fh, '<history turn="%d" galaxy="%d" name="%s">' % (turn, obj.oid, obj.name)
235
            # save systems and owners
236
            players = {}
237
            print >>fh, '  <systems>'
238
            for systemID in obj.systems:
239
                system = tran.db[systemID]
240
                owners = {}
241
                for planetID in system.planets:
242
                    ownerID = tran.db[planetID].owner
243
                    if ownerID != OID_NONE:
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable OID_NONE does not seem to be defined.
Loading history...
244
                        owners[ownerID] = tran.db[ownerID].name
245
                        players[ownerID] = None
246
                print >>fh, '    <sys x="%.2f" y="%.2f" name="%s" owners="%s"/>' % (
247
                    system.x,
248
                    system.y,
249
                    system.name,
250
                    ",".join(owners.values())
251
                )
252
            print >>fh, '  </systems>'
253
            # stats
254
            print >>fh, '  <stats>'
255
            for playerID in players:
256
                player = tran.db[playerID]
257
                print >>fh, '    <pl name="%s" pop="%d" planets="%d" stucts="%d" cp="%d" mp="%d" rp="%d"/>'% (
258
                    player.name,
259
                    player.stats.storPop,
260
                    player.stats.planets,
261
                    player.stats.structs,
262
                    player.stats.prodProd,
263
                    player.stats.fleetPwr,
264
                    player.stats.prodSci,
265
                )
266
            print >>fh, '  </stats>'
267
            print >>fh, '</history>'
268
269
270
    @public(AL_ADMIN)
271
    def loadFromXML(self, tran, obj, file, galaxyType, x, y, name):
272
        log.message('IGalaxy', 'Parsing XML file...')
273
        dom = parse(os.path.join('data', file))
274
        log.message('IGalaxy', 'XML file parsed.')
275
        assert dom.documentElement.tagName == 'universe'
276
        for node in dom.documentElement.childNodes:
277
            if node.nodeType == Node.ELEMENT_NODE and node.tagName == 'galaxy':
278
                if node.getAttribute('galaxyType') == galaxyType:
279
                    self.loadDOMNode(tran, obj, node, x, y, name)
280
                    self.connectWormHoles(tran, obj)
281
                    return SUCC
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable SUCC does not seem to be defined.
Loading history...
282
        raise ige.GameException('No such id %s in resource' % galaxyType)
283
284
    def loadDOMNode(self, tran, obj, node, x, y, name):
285
        obj.name = name
286
        obj.x = float(x)
287
        obj.y = float(y)
288
        xoff = x - float(node.getAttribute('x'))
289
        yoff = y - float(node.getAttribute('y'))
290
        obj.creationTurn = tran.db[OID_UNIVERSE].turn
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable OID_UNIVERSE does not seem to be defined.
Loading history...
291
        for elem in node.childNodes:
292
            if elem.nodeType == Node.ELEMENT_NODE:
293
                name = elem.tagName
294
                if name == 'properties':
295
                    self.loadDOMAttrs(obj, elem)
296
                elif name == 'system':
297
                    system = tran.db[self.createSystem(tran, obj)]
298
                    self.cmd(system).loadDOMNode(tran, system, xoff, yoff, elem)
299
                elif name == 'hole':
300
                    wormHole = tran.db[self.createWormHole(tran, obj)]
301
                    self.cmd(wormHole).loadDOMNode(tran, wormHole, xoff, yoff, elem)
302
                else:
303
                    raise ige.GameException('Unknown element %s' % name)
304
        return SUCC
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable SUCC does not seem to be defined.
Loading history...
305
306
    def connectWormHoles(self, tran, obj):
307
        wormHoles = {}
308
        for holeID in obj.systems:
309
            wormHole = tran.db[holeID]
310
            if wormHole.type == T_WORMHOLE:
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable T_WORMHOLE does not seem to be defined.
Loading history...
311
                wormHoles[wormHole.name] = holeID
312
313
        for holeID in obj.systems:
314
            wormHole = tran.db[holeID]
315
            if wormHole.type != T_WORMHOLE:
316
                continue
317
            if len(wormHole.destination) == 0:
318
                raise ige.GameException('Wrong WormHole(%d) definition' % holeID)
319
            if wormHole.destination == wormHole.name:
320
                raise ige.GameException('Same destination as position for WormHole(%d)' % holeID)
321
            destinationOid = wormHoles[wormHole.destination]
322
            if destinationOid == OID_NONE:
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable OID_NONE does not seem to be defined.
Loading history...
323
                raise ige.GameException('WormHole(%d) has wrong destination ''%s''' % (holeID, wormHole.destination))
324
            wormHole.destinationOid = destinationOid
325
326
    def createSystem(self, tran, obj):
327
        system = self.new(T_SYSTEM)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable T_SYSTEM does not seem to be defined.
Loading history...
328
        system.compOf = obj.oid
329
        oid = tran.db.create(system)
330
        obj.systems.append(oid)
331
        return oid
332
333
    def createWormHole(self, tran, galaxy):
334
        hole = self.new(T_WORMHOLE)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable T_WORMHOLE does not seem to be defined.
Loading history...
335
        hole.compOf = galaxy.oid
336
        oid = tran.db.create(hole)
337
        galaxy.systems.append(oid)
338
        return oid
339
340
    @public(AL_OWNER)
341
    def toggleTime(self, tran, obj):
342
        player = tran.db[obj.owner]
343
        obj.timeEnabled = not obj.timeEnabled
344
        obj.timePaused = not obj.timeEnabled
345
        self._trickleTimeToPlayers(tran, obj)
346
        return obj.timeEnabled
347
348
    def _trickleTimeToPlayers(self, tran, obj):
349
        # enable time for players
350
        playerIDs = set()
351
        for systemID in obj.systems:
352
            system = tran.db[systemID]
353
            for planetID in system.planets:
354
                planet = tran.db[planetID]
355
                playerIDs.add(planet.owner)
356
        playerIDs.discard(OID_NONE)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable OID_NONE does not seem to be defined.
Loading history...
357
        for playerID in playerIDs:
358
            player = tran.db[playerID]
359
            if player.timeEnabled != obj.timeEnabled:
360
                player.timeEnabled = obj.timeEnabled
361
                player.lastLogin = time.time()
362
                if player.timeEnabled:
363
                    Utils.sendMessage(tran, player, MSG_ENABLED_TIME, player.oid, None)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable MSG_ENABLED_TIME does not seem to be defined.
Loading history...
364
                else:
365
                    Utils.sendMessage(tran, player, MSG_DISABLED_TIME, player.oid, None)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable MSG_DISABLED_TIME does not seem to be defined.
Loading history...
366
367
    def _isEligibleEnableTime(self, tran, obj):
368
        if obj.timeEnabled or obj.timePaused:
369
            # explicitly paused galaxy needs to be explicitly unpaused
370
            return False
371
        # We have to give players some time to prepare
372
        # (as they might be waiting for very long time for this galaxy to be created).
373
        currentTurn = tran.db[OID_UNIVERSE].turn
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable OID_UNIVERSE does not seem to be defined.
Loading history...
374
        if obj.creationTurn + Rules.galaxyStartDelay <= currentTurn:
375
            log.debug("Time to prepare has passed", obj.creationTurn, currentTurn)
376
            return True
377
        elif obj.scenario == SCENARIO_SINGLE:
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable SCENARIO_SINGLE does not seem to be defined.
Loading history...
378
            return True
379
        return False
380
381
    def _firstEnableTime(self, tran, obj):
382
        # spawn rebel player on all vacant starting positions
383
        for positionID in copy.copy(obj.startingPos):
384
            obj.startingPos.remove(positionID)
385
            # create new player
386
            log.debug("Creating new Rebel player", T_AIPLAYER)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable T_AIPLAYER does not seem to be defined.
Loading history...
387
            player = self.new(T_AIPLAYER)
388
            self.cmd(player).register(tran, player, obj.oid)
389
            player.galaxy = obj.oid
390
            playerID = player.oid
391
            # TODO tweak more planet's attrs
392
            planet = tran.db[positionID]
393
            self.cmd(planet).changeOwner(tran, planet, playerID, 1)
394
            IAIPlayer.IAIPlayer.setStartingTechnologies(player)
395
            # fleet
396
            # add basic ships designs
397
            # add small fleet
398
            system = tran.db[planet.compOf]
399
            IAIPlayer.IAIPlayer.setStartingShipDesigns(player)
400
            IAIPlayer.IAIPlayer.setStartingPlanet(tran, playerID, planet)
401
            IAIPlayer.IAIPlayer.setStartingFleet(tran, playerID, system)
402
            system.scannerPwrs[playerID] = Rules.startingScannerPwr
403
        # do scanner evaluation because of all new players
404
        self.cmd(obj).processSCAN2Phase(tran, obj, None)
405
406
    @public(AL_ADMIN)
407
    def enableTime(self, tran, obj, force = False):
408
        log.debug('IGalaxy', 'Checking for time...')
409
        if not force and not self._isEligibleEnableTime(tran, obj):
410
            return
411
        if obj.timeEnabled is None:
412
            self._firstEnableTime(tran, obj)
413
        # ok, enable time
414
        log.message('IGalaxy', 'Enabling time for', obj.oid)
415
        obj.timeEnabled = True
416
        self._trickleTimeToPlayers(tran, obj)
417
418
    @public(AL_OWNER)
419
    def deleteSingle(self, tran, obj):
420
        if obj.scenario != SCENARIO_SINGLE:
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable SCENARIO_SINGLE does not seem to be defined.
Loading history...
421
            raise ige.GameException('Only Single Player galaxies can be deleted this way')
422
        log.debug(obj.oid, "GALAXY - singleplayer delete")
423
        self.delete(tran, obj)
424
425
    @public(AL_ADMIN)
426
    def delete(self, tran, obj):
427
        log.debug(obj.oid, "GALAXY - delete")
428
        universe = tran.db[OID_UNIVERSE]
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable OID_UNIVERSE does not seem to be defined.
Loading history...
429
        # delete systems and planets
430
        for systemID in obj.systems:
431
            log.debug("Deleting system", systemID)
432
            system = tran.db[systemID]
433
            log.debug("-- planets", system.planets)
434
            log.debug("-- fleets", system.fleets, system.closeFleets)
435
            for planetID in system.planets[:]:
436
                planet = tran.db[planetID]
437
                self.cmd(planet).changeOwner(tran, planet, OID_NONE, force = 1)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable OID_NONE does not seem to be defined.
Loading history...
438
                del tran.db[planetID]
439
            for fleetID in system.closeFleets[:]:
440
                fleet = tran.db[fleetID]
441
                # this will modify system fleet and closeFleets attrs
442
                self.cmd(fleet).disbandFleet(tran, fleet)
443
            del tran.db[systemID]
444
        # delete all remaining fleets
445
        for playerID in universe.players[:]:
446
            player = tran.db[playerID]
447
            if obj.oid != player.galaxy:
448
                continue
449
            if player.fleets:
450
                log.debug("Player %d has still fleets" % playerID, player.name, player.fleets)
451
                for fleetID in player.fleets:
452
                    fleet = tran.db[fleetID]
453
                    log.debug("Fleet NOT DELETED:", fleet)
454
            if player.planets:
455
                log.debug("Player %d has still planets" % playerID, player.name, player.planets)
456
            self.cmd(player).delete(tran, player)
457
        # remove this galaxy from the list of the galaxies
458
        tran.db[OID_UNIVERSE].galaxies.remove(obj.oid)
459
        del tran.db[obj.oid]
460
        return 1
461
462
    @public(AL_NONE)
463
    def getPublicInfo(self, tran, obj):
464
        result = IDataHolder()
465
        result.oid = obj.oid
466
        result.x = obj.x
467
        result.y = obj.y
468
        result.radius = obj.radius
469
        result.type = obj.type
470
        result.name = obj.name
471
        result.emrLevel = obj.emrLevel
472
        result.scenario = obj.scenario
473
        result.scenarioData = obj.scenarioData
474
        result.timeEnabled = obj.timeEnabled
475
        return result
476
477
    @public(AL_NONE)
478
    def getDescription(self,obj):
479
        return obj.description
480
481
    @public(AL_ADMIN)
482
    def setupEnvironment(self, tran, obj):
483
        universe = tran.db[OID_UNIVERSE]
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable OID_UNIVERSE does not seem to be defined.
Loading history...
484
        # we will first scan galaxy, to determine which environments are available
485
        # this way, we will create only players that are needed, and not all types
486
        vacant_planets = {}
487
        for systemID in obj.systems:
488
            system = tran.db[systemID]
489
            for planetID in system.planets:
490
                planet = tran.db[planetID]
491
                # renegades
492
                if planet.plStratRes in (SR_TL1A, SR_TL1B) and planet.owner == OID_NONE:
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable SR_TL1B does not seem to be defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable SR_TL1A does not seem to be defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable OID_NONE does not seem to be defined.
Loading history...
493
                    try:
494
                        vacant_planets[T_AIRENPLAYER] += [planetID]
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable T_AIRENPLAYER does not seem to be defined.
Loading history...
495
                    except KeyError:
496
                        vacant_planets[T_AIRENPLAYER] = [planetID]
497
                # pirates
498
                if planet.plStratRes in (SR_TL3A, SR_TL3B, SR_TL3C) and planet.owner == OID_NONE:
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable SR_TL3A does not seem to be defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable SR_TL3B does not seem to be defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable SR_TL3C does not seem to be defined.
Loading history...
499
                    try:
500
                        vacant_planets[T_AIPIRPLAYER] += [planetID]
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable T_AIPIRPLAYER does not seem to be defined.
Loading history...
501
                    except KeyError:
502
                        vacant_planets[T_AIPIRPLAYER] = [planetID]
503
                # EDEN
504
                if planet.plStratRes in (SR_TL5A, SR_TL5B, SR_TL5C) and planet.owner == OID_NONE:
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable SR_TL5A does not seem to be defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable SR_TL5B does not seem to be defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable SR_TL5C does not seem to be defined.
Loading history...
505
                    try:
506
                        vacant_planets[T_AIEDENPLAYER] += [planetID]
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable T_AIEDENPLAYER does not seem to be defined.
Loading history...
507
                    except KeyError:
508
                        vacant_planets[T_AIEDENPLAYER] = [planetID]
509
                # mutants
510
                if planet.plDisease != 0 and planet.owner == OID_NONE:
511
                    try:
512
                        vacant_planets[T_AIMUTPLAYER] += [planetID]
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable T_AIMUTPLAYER does not seem to be defined.
Loading history...
513
                    except KeyError:
514
                        vacant_planets[T_AIMUTPLAYER] = [planetID]
515
        # iterate over types, create players if needed (it should be) and fill in vacant planets
516
        for playerType in vacant_planets:
517
            found = 0
518
            for playerID in universe.players:
519
                player = tran.db[playerID]
520
                if obj.oid == player.galaxy and player.type == playerType:
521
                    found = 1
522
                    break
523
            if not found:
524
                # create new player
525
                log.debug("Creating new player", playerType)
526
                player = self.new(playerType)
527
                self.cmd(player).register(tran, player, obj.oid)
528
                player.galaxy = obj.oid
529
            # now we have a player, let's iterate over vacant planets and set them up
530
            for planetID in vacant_planets[playerType]:
531
                planet = tran.db[planetID]
532
                self.cmd(planet).changeOwner(tran, planet, player.oid, 1)
0 ignored issues
show
introduced by
The variable player does not seem to be defined for all execution paths.
Loading history...
533
                if playerType == T_AIRENPLAYER:
534
                    IAIRenegadePlayer.IAIRenegadePlayer.setStartingPlanet(tran, planet)
535
                elif playerType == T_AIPIRPLAYER:
536
                    IAIPiratePlayer.IAIPiratePlayer.setStartingPlanet(tran, planet)
537
                elif playerType == T_AIEDENPLAYER:
538
                    IAIEDENPlayer.IAIEDENPlayer.setStartingPlanet(tran, planet)
539
                elif playerType == T_AIMUTPLAYER:
540
                    IAIMutantPlayer.IAIMutantPlayer.setStartingPlanet(tran, planet)
541
542
    ## messaging
543
    def canGetMsgs(self, tran, obj, oid):
544
        return 1
545
546
    canGetMsgs.public = 0
547
548
    def canSendMsg(self, tran, obj, oid, forum):
549
        if forum == "PUBLIC":
550
            return 1
551
        elif forum == "NEWS":
552
            return 1
553
        return 0
554
555
    canSendMsg.public = 0
556