Find the explanation in https://xcran.blogspot.com/2022/03/0-starcraft-ii-python-bot-introduction.html
import sc2from sc2 import run_game, maps, Race, Difficultyfrom sc2.player import Bot, Computerfrom sc2.ids.unit_typeid import *
class AlanBot(sc2.BotAI): async def on_step(self, iteration): await self.buildWorkers() await self.distribute_workers() await self.buildRefineries() await self.buildStructure('supplydepot', 2000) await self.buildStructure('barracks', 4) await self.buildOffensiveUnit('marine', 'barracks', 27) if self.units(UnitTypeId.MARINE).amount > 17: await self.move('marine', True) else: await self.move('marine', False)
async def buildWorkers(self): for commandcenter in self.units(UnitTypeId.COMMANDCENTER).ready.noqueue: if self.can_afford(UnitTypeId.SCV) and self.workers.amount < self.units(UnitTypeId.COMMANDCENTER).amount * 14 + 4: await self.do(commandcenter.train(UnitTypeId.SCV))
async def buildRefineries(self): for commandcenter in self.units(UnitTypeId.COMMANDCENTER).ready: vespenes = self.state.vespene_geyser.closer_than( 18.0, commandcenter) for vespene in vespenes: if not self.can_afford(UnitTypeId.REFINERY): break worker = self.select_build_worker(vespene.position) if worker is None: break if not self.units(UnitTypeId.REFINERY).closer_than(1.0, vespene).exists: await self.do(worker.build(UnitTypeId.REFINERY, vespene))
async def buildStructure(self, structureName, amount): if self.units(UnitTypeId.COMMANDCENTER).ready.exists: commandCenter = self.units(UnitTypeId.COMMANDCENTER).ready.random workers = self.workers.gathering
nearCC = await self.find_placement(UnitTypeId.SUPPLYDEPOT, commandCenter.position, placement_step=2)
if structureName == 'supplydepot': if self.supply_left < 6 and self.can_afford(UnitTypeId.SUPPLYDEPOT): if workers: w = workers.furthest_to(workers.center) if nearCC: await self.do(w.build(UnitTypeId.SUPPLYDEPOT, nearCC))
if structureName == 'barracks': if self.units.of_type([UnitTypeId.SUPPLYDEPOT, UnitTypeId.SUPPLYDEPOTLOWERED, UnitTypeId.SUPPLYDEPOTDROP]).ready.exists \ and self.units(UnitTypeId.BARRACKS).amount + self.already_pending(UnitTypeId.BARRACKS) < amount \ and self.can_afford(UnitTypeId.BARRACKS): if workers: w = workers.furthest_to(workers.center) if nearCC: await self.do(w.build(UnitTypeId.BARRACKS, nearCC))
async def buildOffensiveUnit(self, unitName, structureName, maxAmount): structure = self.unitSelector(structureName) unit = self.unitSelector(unitName) if self.units(structure).ready.exists: for struct in self.units(structure).ready.noqueue: if self.can_afford(unit) and self.supply_left > 0 and self.units(unit).amount < maxAmount: await self.do(struct.train(unit))
run_game(maps.get("AbyssalReefLE"), [ Bot(Race.Terran, AlanBot()), Computer(Race.Zerg, Difficulty.Medium)], realtime=True)