Building a StarCraft II AI Bot with DeepMind's pysc2 in Python
This article provides a step‑by‑step guide, complete with Python code examples, for creating a Protoss AI bot using DeepMind's pysc2 library to mine resources, construct buildings, train units, implement scouting, and execute attack strategies against increasingly difficult computer opponents in StarCraft II.
The article introduces DeepMind's open‑source StarCraft II learning environment (pysc2) and shows how to set up a Python 3.6 environment with the required packages and map files.
Preparation : Install sc2 and import necessary modules, then define a bot class inheriting from sc2.BotAI .
import sc2
from sc2 import run_game, maps, Race, Difficulty
from sc2.player import Bot, Computer
from sc2.constants import *
class SentdeBot(sc2.BotAI):
async def on_step(self, iteration: int):
await self.distribute_workers()
await self.build_workers()
await self.build_pylons()
await self.build_assimilators()
await self.expand()
await self.offensive_force_buildings()
await self.build_offensive_force()
await self.attack()Mining : Implement a method to train probes and build pylons when supply is low.
async def build_workers(self):
for nexus in self.units(UnitTypeId.NEXUS).ready.noqueue:
if self.can_afford(UnitTypeId.PROBE):
await self.do(nexus.train(UnitTypeId.PROBE))
async def build_pylons(self):
if self.supply_left < 5 and not self.already_pending(UnitTypeId.PYLON):
nexus = self.units(UnitTypeId.NEXUS).ready.first
if self.can_afford(UnitTypeId.PYLON):
await self.build(UnitTypeId.PYLON, near=nexus)Building Army : Add logic to construct gateways, cybernetics cores, stargates, and train stalkers or void rays based on unit counts.
async def offensive_force_buildings(self):
if self.units(UnitTypeId.PYLON).ready.exists:
pylon = self.units(UnitTypeId.PYLON).ready.random
if self.units(UnitTypeId.GATEWAY).ready.exists and not self.units(UnitTypeId.CYBERNETICSCORE):
if self.can_afford(UnitTypeId.CYBERNETICSCORE):
await self.build(UnitTypeId.CYBERNETICSCORE, near=pylon)
elif len(self.units(UnitTypeId.GATEWAY)) < 1:
if self.can_afford(UnitTypeId.GATEWAY):
await self.build(UnitTypeId.GATEWAY, near=pylon)
if self.units(UnitTypeId.CYBERNETICSCORE).ready.exists and len(self.units(UnitTypeId.STARGATE)) < 1:
if self.can_afford(UnitTypeId.STARGATE):
await self.build(UnitTypeId.STARGATE, near=pylon)Attack Logic : Define aggressive unit thresholds and issue attack commands when enough units are available, otherwise defend against nearby enemies.
async def attack(self):
aggressive_units = {UnitTypeId.STALKER: [15, 5], UnitTypeId.VOIDRAY: [8, 3]}
for unit_type, (fight, defend) in aggressive_units.items():
if self.units(unit_type).amount > fight:
for s in self.units(unit_type).idle:
await self.do(s.attack(self.find_target(self.state)))
elif self.units(unit_type).amount > defend and self.known_enemy_units:
for s in self.units(unit_type).idle:
await self.do(s.attack(random.choice(self.known_enemy_units)))Advanced Features : The bot collects map data into a NumPy array, visualizes unit positions with OpenCV, and implements a scouting routine using Observers and a robotics facility.
async def intel(self):
game_data = np.zeros((self.game_info.map_size[1], self.game_info.map_size[0], 3), np.uint8)
# draw units, structures, and enemy positions using cv2.circle
flipped = cv2.flip(game_data, 0)
resized = cv2.resize(flipped, None, fx=2, fy=2)
cv2.imshow('Intel', resized)
cv2.waitKey(1)Finally, the article shows how to launch the bot against Easy, Medium, Hard, and Very Hard computer opponents using run_game with the appropriate Difficulty setting.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.