Completed
Push — master ( 600d1a...7beec5 )
by Marek
16s queued 14s
created

AIs.ais_rebel.Rebel._add_design()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 4
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
#
2
#  Copyright 2001 - 2016 Ludek Smid [http://www.ospace.net/]
3
#
4
#  This file is part of Outer Space.
5
#
6
#  Outer Space is free software; you can redistribute it and/or modify
7
#  it under the terms of the GNU General Public License as published by
8
#  the Free Software Foundation; either version 2 of the License, or
9
#  (at your option) any later version.
10
#
11
#  Outer Space is distributed in the hope that it will be useful,
12
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
13
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
#  GNU General Public License for more details.
15
#
16
#  You should have received a copy of the GNU General Public License
17
#  along with Outer Space; if not, write to the Free Software
18
#  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19
#
20
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 _add_design(self, name, hull_id, equip):
211
        self.player.shipDesigns, index = self.client.cmdProxy.addShipDesign(self.player.oid, name, hull_id, equip)
212
        return index
213
214
    def _create_basic_designs(self):
215
        if "scout" not in self.designs:
216
            self.designs["scout"] = self._add_design('Scout',
217
                    Rules.Tech.SMALLHULL0, {Rules.Tech.SCOCKPIT0:1,
218
                    Rules.Tech.SCANNERMOD0:1, Rules.Tech.FTLENG0:3})
219
        if "fighter" not in self.designs:
220
            self.designs["fighter"] = self._add_design('Fighter',
221
                    Rules.Tech.SMALLHULL0, {Rules.Tech.SCOCKPIT0:1,
222
                    Rules.Tech.CANNON0:2, Rules.Tech.FTLENG0:3})
223
        if "bomber" not in self.designs:
224
            self.designs["bomber"] = self._add_design('Bomber',
225
                    Rules.Tech.SMALLHULL0, {Rules.Tech.SCOCKPIT0:1,
226
                    Rules.Tech.CONBOMB0:1, Rules.Tech.FTLENG0:3})
227
        if "colony" not in self.designs:
228
            self.designs["colony"] = self._add_design('Colony Ship',
229
                    Rules.Tech.MEDIUMHULL0, {Rules.Tech.SCOCKPIT0:1,
230
                    Rules.Tech.COLONYMOD0:1, Rules.Tech.FTLENG0:5})
231
232
    def _create_advanced_designs(self):
233
        needed_tech = set([Rules.Tech.SMALLHULL1, Rules.Tech.SCOCKPIT1, Rules.Tech.CANNON1, Rules.Tech.FTLENG1])
234
        if needed_tech.issubset(self.player.techs) and "fighter0" not in self.designs:
235
            self.designs["fighter0"] = self.designs["fighter"]
236
            self.designs["fighter"] = self._add_design('Fighter 2',
237
                    Rules.Tech.SMALLHULL1, {Rules.Tech.SCOCKPIT1:1,
238
                    Rules.Tech.CANNON1:2, Rules.Tech.FTLENG1:3})
239
        needed_tech = set([Rules.Tech.SMALLHULL1, Rules.Tech.SCOCKPIT1, Rules.Tech.CONBOMB1, Rules.Tech.FTLENG1])
240
        if needed_tech.issubset(self.player.techs) and "bomber0" not in self.designs:
241
            self.designs["bomber0"] = self.designs["bomber"]
242
            self.designs["bomber"] = self._add_design('Bomber 2',
243
                    Rules.Tech.SMALLHULL1, {Rules.Tech.SCOCKPIT1:1,
244
                    Rules.Tech.CONBOMB1:1, Rules.Tech.FTLENG1:3})
245
        needed_tech = set([Rules.Tech.MEDIUMHULL0, Rules.Tech.SCOCKPIT1, Rules.Tech.COLONYMOD0, Rules.Tech.FTLENG1])
246
        if needed_tech.issubset(self.player.techs) and "colony0" not in self.designs:
247
            self.designs["colony0"] = self.designs["colony"]
248
            self.designs["colony"] = self._add_design('Colony Ship 2',
249
                    Rules.Tech.MEDIUMHULL0, {Rules.Tech.SCOCKPIT1:1,
250
                    Rules.Tech.COLONYMOD0:1, Rules.Tech.FTLENG1:5})
