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