Completed
Pull Request — master (#242)
by Marek
02:10
created

AIs.ais_rebel.Rebel._colonize_planets()   A

Complexity

Conditions 3

Size

Total Lines 12
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 11
nop 3
dl 0
loc 12
rs 9.85
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
from ige import log
21
from ige.ospace import Const
22
from ige.ospace import Rules
23
from ige.ospace import Utils
24
from ige.ospace import TechHandlers
25
26
import ai_tools as tool
27
from ai import AI
28
29
import copy, random, math
30
31
class Rebel(AI):
32
    def __init__(self, client):
33
        super(Rebel, self).__init__(client)
34
        tool.doRelevance(self.data, self.client, self.db, 10)
35
        self.designs = {}
36
37
    def offense_manager(self):
38
        # rebel is not suited for attacks, yet
39
        pass
40
41
    def _get_idle_planets(self, system):
42
        idle_planets = set()
43
        for planet_id in self.data.myProdPlanets & set(system.planets):
44
            planet = self.db[planet_id]
45
            if not getattr(planet, 'prodQueue', None):
46
                idle_planets.add(planet_id)
47
                continue
48
        return idle_planets
49
50
    def _fill_planets(self, system, idle_planets):
51
        system_stats = tool.getSystemStructStats(self.data, self.client, self.db, system.oid)
52
        for planet_id in copy.copy(idle_planets):
53
            planet = self.db[planet_id]
54
            prod_tech_id = Rules.Tech.RESCENTRE1 if planet.plMin < 100 else Rules.Tech.FACTORY1
55
            prod_tech = self.client.getFullTechInfo(prod_tech_id)
56
            # now we ignore all already build structures, and try to satisfy
57
            # outpost/fact or outpost/labs ration [on free slots]
58
            if planet.plSlots > len(planet.slots):
59
                if system_stats.en > prod_tech.operEn and system_stats.bio > prod_tech.operWorkers / 100:
60
                    planet.prodQueue, self.player.stratRes = self.client.cmdProxy.startConstruction(planet.oid,
61
                        prod_tech.id, 1, planet_id, prod_tech.id < 1000, 0, Const.OID_NONE)
62
                    idle_planets.remove(planet_id)
63
                else:
64
                    planet.prodQueue, self.player.stratRes = self.client.cmdProxy.startConstruction(planet_id,
65
                        Rules.Tech.OUTPOST1, 1, planet_id, Rules.Tech.OUTPOST1 < 1000, 0, Const.OID_NONE)
66
                    idle_planets.remove(planet_id)
67
68
    def _colonize_planets(self, system, idle_planets):
69
        toColonize = self.data.freePlanets & set(system.planets)
70
        # colonize remaining planets
71
        for planet_id in copy.copy(idle_planets):
72
            planet = self.db[planet_id]
73
            if toColonize:
74
                targetID = toColonize.pop()
75
                target = self.db[targetID]
76
                planet.prodQueue, self.player.stratRes = self.client.cmdProxy.startConstruction(planet_id,
77
                    Rules.Tech.OUTPOST1, 1,
78
                    targetID, Rules.Tech.OUTPOST1 < 1000, 0, Const.OID_NONE)
79
                idle_planets.remove(planet_id)
80
81
    def _build_ships(self, system, idle_planets):
82
        for planet_id in copy.copy(idle_planets):
83
            planet = self.db[planet_id]
84
            systemFleets = getattr(system, 'fleets', [])
85
            has_colony = False
86
            has_scouts = False
87
            shared_system = len(set(system.planets) & self.data.otherPlanets) > 0
88
            for fleetID in systemFleets:
89
                fleet = self.db[fleetID]
90
                if getattr(fleet, 'owner', Const.OID_NONE) == self.player.oid:
91
                    has_colony |= tool.fleetContains(fleet, {self.designs["colony"]:1})
92
                    has_scouts |= tool.fleetContains(fleet, {self.designs["scout"]:1})
93
            if not has_colony:
94
                planet.prodQueue, self.player.stratRes = self.client.cmdProxy.startConstruction(planet_id,
95
                    self.designs["colony"], 1, planet_id, self.designs["colony"] < 1000, 0, Const.OID_NONE)
96
            elif not has_scouts:
97
                planet.prodQueue, self.player.stratRes = self.client.cmdProxy.startConstruction(planet_id,
98
                    self.designs["scout"], 1, planet_id, self.designs["scout"] < 1000, 0, Const.OID_NONE)
99
            elif Rules.Tech.UPGRADESHIPS in self.player.techs and self.player.fleetUpgradePool < 2000:
100
                planet.prodQueue, self.player.stratRes = self.client.cmdProxy.startConstruction(planet_id,
101
                    Rules.Tech.UPGRADESHIPS, 1, planet_id, Rules.Tech.UPGRADESHIPS < 1000, 0, Const.OID_NONE)
102
103
            elif not shared_system:
104
                # build fighters
105
                planet.prodQueue, self.player.stratRes = self.client.cmdProxy.startConstruction(planet_id,
106
                    self.designs["fighter"], 1, planet_id, self.designs["fighter"] < 1000, 0, Const.OID_NONE)
107
108
    def _planet_manager(self):
109
        for planet_id in self.data.myPlanets:
110
            tool.sortStructures(self.client, self.db, planet_id)
111
        for system_id in self.data.mySystems:
112
            system = self.db[system_id]
113
            idle_planets = self._get_idle_planets(system)
114
            # build production buildings if nothing is needed, or outposts
115
            self._fill_planets(system, idle_planets)
116
            self._colonize_planets(system, idle_planets)
117
            self._build_ships(system, idle_planets)
118
119
    def _place_gov_center(self, candidate_planets):
120
        PLACEHOLDERS = (Rules.Tech.RESCENTRE1, Rules.Tech.FACTORY1)
121
        for planet_id in candidate_planets:
122
            planet = self.db[planet_id]
123
            if planet.prodProd == 0:
124
                continue
125
            gov_placeholder = None
126
            for struct in [x for x in planet.slots if x[0] in PLACEHOLDERS]:
127
                if gov_placeholder is not None:
128
                    planet.prodQueue, self.player.stratRes = self.client.cmdProxy.startConstruction(planet_id,
129
                        Rules.Tech.GOVCENTER1, 1, planet_id, Rules.Tech.GOVCENTER1 < 1000, 0, gov_placeholder)
130
                    planet.prodQueue, self.player.stratRes = self.client.cmdProxy.startConstruction(planet_id,
131
                        Rules.Tech.OUTPOST1, 1, planet_id, Rules.Tech.OUTPOST1 < 1000, 0, struct[0])
132
                    return
133
                gov_placeholder = struct[0]
134
135
    def _cancel_gov_tasks(self, planet_ids):
136
        # cancel all tasks
137
        for planet_id in planet_ids:
138
            planet = self.db[planet_id]
139
            indexes = []
140
            i = 0
141
            for task in planet.prodQueue:
142
                if task.techID in set([1000, 3010, 3011]):
143
                    indexes.append(i)
144
                i += 1
145
            indexes.reverse()
146
            for index in indexes:
147
                self.client.cmdProxy.abortConstruction(planet_id, index)
148
149
    def _get_current_gov(self):
150
        gov_position = Const.OID_NONE
151
        gov_productions = []
152
        for planet_id in self.data.myPlanets:
153
            # find build gov center
154
            planet = self.db[planet_id]
155
            for struct in planet.slots:
156
                if struct[0] in set([1000, 3010, 3011]):
157
                    gov_position = planet_id
158
                    break
159
            for task in getattr(planet, 'prodQueue', []):
160
                if task.techID in set([1000, 3010, 3011]):
161
                    gov_productions.append(planet_id)
162
                    break
163
        return gov_position, gov_productions
164
165
    def _empire_manager(self):
166
        if not Rules.Tech.GOVCENTER1 in self.player.techs.keys():
167
            return
168
        candidates = tool.findPopCenterPlanets(self.db, self.data.myPlanets)
169
        candidate_planets = candidates[:10]
170
        gov_position, gov_productions = self._get_current_gov()
171
        if not set(candidate_planets) & (set([gov_position]) | set(gov_productions)):
172
            self._cancel_gov_tasks(gov_productions)
173
            self._place_gov_center(candidate_planets)
174
        return
175
176
    def _expansion_manager(self):
177
        should_repeat = True
178
        pirate_influenced_systems = tool.findInfluence(self.data, self.client, self.db, Rules.pirateInfluenceRange, self.data.pirateSystems)
179
        while should_repeat:
180
            should_repeat = False
181
            should_repeat |= self._explore(self.designs["scout"])
182
            safe_systems = (self.data.freeSystems & self.data.relevantSystems) - pirate_influenced_systems
183
            should_repeat |= self._colonize_free_systems(safe_systems, self.designs["colony"])
184
185
    def _identify_basic_designs(self):
186
        for desID in self.player.shipDesigns:
187
            design = self.player.shipDesigns[desID]
188
            if design.name == 'Scout':
189
                self.designs["scout"] = desID
190
            elif design.name == 'Fighter':
191
                self.designs["fighter"] = desID
192
            elif design.name == 'Bomber':
193
                self.designs["bomber"] = desID
194
            elif design.name == 'Colony Ship':
195
                self.designs["colony"] = desID
196
197
    def _identify_advanced_designs(self):
198
        for desID in self.player.shipDesigns:
199
            design = self.player.shipDesigns[desID]
200
            if design.name == 'Fighter 2':
201
                self.designs["fighter0"] = self.designs["fighter"]
202
                self.designs["fighter"] = desID
203
            elif design.name == 'Bomber 2':
204
                self.designs["bomber0"] = self.designs["bomber"]
205
                self.designs["bomber"] = desID
206
            elif design.name == 'Colony Ship 2':
207
                self.designs["colony0"] = self.designs["colony"]
208
                self.designs["colony"] = desID
209
210
    def _create_basic_designs(self):
211
        if "scout" not in self.designs:
212
            self.designs["scout"] = self.client.cmdProxy.addShipDesign(self.player.oid, 'Scout',
213
                    Rules.Tech.SMALLHULL0, {Rules.Tech.SCOCKPIT0:1,
214
                    Rules.Tech.SCANNERMOD0:1, Rules.Tech.FTLENG0:3})
215
        if "fighter" not in self.designs:
216
            self.designs["fighter"] = self.client.cmdProxy.addShipDesign(self.player.oid, 'Fighter',
217
                    Rules.Tech.SMALLHULL0, {Rules.Tech.SCOCKPIT0:1,
218
                    Rules.Tech.CANNON0:2, Rules.Tech.FTLENG0:3})
219
        if "bomber" not in self.designs:
220
            self.designs["bomber"] = self.client.cmdProxy.addShipDesign(self.player.oid, 'Bomber',
221
                    Rules.Tech.SMALLHULL0, {Rules.Tech.SCOCKPIT0:1,
222
                    Rules.Tech.CONBOMB0:1, Rules.Tech.FTLENG0:3})
223
        if "colony" not in self.designs:
224
            self.designs["colony"] = self.client.cmdProxy.addShipDesign(self.player.oid, 'Colony Ship',
225
                    Rules.Tech.MEDIUMHULL0, {Rules.Tech.SCOCKPIT0:1,
226
                    Rules.Tech.COLONYMOD0:1, Rules.Tech.FTLENG0:5})
227
228
    def _create_advanced_designs(self):
229
        needed_tech = set([Rules.Tech.SMALLHULL1, Rules.Tech.SCOCKPIT1, Rules.Tech.CANNON1, Rules.Tech.FTLENG1])
230
        if needed_tech.issubset(self.player.techs) and "fighter0" not in self.designs:
231
            self.designs["fighter0"] = self.designs["fighter"]
232
            self.designs["fighter"] = self.client.cmdProxy.addShipDesign(self.player.oid, 'Fighter 2',
233
                    Rules.Tech.SMALLHULL1, {Rules.Tech.SCOCKPIT1:1,
234
                    Rules.Tech.CANNON1:2, Rules.Tech.FTLENG1:3})
235
        needed_tech = set([Rules.Tech.SMALLHULL1, Rules.Tech.SCOCKPIT1, Rules.Tech.CONBOMB1, Rules.Tech.FTLENG1])
236
        if needed_tech.issubset(self.player.techs) and "bomber0" not in self.designs:
237
            self.designs["bomber0"] = self.designs["bomber"]
238
            self.designs["bomber"] = self.client.cmdProxy.addShipDesign(self.player.oid, 'Bomber 2',
239
                    Rules.Tech.SMALLHULL1, {Rules.Tech.SCOCKPIT1:1,
240
                    Rules.Tech.CONBOMB1:1, Rules.Tech.FTLENG1:3})
241
        needed_tech = set([Rules.Tech.MEDIUMHULL0, Rules.Tech.SCOCKPIT1, Rules.Tech.COLONYMOD0, Rules.Tech.FTLENG1])
242
        if needed_tech.issubset(self.player.techs) and "colony0" not in self.designs:
243
            self.designs["colony0"] = self.designs["colony"]
244
            self.designs["colony"] = self.client.cmdProxy.addShipDesign(self.player.oid, 'Colony Ship 2',
245
                    Rules.Tech.MEDIUMHULL0, {Rules.Tech.SCOCKPIT1:1,
246
                    Rules.Tech.COLONYMOD0:1, Rules.Tech.FTLENG1:5})
247
248
    def _upgrade_obsolete_design(self, old_code_name, new_code_name):
249
        if old_code_name in self.designs:
250
            old_design_id = self.designs[old_code_name]
251
            new_design_id = self.designs[new_code_name]
252
            old_design = self.player.shipDesigns[old_design_id]
253
            if not old_design.upgradeTo:
254
                self.player.shipDesigns, self.player.stratRes, tasksUpgraded, self.player.prodQueues = \
255
                        self.client.cmdProxy.upgradeShipDesign(self.player.oid, old_design_id, new_design_id)
256
257
    def _get_service_centers(self):
258
        service_centers = []
259
        for planet in [self.db[planetID] for planetID in self.data.myPlanets]:
260
            # assumption: if it repairs, it also upgrades
261
            if not planet.repairShip: continue
262
            service_centers.append(planet.compOf)
263
        return service_centers
264
265
    def _get_outdated_fleets(self, obsolete_designs):
266
        outdated_fleets = []
267
        for fleet in [self.db[fleetID] for fleetID in self.data.idleFleets]:
268
            if set(obsolete_designs).intersection([ship[0] for ship in fleet.ships]):
269
                outdated_fleets.append(fleet)
270
        return outdated_fleets
271
272
    def _recall_to_upgrade(self, service_centers, outdated_fleets, obsolete_designs):
273
        for fleet in outdated_fleets:
274
            if fleet.orbiting in service_centers: continue
275
            subfleet_sheet = {}.fromkeys(obsolete_designs, 0)
276
            max_range = tool.subfleetMaxRange(self.client, self.db, subfleet_sheet, fleet.oid)
277
            nearest = tool.findNearest(self.db, fleet, service_centers, max_range)
278
            if not nearest: continue
279
            nearest_service = nearest[0]
280
            fleet, new_fleet, my_fleets = tool.orderPartFleet(self.client, self.db,
281
                subfleet_sheet, True, fleet.oid, Const.FLACTION_MOVE, nearest_service, None)
282
283
    def _upgrade_manager(self):
284
        UPGRADABLE = ["fighter", "bomber", "colony"]
285
        OBSOL_FUNC = lambda x: x + "0"
286
        obsoleted = set(map(OBSOL_FUNC, UPGRADABLE)).intersection(self.designs)
287
        obsolete_designs = [self.designs[obsol] for obsol in obsoleted]
288
        if not obsolete_designs: return
289
290
        service_centers = self._get_service_centers()
291
        outdated_fleets = self._get_outdated_fleets(obsolete_designs)
292
        self._recall_to_upgrade(service_centers, outdated_fleets, obsolete_designs)
293
        for code_name in UPGRADABLE:
294
            self._upgrade_obsolete_design(OBSOL_FUNC(code_name), code_name)
295
296
    def _ship_design_manager(self):
297
        self._identify_basic_designs()
298
        self._identify_advanced_designs()
299
        self._create_basic_designs()
300
        self._create_advanced_designs()
301
302
    def _help_system(self):
303
        tool.doDanger(self.data, self.client, self.db)
304
        pirate_influenced_systems = tool.findInfluence(self.data, self.client, self.db, Rules.pirateInfluenceRange, self.data.pirateSystems)
305
        one_fighter_mp = self.player.shipDesigns[self.designs["fighter"]].combatPwr
306
        for system_id in set(self.data.endangeredSystems) - set(pirate_influenced_systems):
307
            mil_pwr, shipQuantity = self.data.endangeredSystems[system_id]
308
            mil_pwr = -mil_pwr
309
            if system_id in self.data.myMPPerSystem:
310
                mil_pwr += self.data.myMPPerSystem[system_id]
311
            if mil_pwr < 0:
312
                system = self.db[system_id]
313
                nearest = tool.findNearest(self.db, system, self.data.mySystems, 99999, 20)[1:]
314
                for temp_id in nearest:
315
                    if temp_id in self.data.myMPPerSystem:
316
                        temp_mp = self.data.myMPPerSystem[temp_id]
317
                    else:
318
                        temp_mp = 0
319
                        self.data.myMPPerSystem[temp_id] = 0
320
                    if temp_id in self.data.endangeredSystems:
321
                        a, b = self.data.endangeredSystems[temp_id]
322
                        temp_mp -= a * 1.5
323
                        if temp_mp <= 0: continue
324
                    orig = temp_mp = min(-mil_pwr, temp_mp) * 1.25
325
                    # this is just prototype, working only with Fighters
326
                    quantity = int(math.ceil(temp_mp / float(one_fighter_mp)))
327
                    if quantity == 0:
328
                        continue
329
                    ships_left, mil_pwrSend = tool.orderFromSystem(self.data, self.client, self.db,
330
                        {self.designs["fighter"]:quantity}, temp_id, Const.FLACTION_MOVE, system_id, None)
331
                    mil_pwr += mil_pwrSend
332
                    self.data.myMPPerSystem[temp_id] -= mil_pwrSend
333
                    if mil_pwr > 0: break
334
335
    def _return_strays(self):
336
        for fleetID in self.data.idleFleets:
337
            fleet = self.db[fleetID]
338
            # fleets orbiting in systems not belonging to the self.player
339
            if fleet.orbiting and fleet.orbiting not in self.data.mySystems:
340
                nearest = tool.findNearest(self.db, fleet, self.data.mySystems, 99999, 1)
341
                if len(nearest):
342
                    targetID = nearest[0]
343
                    tool.orderFleet(self.client, self.db, fleetID, Const.FLACTION_MOVE, targetID, None)
344
345
    def defense_manager(self):
346
        self._help_system()
347
        self._return_strays()
348
349
    def economy_manager(self):
350
        self._empire_manager()
351
        self._planet_manager()
352
        self._expansion_manager()
353
        self._upgrade_manager()
354
355
    def run(self):
356
        self._ship_design_manager() # this fills self.designs, needs to go first
357
        top_prio_tech = [Rules.Tech.OUTPOST1,
358
                         Rules.Tech.GOVCENTER1,
359
                         Rules.Tech.FACTORY1,
360
                         Rules.Tech.RESCENTRE1,
361
                         Rules.Tech.FTLENG1,
362
                         ]
363
        mid_prio_tech = [Rules.Tech.SMALLHULL1,
364
                         Rules.Tech.SCOCKPIT1,
365
                         Rules.Tech.CANNON1,
366
                         Rules.Tech.UPGRADESHIPS,
367
                         ]
368
        low_prio_tech = [Rules.Tech.PWRPLANTOIL1,
369
                         Rules.Tech.FARM1,
370
                         Rules.Tech.COMSCAN1,
371
                         Rules.Tech.PWRPLANTSOL1,
372
                         Rules.Tech.SPACEPORT,
373
                         Rules.Tech.SCANNERMOD1,
374
                         Rules.Tech.SCANNERMOD2,
375
                         Rules.Tech.CONBOMB1,
376
                         Rules.Tech.HOLIDAYS1,
377
                         Rules.Tech.DEEPSPACESCAN,
378
                         ]
379
        ignored_tech = [Rules.Tech.BIONICTL2,
380
                        Rules.Tech.HUMANTL2,
381
                        Rules.Tech.ROBOTTL2,
382
                        ]
383
        tech_prio = {10: top_prio_tech,
384
                     3: mid_prio_tech,
385
                     1: low_prio_tech,
386
                     0: ignored_tech}
387
        self.research_manager(tech_prio)
388
        self.diplomacy_manager(friendly_types=[Const.T_PLAYER, Const.T_AIPLAYER, Const.T_AIRENPLAYER],
389
                               pacts=[Const.PACT_ALLOW_CIVILIAN_SHIPS, Const.PACT_ALLOW_TANKING,
390
                                      Const.PACT_MINOR_SCI_COOP, Const.PACT_MAJOR_SCI_COOP,
391
                                      Const.PACT_MINOR_CP_COOP, Const.PACT_MAJOR_CP_COOP])
392
        self.economy_manager()
393
        self.defense_manager()
394
        self.offense_manager()
395
396
397
def run(aclient):
398
    ai = Rebel(aclient)
399
    ai.run()
400
    aclient.saveDB()
401
402