251
252
    def _upgrade_obsolete_design(self, old_code_name, new_code_name):
253
        if old_code_name in self.designs:
254
            old_design_id = self.designs[old_code_name]
255
            new_design_id = self.designs[new_code_name]
256
            old_design = self.player.shipDesigns[old_design_id]
257
            if not old_design.upgradeTo:
258
                self.player.shipDesigns, self.player.stratRes, tasksUpgraded, self.player.prodQueues = \
259
                        self.client.cmdProxy.upgradeShipDesign(self.player.oid, old_design_id, new_design_id)
260
261
    def _get_service_centers(self):
262
        service_centers = []
263
        for planet in [self.db[planetID] for planetID in self.data.myPlanets]:
264
            # assumption: if it repairs, it also upgrades
265
            if not planet.repairShip: continue
266
            service_centers.append(planet.compOf)
267
        return service_centers
268
269
    def _get_outdated_fleets(self, obsolete_designs):
270
        outdated_fleets = []
271
        for fleet in [self.db[fleetID] for fleetID in self.data.idleFleets]:
272
            if set(obsolete_designs).intersection([ship[0] for ship in fleet.ships]):
273
                outdated_fleets.append(fleet)
274
        return outdated_fleets
275
276
    def _recall_to_upgrade(self, service_centers, outdated_fleets, obsolete_designs):
277
        for fleet in outdated_fleets:
278
            if fleet.orbiting in service_centers: continue
279
            subfleet_sheet = {}.fromkeys(obsolete_designs, 0)
280
            max_range = tool.subfleetMaxRange(self.client, self.db, subfleet_sheet, fleet.oid)
281
            nearest = tool.findNearest(self.db, fleet, service_centers, max_range)
282
            if not nearest: continue
283
            nearest_service = nearest[0]
284
            fleet, new_fleet, my_fleets = tool.orderPartFleet(self.client, self.db,
285
                subfleet_sheet, True, fleet.oid, Const.FLACTION_MOVE, nearest_service, None)
286
287
    def _upgrade_manager(self):
288
        UPGRADABLE = ["fighter", "bomber", "colony"]
289
        OBSOL_FUNC = lambda x: x + "0"
290
        obsoleted = set(map(OBSOL_FUNC, UPGRADABLE)).intersection(self.designs)
291
        obsolete_designs = [self.designs[obsol] for obsol in obsoleted]
292
        if not obsolete_designs: return
293
294
        service_centers = self._get_service_centers()
295
        outdated_fleets = self._get_outdated_fleets(obsolete_designs)
296
        self._recall_to_upgrade(service_centers, outdated_fleets, obsolete_designs)
297
        for code_name in UPGRADABLE:
298
            self._upgrade_obsolete_design(OBSOL_FUNC(code_name), code_name)
299
300
    def _ship_design_manager(self):
301
        self._identify_basic_designs()
302
        self._identify_advanced_designs()
303
        self._create_basic_designs()
304
        self._create_advanced_designs()
305
306
    def _help_system(self):
307
        tool.doDanger(self.data, self.client, self.db)
308
        pirate_influenced_systems = tool.findInfluence(self.data, self.client, self.db, Rules.pirateInfluenceRange, self.data.pirateSystems)
309
        one_fighter_mp = self.player.shipDesigns[self.designs["fighter"]].combatPwr
310
        for system_id in set(self.data.endangeredSystems) - set(pirate_influenced_systems):
311
            mil_pwr, shipQuantity = self.data.endangeredSystems[system_id]
312
            mil_pwr = -mil_pwr
313
            if system_id in self.data.myMPPerSystem:
314
                mil_pwr += self.data.myMPPerSystem[system_id]
315
            if mil_pwr < 0:
316
                system = self.db[system_id]
317
                nearest = tool.findNearest(self.db, system, self.data.mySystems, 99999, 20)[1:]
318
                for temp_id in nearest:
319
                    if temp_id in self.data.myMPPerSystem:
320
                        temp_mp = self.data.myMPPerSystem[temp_id]
321
                    else:
322
                        temp_mp = 0
