await self.do(sg.train(VOIDRAY)) def find_target(self): if len(self.known_enemy_units) > 0: return random.choice(self.known_enemy_units) elif len(self.known_enemy_structures) > 0: return random.choice(self.known_enemy_structures) else: return self.enemy_start_locations[0] async def attack(self): # {UNIT: [n to fight, n to defend]} aggressive_units = {STALKER: [15, 5], VOIDRAY: [15, 5]} for UNIT in aggressive_units: if self.units(UNIT).amount >= aggressive_units[UNIT][0]: for s in self.units(UNIT).idle: await self.do(s.attack(self.find_target())) elif self.units(UNIT).amount >= aggressive_units[UNIT][1]: if len(self.known_enemy_units) > 0: for s in self.units(UNIT).idle: await self.do( s.attack(random.choice(self.known_enemy_units))) run_game( maps.get("AbyssalReefLE"), [Bot(Race.Protoss, SentdeBot()), Computer(Race.Terran, Difficulty.Hard)], realtime=False)
await self.build(PYLON, near=nexuses.first) """Build assimilators wherever we can build them closest""" async def build_assimilators(self): for nexus in self.units(NEXUS).ready: vespenes = self.state.vespene_geyser.closer_than(15.0, nexus) for vespene in vespenes: if not self.can_afford(ASSIMILATOR): break worker = self.select_build_worker(vespene.position) if worker is None: break # if we can't find a close assim, grab a worker that will build it if not self.units(ASSIMILATOR).closer_than(1.0, vespene).exists: await self.do(worker.build(ASSIMILATOR, vespene)) """Logic for expanding""" async def expand(self): if self.units(NEXUS).amount < 3 and self.can_afford(NEXUS): await self.expand_now() run_game( maps.get("AbyssalReefLE"), [Bot(Race.Protoss, JanusBot()), Computer(Race.Terran, Difficulty.Easy)], realtime=False)
from sc2.player import Bot, Computer, Human import random # Load bot from Overmind import Overmind bot = Bot(Race.Zerg, Overmind()) # Start game if __name__ == '__main__': if "--LadderServer" in sys.argv: # Ladder game started by LadderManager print("Starting ladder game...") run_ladder_game(bot) else: # Local game print("Starting local game...") map_name = random.choice(["CatalystLE"]) #map_name = random.choice(["ProximaStationLE", "NewkirkPrecinctTE", "OdysseyLE", "MechDepotLE", "AscensiontoAiurLE", "BelShirVestigeLE"]) #map_name = "(2)16-BitLE" sc2.run_game( sc2.maps.get(map_name), [ #Human(Race.Terran), bot, Computer(Race.Random, Difficulty.VeryHard) # CheatInsane VeryHard ], realtime=False, save_replay_as="Example.SC2Replay")
if self.can_afford(SPINECRAWLER): await self.build(SPINECRAWLER, near=self.townhalls.random.position.towards( self.game_info.map_center, 10)) if self.can_afford(SPORECRAWLER): await self.build(SPORECRAWLER, near=self.townhalls.random.position.towards( self.game_info.map_center, 10)) #runs the actual game run_game( maps.get("AbyssalReefLE"), [ #Human(Race.Random), Bot(Race.Zerg, HydraliskBrood()), Computer(Race.Random, Difficulty.Hard) ], realtime=True, save_replay_as="HydraliskBrood_vs_VeryHard.SC2Replay") #Computer.Difficulty: #VeryEasy, #Easy, #Medium, #MediumHard, #Hard, #Harder, #VeryHard, #CheatVision, #CheatMoney,
import sc2, sys from __init__ import run_ladder_game from sc2 import Race, Difficulty from sc2.player import Bot, Computer # Load bot from PVPBot import PVPBot bot = Bot(Race.Protoss, PVPBot()) anotherBot = Bot(Race.Protoss, PVPBot()) # Start game if __name__ == '__main__': if "--LadderServer" in sys.argv: # Ladder game started by LadderManager print("Starting ladder game...") result, opponentid = run_ladder_game(bot) print(result, " against opponent ", opponentid) else: # Local game print("Starting local game...") sc2.run_game( sc2.maps.get("BelShirVestigeLE"), [ bot, Computer(Race.Protoss, Difficulty.VeryHard) #anotherBot AscensiontoAiurLE AbyssalReefLE BelShirVestigeLE ], realtime=True)
REFINERY).amount < 4 and not self.already_pending( REFINERY): try: vgs = self.state.vespene_geyser.closer_than(20.0, cc) for vg in vgs: if self.units(REFINERY).closer_than(1.0, vg).exists: break worker = self.select_build_worker(vg.position) await self.do(worker.build(REFINERY, vg)) except Exception as e: pass async def build_scv(self): if self.units(SCV).amount <= MAX_WORKERS: for cc in self.units(COMMANDCENTER).ready.noqueue: if self.can_afford(SCV) and not self.already_pending(SCV): await self.do(cc.train(SCV)) async def build_supply_depot(self): SD = self.units(COMMANDCENTER) if self.supply_used > 0.7 * self.supply_cap: if self.can_afford( SUPPLYDEPOT) and not self.already_pending(SUPPLYDEPOT): await self.build(SUPPLYDEPOT, near=SD.first.position.towards( self.game_info.map_center, 4)) run_game(maps.get("AbyssalReefLE"), [Bot(Race.Terran, NN()), Computer(Race.Terran, Difficulty.Easy)], realtime=True)
# type: ignore import random from sc2 import run_game, maps, Race, Difficulty from sc2.player import Bot, Computer from bot.main import Botto if __name__ == "__main__": bot = Bot(Race.Zerg, Botto()) run_game( random.choice(maps.get()), [bot, Computer(Race.Random, Difficulty.Hard)], realtime=False, step_time_limit=0.1, game_time_limit=(60 * 60), # Max match duration in seconds save_replay_as="latest.SC2Replay", )
import sc2 from sc2 import run_game, maps, Race, Difficulty from sc2.player import Bot, Computer class WorkerRushBot(sc2.BotAI): async def on_step(self, iteration): if iteration == 0: for worker in self.workers: await self.do(worker.attack(self.enemy_start_locations[0])) run_game(maps.get("Abyssal Reef LE"), [ Bot(Race.Zerg, WorkerRushBot()), Computer(Race.Protoss, Difficulty.Medium) ], realtime=False)
import sc2 from sc2 import run_game, maps, Race, Difficulty from sc2.player import Bot, Computer class GatherMineralsBot(sc2.BotAI): async def on_step(self, iteration): await self.distribute_workers() run_game(maps.get("CyberForestLE"), [ Bot(Race.Zerg, GatherMineralsBot()), Computer(Race.Terran, Difficulty.Easy) ], realtime=True)
return random.choice(self.known_enemy_structures) else: return self.enemy_start_locations[0] """Attack: Logic: Down BELOW""" async def attack(self): # {UNIT: [n to fight, n to defend]} aggressive_units = {STALKER: [15, 5], VOIDRAY: [8, 3]} # For every stalker and then voidray # for UNIT in aggressive_units: # If we have more UNITs than what is specified for fight and defend, find a target and attack # if self.units(UNIT).amount > aggressive_units[UNIT][ 0] and self.units(UNIT).amount > aggressive_units[UNIT][1]: for s in self.units(UNIT).idle: await self.do(s.attack(self.find_target(self.state))) # If we have more than the defend value and we know some enemy unit locations, attack a random enemy # elif self.units(UNIT).amount > aggressive_units[UNIT][1]: if len(self.known_enemy_units) > 0: for s in self.units(UNIT).idle: await self.do( s.attack(random.choice(self.known_enemy_units))) run_game(maps.get(map_name), [Bot(race, MitchyBot()), Computer(enemy_race, enemy_difficulty)], realtime=realtime_condition)
from constructorAgent import ConstructorAgent from militarAgent import MilitarAgent from explorationAgent import ExplorationAgent from upgradeAgent import UpgradeAgent class MainAgent(sc2.BotAI): def __init__(self): self.ITERATIONS_PER_MINUTE = 165 self.MAX_WORKERS = 66 self.workerAgent = WorkerAgent(self) self.constructorAgent = ConstructorAgent(self) self.militarAgent = MilitarAgent(self) self.explorationAgent = ExplorationAgent(self) self.upgradeAgent = UpgradeAgent(self) self.iteration = 0 async def on_step(self, iteration): self.iteration = iteration await self.workerAgent.on_step(iteration) await self.constructorAgent.on_step(iteration) await self.explorationAgent.on_step(iteration) await self.militarAgent.on_step(iteration) await self.upgradeAgent.on_step(iteration) run_game( maps.get("AcropolisLE"), [Bot(Race.Protoss, MainAgent()), Computer(Race.Zerg, Difficulty.Hard)], realtime=False)
#realtime=true -> hra běží v reálném čase; false-> hra běží rychle #run_game(maps.get("CatalystLE"), [Bot(Race.Zerg, SrBotZerg()),Bot(Race.Terran, SrBoTerran())], realtime=False) #Muj Zerg vs muj Terran #run_game(maps.get("CatalystLE"), [Human(Race.Terran),Bot(Race.Terran, SrBoTerran())], realtime=True) #Hráč Terran vs muj Terran #run_game(maps.get("CatalystLE"), [Human(Race.Terran),Bot(Race.Zerg, SrBotZerg())], realtime=True) #Hráč Terran vs muj Zerg for i in range(number_of_games): print("-- Hra "+str(i+1)+" z "+str(number_of_games)+" --") time.sleep(5) #aby se stihla ukončit pposlední hra (nemuzou byt 2 instance hry zapnute najednou) if(DEBUG_SHOWGAME): if(i%3==0): result = run_game(maps.get("CatalystLE"), [Bot(Race.Terran, SrBoTerran(0)),Computer(Race.Zerg, Difficulty.Easy)], realtime=False) elif(i%3==1): result = run_game(maps.get("CatalystLE"), [Bot(Race.Terran, SrBoTerran(0)),Computer(Race.Zerg, Difficulty.Easy)], realtime=False) elif(i%3==2): result = run_game(maps.get("CatalystLE"), [Bot(Race.Terran, SrBoTerran(0)),Computer(Race.Zerg, Difficulty.Easy)], realtime=False) print("HRA SKONCILA : "+str(result)) else: #---------------CTU------------
def main(): sc2.run_game(sc2.maps.get("Abyssal Reef LE"), [ Bot(Race.Terran, ScoutBot()), Computer(Race.Protoss, Difficulty.Easy) ], realtime=False)
for enemy_building in self.known_enemy_structures: pos = enemy_building.position if enemy_building.name.lower() not in main_base_names: cv2.circle(game_data, (int(pos[0]), int(pos[1])), 5, (0, 0, 255), 1) else: cv2.circle(game_data, (int(pos[0]), int(pos[1])), 15, (0, 0, 255), 1) for enemy_unit in self.known_enemy_units: if not enemy_unit.is_structure: worker_names = ["probe", "scv", "drone"] pos = enemy_unit.position if enemy_unit.name.lower() in worker_names: cv2.circle(game_data, (int(pos[0]), int(pos[1])), 1, (0, 0, 255), 1) else: cv2.circle(game_data, (int(pos[0]), int(pos[1])), 3, (0, 0, 255), 1) self.flipped = cv2.flip(game_data, 0) resized = cv2.resize(self.flipped, dsize=None, fx=2, fy=2) cv2.imshow('Intel', resized) cv2.waitKey(1) run_game(maps.get("(2)LostandFoundLE"), [Bot(Race.Zerg, sc2Bot()), Computer(Race.Zerg, Difficulty.Hard)], realtime=True)
import sc2, sys from __init__ import run_ladder_game from sc2 import Race, Difficulty from sc2.player import Bot, Computer # Load bot from example_bot import ExampleBot bot = Bot(Race.Random, ExampleBot()) # Start game if __name__ == '__main__': if "--LadderServer" in sys.argv: # Ladder game started by LadderManager print("Starting ladder game...") run_ladder_game(bot) else: # Local game print("Starting local game...") sc2.run_game(sc2.maps.get("Abyssal Reef LE"), [ bot, Computer(Race.Protoss, Difficulty.VeryHard) ], realtime=True)
################################################# elif choice == 1: #attack_unit_closest_nexus if len(self.known_enemy_units) > 0: target = self.known_enemy_units.closest_to( random.choice(self.units(NEXUS))) elif choice == 2: #attack enemy structures if len(self.known_enemy_structures) > 0: target = random.choice(self.known_enemy_structures) elif choice == 3: #attack_enemy_start target = self.enemy_start_locations[0] if target: for vr in self.units(VOIDRAY).idle: await self.do(vr.attack(target)) y = np.zeros(4) y[choice] = 1 self.train_data.append([y, self.flipped]) run_game(maps.get("AbyssalReefLE"), [ Bot(Race.Protoss, SentdeBot(use_model=True)), Computer(Race.Protoss, Difficulty.Medium), ], realtime=False)
import sys from os import path sys.path.append(path.join(path.dirname(__file__), "..")) import sc2 from sc2 import Race, Difficulty from sc2.player import Bot, Computer from Main import RoachRush bot = Bot(Race.Zerg, RoachRush()) # Start game if __name__ == "__main__": sc2.run_game( sc2.maps.get("AcolyteLE"), [ bot, Computer(Race.Zerg, Difficulty.Hard), ], realtime=False, )
def main(): sc2.run_game(sc2.maps.get("Abyssal Reef LE"), [ Bot(Race.Protoss, ThreebaseVoidrayBot()), Computer(Race.Protoss, Difficulty.Easy) ], realtime=False)
self.known_enemy_units ) > 0 and not u.type_id == UnitTypeId.PROBE and not u.is_structure: await self.do( u.attack(random.choice(self.known_enemy_units))) async def build_cannons(self): if self.units(UnitTypeId.FORGE).exists: for n in self.units(UnitTypeId.NEXUS): pylon = self.units(UnitTypeId.PYLON).random if self.can_afford( UnitTypeId.PHOTONCANNON) and not self.already_pending( UnitTypeId.PHOTONCANNON): if self.units(UnitTypeId.PHOTONCANNON).closer_than( n.radar_range, n).amount < 3: await self.build(UnitTypeId.PHOTONCANNON, near=pylon) def seek_enemy(self, state): if len(self.known_enemy_units) > 0: return random.choice(self.known_enemy_units) elif len(self.known_enemy_structures) > 0: return random.choice(self.known_enemy_structures) else: return self.enemy_start_locations[0] run_game(maps.get("AbyssalReefLE"), [ Bot(Race.Protoss, GrandeBot()), Computer(Race.Protoss, Difficulty.Medium) ], realtime=True)
if x < 0: x = 0 elif x > self.game_info.map_size[0]: x = self.game_info.map_size[0] if y < 0: y = 0 elif y > self.game_info.map_size[1]: y = self.game_info.map_size[1] return position.Point2(position.Pointlike((x, y))) def get_bases(self): hatches = len(self.units(HATCHERY).ready) lairs = len(self.units(LAIR)) hives = len(self.units(HIVE)) return (hatches + lairs + hives, hatches, lairs, hives) def select_target(self): if self.known_enemy_structures.exists: return random.choice(self.known_enemy_structures).position return self.enemy_start_locations[0] run_game(maps.get('RedshiftLE'), [Bot(Race.Zerg, bot()), Computer(Race.Zerg, Difficulty.Easy)], realtime=speed)
def main(): sc2.run_game(sc2.maps.get("Marine Control v1.4"), [ Bot(Race.Terran, MarineSplitChallenge()), ], realtime=True, save_replay_as="Example.SC2Replay")
game_map = args.map_name # bot 초기화 bots = list() for bot_path in (args.bot1, args.bot2): try: if len(bot_path) == 4 and bot_path.lower().startswith('com'): # bot 경로 시작이 com으로 시작하면 기본 AI를 사용함 level = int(bot_path[3]) # 4번째 문자는 봇의 난이도를 뜻함 # 예) com7 -> 기본 AI 난이도 7 # 난이도는 1~10까지 있음 assert 1 <= level <= 10 bot = Computer(Race.Terran, Difficulty(level)) else: # 일반 bot 임포트 module, name = bot_path.rsplit('.', 1) bot_cls = getattr(importlib.import_module(module), name) # debug 인자를 반드시 전달함 bot_ai = bot_cls(debug=args.debug) bot = Bot(Race.Terran, bot_ai) bots.append(bot) except ImportError: import traceback logger.error(f"bot 클래스를 임포트 할 수 없음: {bot_path}") traceback.print_exc() exit(1) result = sc2.run_game(game_map, bots, realtime=args.realtime) print(result)
from scv import SCV_AI import sc2 from sc2 import units from sc2.bot_ai import BotAI from sc2.player import Bot, Computer from sc2.ids.unit_typeid import UnitTypeId from scv import SCV_AI from commandCenter import commandCenter_AI CC = commandCenter_AI SCV = SCV_AI sc2.run_game( sc2.maps.get("(2)CatalystLE"), [ Bot(sc2.Race.Terran, SCV_AI()), Computer(sc2.Race.Zerg, sc2.Difficulty.Easy) ], realtime=False, )
def main(): sc2.run_game(sc2.maps.get("AcropolisLE"), [ Bot(Race.Terran, BotDaGalera()), Computer(Race.Zerg, Difficulty.Hard) ], realtime=False)
def main(): sc2.run_game(sc2.maps.get("Newkirk Precinct TE"), [ Bot(Race.Zerg, BanelingBustBot()), Computer(Race.Terran, Difficulty.VeryHard) ], realtime=False)
#consider adding units to tag with defender army = self.units(ZEALOT) | self.units(STALKER) | self.units( IMMORTAL) enemyUnits = self.known_enemy_units nexuses = self.units(NEXUS).exists max_difference = math.pi dangerRadius = nexuses.position.towards_with_random_angle( nexuses.position, random.randrange(0, 15)) #tell units to attack enemies in range of defensible pylons for unit in army: if enemyUnits(near=dangerRadius): in_range_enemies = enemy_fighters.in_attack_range_of(unit) if in_range_enemies: lowest_hp = min(in_range_enemies, key=lambda e: e.health + e.shield) self.actions.append(unit.attack(lowest_hp)) else: self.actions.append( unit.move(enemy_fighters.closest_to(unit))) else: self.actions.append(unit.move(dangerRadius)) run_game( maps.get("(2)AcidPlantLE"), [ Bot(Race.Protoss, lewis()), Computer(Race.Zerg, Difficulty.VeryHard) #Bot(Race.Protoss, lewis2()) ], realtime=False)
#------------------------------------------------------------------------------- # Name: Starcraft # Purpose: # # Author: Felicity # # Created: 13/02/2019 # Copyright: (c) Felicity 2019 # Licence: <your licence> #------------------------------------------------------------------------------- import sc2 from sc2 import run_game,maps, Race , Difficulty from sc2.player import Bot,Computer,Human,Observer from Yeeto_mainV04 import YeetoBot run_game(maps.get("AutomatonLE"), [ Bot(Race.Zerg,YeetoBot(),"YeetoBot"), Computer(Race.Terran, Difficulty.Easy) ], realtime=True)
REFINERY): try: vgs = self.state.vespene_geyser.closer_than(20.0, cc) for vg in vgs: if self.units(REFINERY).closer_than(1.0, vg).exists: break worker = self.select_build_worker(vg.position) await self.do(worker.build(REFINERY, vg)) except Exception as e: pass async def build_scv(self): if self.units(SCV).amount <= MAX_WORKERS: for cc in self.units(COMMANDCENTER).ready.noqueue: if self.can_afford(SCV) and not self.already_pending(SCV): await self.do(cc.train(SCV)) async def build_supply_depot(self): SD = self.units(COMMANDCENTER) if self.supply_used > 0.7 * self.supply_cap: if self.can_afford( SUPPLYDEPOT) and not self.already_pending(SUPPLYDEPOT): await self.build(SUPPLYDEPOT, near=SD.first.position.towards( self.main_base_ramp.top_center, 4)) run_game(maps.get("AbyssalReefLE"), [Bot(Race.Terran, NN()), Computer(Race.Terran, Difficulty.Medium)], realtime=False)
def main(): maps = [ "16-BitLE", "2000AtmospheresAIE", "AbiogenesisLE", "AbyssalReefLE", "AcidPlantLE", "AcolyteLE", "AcropolisLE", "Artana", "AscensiontoAiurLE", "AutomatonLE", "BackwaterLE", "Bandwidth", "BattleontheBoardwalkLE", "BelShirVestigeLE", "BlackburnAIE", "BlackpinkLE", "BlueshiftLE", "CactusValleyLE", "CatalystLE", "CeruleanFallLE", "CrystalCavern", "CyberForestLE", "DarknessSanctuaryLE", "DeathAura506", "DeathAuraLE", "DefendersLandingLE", "DigitalFrontier", "DiscoBloodbathLE", "DreamcatcherLE", "EastwatchLE", "Ephemeron", "EphemeronLE", "EternalEmpire506", "EternalEmpireLE", "EverDream506", "EverDreamLE", "FractureLE", "FrostLE", "GoldenWall506", "GoldenWallLE", "HonorgroundsLE", "IceandChrome506", "IceandChromeLE", "InterloperLE", "JagannathaAIE", "KairosJunctionLE", "KingsCoveLE", "LostandFoundLE", "LightshadeAIE", "MechDepotLE", "NeonVioletSquareLE", "NewkirkPrecinctTE", "NewRepugnancyLE", "NightshadeLE", "OdysseyLE", "OldSunshine", "OxideAIE", "PaladinoTerminalLE", "ParaSiteLE", "PillarsofGold506", "PillarsofGoldLE", "PortAleksanderLE", "PrimusQ9", "ProximaStationLE", "RedshiftLE", "Reminiscence", "RomanticideAIE", "Sanglune", "SequencerLE", "SimulacrumLE", "Submarine506", "SubmarineLE", # "StasisLE", Commented out because it has uneven number of expansions, and wasn't used in the ladder pool anyway "TheTimelessVoid", "ThunderbirdLE", "Treachery", "Triton", "Urzagol", "WintersGateLE", "WorldofSleepersLE", "YearZeroLE", "ZenLE", ] for map_ in maps: try: bot = ExporterBot() bot.map_name = map_ file_path = bot.get_pickle_file_path() if os.path.isfile(file_path): logger.warning( f"Pickle file for map {map_} was already generated. Skipping. If you wish to re-generate files, please remove them first." ) continue sc2.run_game( sc2.maps.get(map_), [Bot(Race.Terran, bot), Computer(Race.Zerg, Difficulty.Easy)], realtime=False) except ProtocolError: # ProtocolError appears after a leave game request pass except Exception as e: logger.warning( f"Map {map_} could not be found, so pickle files for that map could not be generated. Error: {e}" )
async def expand(self): try: if self.units(NEXUS).amount < self.nexus_limit and self.can_afford(NEXUS): await self.expand_now() except Exception as e: print(str(e)) if __name__ == "__main__": """ parser = argparse.ArgumentParser(description = "The Squinn Bot") parser.add_argument("--race", choices = ["protoss", "zerg", "terran", "random"], default = "random", help = "Specify the race [DEFAULT: random]") parser.add_argument("--seed", type = int, default = 42, help = "Random seed [DEFAULT: 42].") parser.add_argument("--headless", action = "store_true") args = vars(parser.parse_args()) np.random.seed(args['seed']) races = {"protoss": Race.Protoss, "terran": Race.Terran, "zerg": Race.Zerg} if args['race'] == "random": race = np.random.choice(list(races.values())) else: race = races[args['race']] """ run_game(maps.get("AbyssalReefLE"), [ Bot(Race.Protoss, SquinnBot()), Computer(Race.Terran, Difficulty.Easy) ], realtime = True)
def main(): sc2.run_game(sc2.maps.get("Empty128"), [Bot(Race.Terran, TestBot()), Bot(Race.Zerg, EmptyBot())], realtime=False)