323
                        self.data.myMPPerSystem[temp_id] = 0
324
                    if temp_id in self.data.endangeredSystems:
325
                        a, b = self.data.endangeredSystems[temp_id]
326
                        temp_mp -= a * 1.5
327
                        if temp_mp <= 0: continue
328
                    orig = temp_mp = min(-mil_pwr, temp_mp) * 1.25
329
                    # this is just prototype, working only with Fighters
330
                    quantity = int(math.ceil(temp_mp / float(one_fighter_mp)))
331
                    if quantity == 0:
332
                        continue
333
                    ships_left, mil_pwrSend = tool.orderFromSystem(self.data, self.client, self.db,
334
                        {self.designs["fighter"]:quantity}, temp_id, Const.FLACTION_MOVE, system_id, None)
335
                    mil_pwr += mil_pwrSend
336
                    self.data.myMPPerSystem[temp_id] -= mil_pwrSend
337
                    if mil_pwr > 0: break
338
339
    def _return_strays(self):
340
        for fleetID in self.data.idleFleets:
341
            fleet = self.db[fleetID]
342
            # fleets orbiting in systems not belonging to the self.player
343
            if fleet.orbiting and fleet.orbiting not in self.data.mySystems:
344
                nearest = tool.findNearest(self.db, fleet, self.data.mySystems, 99999, 1)
345
                if len(nearest):
346
                    targetID = nearest[0]
347
                    tool.orderFleet(self.client, self.db, fleetID, Const.FLACTION_MOVE, targetID, None)
348
349
    def defense_manager(self):
350
        self._help_system()
351
        self._return_strays()
352
353
    def economy_manager(self):
354
        self._empire_manager()
355
        self._planet_manager()
356
        self._expansion_manager()
357
        self._upgrade_manager()
358
359
    def run(self):
360
        self._ship_design_manager() # this fills self.designs, needs to go first
361
        top_prio_tech = [Rules.Tech.OUTPOST1,
362
                         Rules.Tech.GOVCENTER1,
363
                         Rules.Tech.FACTORY1,
364
                         Rules.Tech.RESCENTRE1,
365
                         Rules.Tech.FTLENG1,
366
                         ]
367
        mid_prio_tech = [Rules.Tech.SMALLHULL1,
368
                         Rules.Tech.SCOCKPIT1,
369
                         Rules.Tech.CANNON1,
370
                         Rules.Tech.UPGRADESHIPS,
371
                         ]
372
        low_prio_tech = [Rules.Tech.PWRPLANTOIL1,
373
                         Rules.Tech.FARM1,
374
                         Rules.Tech.COMSCAN1,
375
                         Rules.Tech.PWRPLANTSOL1,
376
                         Rules.Tech.SPACEPORT,
377
                         Rules.Tech.SCANNERMOD1,
378
                         Rules.Tech.SCANNERMOD2,
379
                         Rules.Tech.CONBOMB1,
380
                         Rules.Tech.HOLIDAYS1,
381
                         Rules.Tech.DEEPSPACESCAN,
382
                         ]
383
        ignored_tech = [Rules.Tech.BIONICTL2,
384
                        Rules.Tech.HUMANTL2,
385
                        Rules.Tech.ROBOTTL2,
386
                        ]
387
        tech_prio = {10: top_prio_tech,
388
                     3: mid_prio_tech,
389
                     1: low_prio_tech,
390
                     0: ignored_tech}
391
        self.research_manager(tech_prio)
392
        self.diplomacy_manager(friendly_types=[Const.T_PLAYER, Const.T_AIPLAYER, Const.T_AIRENPLAYER],
393
                               pacts=[Const.PACT_ALLOW_CIVILIAN_SHIPS, Const.PACT_ALLOW_TANKING,
394
                                      Const.PACT_MINOR_SCI_COOP, Const.PACT_MAJOR_SCI_COOP,
395
                                      Const.PACT_MINOR_CP_COOP, Const.PACT_MAJOR_CP_COOP])
396
        self.economy_manager()
397
        self.defense_manager()
398
        self.offense_manager()
399
400
401
def run(aclient):
402
    ai = Rebel(aclient)
403
    ai.run()
404
    aclient.saveDB()
405
406