Example #1
0
def main():
    sc2.run_game(sc2.maps.get("(2)CatalystLE"), [
        Bot(Race.Protoss, WarpGateBot()),
        Computer(Race.Protoss, Difficulty.VeryHard)
    ],
                 realtime=False)
Example #2
0
from sc2 import Race, Difficulty
from sc2.player import Bot, Computer
import os

# Load bot
from timeout_bot import timeout_bot
bot = Bot(Race.Terran, timeout_bot())

# Start game
try:
    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("AutomatonLE"),
                [bot, Computer(Race.Protoss, Difficulty.CheatInsane)],
                realtime=False)
except Exception as e:
    with open(
            os.path.join(os.path.dirname(os.path.abspath(__file__)),
                         "data/errors.txt"), "a+") as f:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        f.write(str(exc_type) + " " + fname + " " + exc_tb.tb_lineno)
Example #3
0
    async def build_supplydepot(self):
        if self.supply_left < 8 and not self.already_pending(SUPPLYDEPOT) and self.can_afford(SUPPLYDEPOT):
            await self.build(SUPPLYDEPOT, near=self.units(COMMANDCENTER).first)

    async def build_barracks(self):
        if self.can_afford(BARRACKS) and self.units(BARRACKS).amount < 4:
            await self.build(BARRACKS, near=self.units(COMMANDCENTER).first)

    async def train_marines(self):
        for rax in self.units(BARRACKS):
            if rax.is_ready and rax.noqueue:
                if self.can_afford(MARINE) and self.units(MARINE).amount < 50:
                    await self.do(rax.train(MARINE))

    async def attack(self):
        if self.units(MARINE).amount > 12:
            if len(self.known_enemy_units) > 0:
                for m in self.units(MARINE).idle:
                    await self.do(m.attack(random.choice(self.known_enemy_units)))

        if self.units(MARINE).amount > 10:
            for m in self.units(MARINE).idle:
                await self.do(m.attack(self.enemy_start_locations[0]))

run_game(maps.get("AbyssalReefLE"),[
    Bot(Race.Terran, CAPSbot()),
    Computer(Race.Terran, Difficulty.VeryHard)
    ], realtime=False)

def main():
    run_game(maps.get("EphemeronLE"), [
        Bot(Race.Protoss, SentdeBot()),
        Computer(Race.Zerg, Difficulty.Harder)], realtime=False
        ,save_replay_as="eight_gateway_rush.SC2Replay"
        )  # realtime设为False可以加速
Example #5
0
def main():
    sc2.run_game(sc2.maps.get("AbyssalReefLE"), [
        Bot(Race.Protoss, CannonRushBot(), name="CheeseCannon"),
        Computer(Race.Protoss, Difficulty.Medium)
    ],
                 realtime=True)
Example #6
0
    async def use_stim_pack(self):
        for marine in self.units(UnitTypeId.MARINE).ready:
            abilities = await self.get_available_abilities(marine)
            try:
                if marine.is_attacking and AbilityId.EFFECT_STIM_MARINE in abilities \
                        and marine.health_percentage >= 0.5 and marine.weapon_cooldown:
                    await self.do(marine(AbilityId.EFFECT_STIM_MARINE))
            except Exception:
                continue


if __name__ == '__main__':
    from examples.terran.proxy_rax import ProxyRaxBot
    from Sentdex_tuto.t6_defeated_hard_AI import SentdeBot

    sc2.run_game(sc2.maps.get("AbyssalReefLE"), [
        Bot(Race.Terran, JarexTerran(use_model=False, human_control=False, debug=True, take_training_data=False),
            name=JarexTerran.BOTNAME),
        Computer(Race.Zerg, Difficulty.Hard)
    ], realtime=False)

    # sc2.run_game(sc2.maps.get("AbyssalReefLE"), [
    #     Bot(Race.Terran, JarexTerran()),
    #     Bot(Race.Protoss, SentdeBot())
    # ], realtime=False)

    # sc2.run_game(sc2.maps.get("AbyssalReefLE"), [
    #     Bot(Race.Terran, JarexTerran()),
    #     Bot(Race.Terran, JarexTerran())
    # ], realtime=False)
Example #7
0
                                 self.game_info.map_center, 4))
            if self.can_afford(SHIELDBATTERY) and self.units(
                    PHOTONCANNON).exists:
                await self.build(SHIELDBATTERY,
                                 near=pylon.position.towards(
                                     self.game_info.map_center, -2))


#runs the actual game
#run_game(maps.get("AbyssalReefLE"), [
run_game(
    maps.get("AbyssalReefLE"),
    [
        #Human(Race.Terran),
        Bot(Race.Protoss, VoidRaySpamBot()),
        Computer(Race.Random, Difficulty.VeryHard)
    ],
    realtime=True,
    save_replay_as="VoidRaySpam_vs_VeryHard.SC2Replay")

#Computer.Difficulty:
#VeryEasy,
#Easy,
#Medium,
#MediumHard,
#Hard,
#Harder,
#VeryHard,
#CheatVision,
#CheatMoney,
#CheatInsane
Example #8
0
from managers.MilitaryManager import MilitaryManager
from managers.ResourcesManager import ResourcesManager
from managers.ScoutingManager import ScoutingManager
from managers.StructureManager import StructureManager


class Scyther(sc2.BotAI):
    def __init__(self):
        super().__init__()
        self.managers = [
            ResourcesManager(self),
            StructureManager(self),
            ScoutingManager(self),
            MilitaryManager(self)
        ]

    async def on_start(self):
        for manager in self.managers:
            await manager.start()

    async def on_step(self, iteration: int):
        for manager in self.managers:
            await manager.update(iteration)


run_game(
    maps.get("AcropolisLE"),
    [Bot(Race.Protoss, Scyther()),
     Computer(Race.Zerg, Difficulty.Medium)],
    realtime=False)
Example #9
0
def main():
    sc2.run_game(sc2.maps.get("Abyssal Reef LE"), [
        Bot(Race.Protoss, LeaderBot()),
        Computer(Race.Terran, Difficulty.Medium)
    ],
                 realtime=False)
Example #10
0
                    [self.flipped.reshape([-1, 176, 200, 3])])
                choice = np.argmax(prediction[0])
            else:
                choice = random.randrange(0, 14)
                #   2. We here, have choise = 14
                #   8. Have choise = 8
            try:
                await self.choices[choice]()
                #   3. We here, have calling choices[14]() - in console it's self.do_nothing()
                #   9. Calling choices[8]() - in console it's self.build_pylon()
            except Exception as e:
                print(str(e))
            ###### NEW CHOICE HANDLING HERE #########
            ###### NEW CHOICE HANDLING HERE #########
            y = np.zeros(14)
            y[choice] = 1
            self.train_data.append([y, self.flipped])


#   MAIN BLOCK ENDS UP
#                   STOP

if True:
    run_game(
        maps.get("AbyssalReefLE"),
        [
            Bot(Race.Protoss, SentdeBot(use_model=False, title=1)),
            #Bot(Race.Protoss, SentdeBot(use_model=False, title=2)),
            Computer(Race.Protoss, Difficulty.Medium),
        ],
        realtime=False)
                    if barrack.add_on_tag not in tech_lab_tags:
                        # if we can afford it (enough minerals and vaspene gas).
                        if self.can_afford(BARRACKSTECHLAB):
                            # we build the tech_lab on the selected barrack
                            await self.do(barrack.build(BARRACKSTECHLAB))

    async def create_army(self):
        if self.units(BARRACKS).ready.exists:

            for barrack in self.units(BARRACKS).ready.noqueue:

                if self.can_afford(MARINE) and self.supply_left > 0:

                    await self.do(barrack.train(MARINE))


if __name__ == "__main__":

    # To run several instances just execute several time this code
    # ==> /!\ each instances multiply the processor needs and memory needs.
    # specify run speed at TRUE = normal speed and FAlSE = ultra fast speed.

    # to play against a bot, the human player must be player 1 and placed before the bot ! else it won't work
    # [Human(sc2.Race.Zerg), Bot(sc2.Race.Terran, MeatBot())]

    run_game(
        maps.get("AbyssalReefLE"),
        [Bot(Race.Terran, BotTerran()),
         Computer(Race.Zerg, Difficulty.Easy)],
        realtime=False)  # time in second : 1800sec = 30 min
Example #12
0
def run_episodes(episode_count, loop):
    try:
        print("run_episodes:" + str(episode_count))
        app.state[EPISODE] = 0
        app.state[REWARD] = 0

        set_sim_status(RUNNING)

        map = app.state[MAP]

        print("run_game starting...")

        asyncio.set_event_loop(loop)

        run_game(maps.get(map), [
            Bot(Race.Zerg, WorkerRushBot()),
            Computer(Race.Protoss, Difficulty.Medium)
        ],
                 realtime=False)

        print("run_game finished!")

        # for i in range(episode_count):
        #     if (app.state[STATUS][CODE] != RUNNING):
        #         break

        #     app.state[EPISODE] = i

        #     done = False
        #     last_reward = 0
        #     last_action = 0

        #     ob = env.reset()
        #     print("episode #" + str(i) + ": " + repr(ob))

        #     agent_context = agent_on_reset()

        #     step = 0
        #     while app.state[STATUS][CODE] == RUNNING:
        #         app.state[STEP] = step
        #         step += 1

        #         state = ob
        #         if (isinstance(ob, np.ndarray)):
        #             state = ob.tolist()
        #         elif (isinstance(ob, np.int64) or isinstance(ob, int)):
        #             state = (float(ob),)
        #         else:
        #             print("type of state`: " + repr(type(state)))

        #         app.state[OBSERVATION] = state

        #         on_step_result = agent_on_step(
        #             state, last_reward, last_action, done, agent_context)

        #         # print("on_step_result " + repr(on_step_result))

        #         if (app.state[STATUS][CODE] == ERROR):
        #             break

        #         # last_action = env.action_space.sample()
        #         last_action = on_step_result[ACTION]
        #         agent_context = on_step_result[CONTEXT]

        #         ob, last_reward, done, _ = env.step(last_action)
        #         app.state[REWARD] += last_reward

        #         if done:
        #             agent_on_step(ob, last_reward, last_action,
        #                           done, agent_context)
        #             print("- DONE!")
        #             break

        #         print("- step = " + str(step) + ", reward = " +
        #               str(last_reward) + ", ob = " + repr(ob))

        #         # Note there's no env.render() here. But the map still can open window and
        #         # render if asked by env.monitor: it calls env.render('rgb_array') to record video.
        #         # Video is not recorded every episode, see capped_cubic_video_schedule for details.

        #         # render = env.render('rgb_array')
        #         # print("- render " + repr(render))

        # status = app.state[STATUS]
        # if (status[CODE] != ERROR and status[CODE] != STOPPED):
        #     set_sim_status(ENDED)

    except Exception as e:
        print("exception: " + repr(e))
        set_sim_status(ERROR, [str(e)])
Example #13
0
                            await self.do(m.attack(target))
                    if self.units(MARINE).ready:
                        for mn in self.units(MARINE).idle:
                            await self.do(mn.attack(target))
                    if self.units(HELLION).ready:
                        for mn in self.units(HELLION).idle:
                            await self.do(mn.attack(target))

#   NOTES:
#           Both values: [[array_choise, self.flipped]]  -- should be in Numpy format
#           Also you should be saving in Numpy format
            self.train_data.append([array_choise, self.flipped])
            # print('\n', self.train_data)


############################################################################################
############################################################################################

# count = 0
# while count < 20:
# print('\n\n \t\t COUNT = {} \n\n'.format(count))
run_game(maps.get("AbyssalReefLE"),
         [Bot(Race.Terran, NN()),
          Computer(Race.Terran, Difficulty.Medium)],
         realtime=False)
# count += 1

# run_game(maps.get("AbyssalReefLE"), [
#         Bot(Race.Terran, NN()),
#         Computer(Race.Terran, Difficulty.Hard)
#     ], realtime=False)
Example #14
0
def main():
    sc2.run_game(sc2.maps.get("(2)CatalystLE"), [
        Bot(Race.Protoss, CannonRushBot()),
        Computer(Race.Protoss, Difficulty.Hard)
    ],
                 realtime=False)
Example #15
0
                    self.do_something_after = self.iteration + wait
                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(uti.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(uti.VOIDRAY).idle:
                        await self.do(vr.attack(target))

                y = np.zeros(4)
                y[choice] = 1
                print(y)
                self.train_data.append([y, self.flipped])
            print(len(self.train_data))


if __name__ == '__main__':
    run_game(
        maps.get("AcidPlantLE"),
        [Bot(Race.Protoss, StarBot()), Computer(Race.Terran, Difficulty.Medium)],
        realtime=False
    )
def main():
    sc2.run_game(
        sc2.maps.get("(2)CatalystLE"),
        [Bot(Race.Protoss, CannonRushBot(), name="CheeseCannon"), Computer(Race.Protoss, Difficulty.Medium)],
        realtime=False,
    )
Example #17
0
def main():
    sc2.run_game(sc2.maps.get("Abyssal Reef LE"), [
        Bot(Race.Terran, RampWallBot()),
        Computer(Race.Zerg, Difficulty.Hard)
    ],
                 realtime=False)
Example #18
0
def execute( bot: sc2.BotAI, race: Race, realtime = False, ):
	player_config = [
		# Human(Race.Zerg),
		Bot( race, bot ),
		Computer( Race.Terran, Difficulty.Medium )
	]
Example #19
0
def main():
    sc2.run_game(sc2.maps.get("Abyssal Reef LE"), [
        Bot(Race.Terran, SimpleBot()),
        Computer(Race.Random, Difficulty.Hard)
    ], realtime=False, game_time_limit=(20 * 60))
def main():
    sc2.run_game(sc2.maps.get("(2)CatalystLE"), [
        # Human(Race.Terran),
        Bot(Race.Terran, ProxyRaxBot()),
        Computer(Race.Zerg, Difficulty.Hard)
    ], realtime=False)
                    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)
def main():
    run_game(
        maps.get("Abyssal Reef LE"),
        [Bot(Race.Terran, MyBot()), Computer(Race.Protoss, Difficulty.Medium)],
        realtime=True,
    )
    async def expand(self):
        if self.units(NEXUS).amount < 3 and self.can_afford(NEXUS):
            await self.expand_now()
        ## best situation will be to detect a soldier's rush or knight's rush
        ## by the enemy and then decide how many nexuses to expand
        ## Goal of resource areas = 2

    async def offensive_force_buildings(self):
        if self.units(PYLON).ready.exists:
            pylon = self.units(PYLON).ready.random
            if self.units(GATEWAY).ready.exists:
                # either build a stalker or cyberneticscore
                if not self.units(CYBERNETICSCORE):
                    if self.can_afford(CYBERNETICSCORE) and not self.already_pending(CYBERNETICSCORE):
                        await self.build(CYBERNETICSCORE, near=pylon)
            else:
                if self.can_afford(GATEWAY) and not self.already_pending(GATEWAY):
                    await self.build(GATEWAY, near=pylon)

    async def build_offensive_force(self):
        # build stalkers and not too many units
        # workers might get in the way
        for gw in  self.units(GATEWAY).ready.noqueue:
            if self.can_afford(STALKER) and self.supply_left > 0:
                await self.do(gw.train(STALKER))

run_game(maps.get("AbyssalReefLE"), [Bot(Race.Protoss, SentdeBot()), Computer(Race.Terran, Difficulty.Easy)], realtime=False)

## error message not enough psi Construct additional pylons when  NEXUS amount < 3
Example #24
0
def main():
    sc2.run_game(
        sc2.maps.get("Abyssal Reef LE"),
        [Bot(Race.Protoss, MyBot()),
         Computer(Race.Protoss, Difficulty.Hard)],
        realtime=False)
Example #25
0
    async def build_offensive_force(self):
        for sg in self.units(STARGATE).ready.idle:
            if self.can_afford(VOIDRAY) and self.supply_left > 0:
                await self.do(sg.train(VOIDRAY))

    # 寻找目标
    def find_target(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]

    # 攻击
    async def attack(self):
        aggressive_units = {
            # STALKER: [15, 5],
            VOIDRAY: [8, 3]
        }
        for UNIT in aggressive_units:
            for s in self.units(UNIT).idle:
                await self.do(s.attack(self.find_target(self.state)))


run_game(
    maps.get("KingsCoveLE"),
    [Bot(Race.Protoss, SentdeBot()),
     Computer(Race.Terran, Difficulty.Hard)],
    realtime=False)
Example #26
0
    "bio": (lambda params: Bot(Race.Terran, BioBot())),
    "banshee": (lambda params: Bot(Race.Terran, Banshees())),

    # Random
    "weakworkerrush": (lambda params: Bot(Race.Random, WorkerRushBot())),

    # Debug
    "debugidle": (lambda params: Bot(Race.Protoss, IdleDummy())),
    "debugunits": (lambda params: Bot(Race.Zerg, DebugUnitsDummy())),
    "debugrestorepower": (lambda params: Bot(Race.Protoss, RestorePowerDummy())),
    "debuguseneural": (lambda params: Bot(Race.Zerg, UseNeuralParasiteDummy())),
    "debugdetectneural": (lambda params: Bot(Race.Protoss, DetectNeuralParasiteDummy())),

    # Built-in computer AIs
    "ai": (lambda params: Computer(races[index_check(params, 0, "random")],
                                   difficulty[index_check(params, 1, "veryhard")],
                                   builds[index_check(params, 2, "random")])),
}

races = {
    "protoss": Race.Protoss,
    "zerg": Race.Zerg,
    "terran": Race.Terran,
    "random": Race.Random,
}

builds = {
    "random": AIBuild.RandomBuild,
    "rush": AIBuild.Rush,
    "timing": AIBuild.Timing,
    "power": AIBuild.Power,
Example #27
0
def main():
    run_game(maps.get("AbyssalReefLE"), [
        Bot(Race.Protoss, BinaryBot()),
        Computer(Race.Terran, Difficulty.Hard)
    ],
             realtime=False)
Example #28
0
def main():
    """Determine build-order and start game"""

    self_race_string = race_to_string[self_race]
    enemy_race_string = race_to_string[enemy_race]

    folder = folder_buildorder + self_race_string + race_bot_separator + enemy_race_string + ending_folder + map_name_strategy + ending_folder
    path_strategy = folder + file_strategy

    # Logging based on: https://docs.python.org/3/howto/logging-cookbook.html
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    logger_strategy = logging.getLogger("sc2.strategy")

    loggers = [
        logging.getLogger("sc2.bot_ai"),
        logging.getLogger("sc2.controller"),
        logging.getLogger("sc2.main"),
        logging.getLogger("sc2.maps"),
        logging.getLogger("sc2.paths"),
        logging.getLogger("sc2.sc2process"),
        logging.getLogger("sc2.protocol"),
        logging.getLogger("root"),
        logging.getLogger("sc2.command"), logger_strategy,
        logging.getLogger("sc2.performance")
    ]

    for i in range(eval_number_games):

        print("Evaluation number: {0} of {1}".format(i + 1, eval_number_games))

        hash = get_buildorder_hash(path_strategy, method)

        path = folder + hash + ending_csv
        time_string = str(round(time.time()))
        id = map_name + self_race_string + race_bot_separator + enemy_race_string + time_string + "_" + hash

        subpath = method_experiment_name + ending_folder + map_name + ending_folder

        create_folder(folder_bot_replays + subpath)
        create_folder(folder_bot_logs + subpath)

        output_replay = folder_bot_replays + subpath + id + ending_sc2replay
        log_file_path = folder_bot_logs + subpath + id + ending_logs

        fh = logging.FileHandler(log_file_path, mode="w")
        fh.setFormatter(formatter)
        fh.setLevel(logging.DEBUG)

        # add output to path to loggers
        for logger in loggers:
            logger.addHandler(fh)

        logger_strategy.info("Log file: {0}".format(log_file_path))
        logger_strategy.info("Selected build-order hash: {0}".format(hash))
        logger_strategy.info("Outputfile will be {0}".format(output_replay))
        logger_strategy.info("ID: {0}".format(id))

        # Start game
        run_game(
            maps.get(map_name),
            [
                Bot(
                    self_race,
                    Bot_AI_Extended(path, output_replay, logger_strategy,
                                    method_experiment_name, map_name)),
                #Bot(self_race, Bot_AI_Extended(path, output_replay, logger_strategy))
                Computer(enemy_race, enemy_difficulty)
            ],
            realtime=False,
            save_replay_as=output_replay,
            game_time_limit=max_gametime)

        for logger in loggers:
            logger.removeHandler(fh)

        fh.flush()
        fh.close()

        logging.shutdown()
                choice_weights = 1 * [0] + zealot_weight * [
                    1
                ] + gateway_weight * [2] + voidray_weight * [
                    3
                ] + stalker_weight * [4] + worker_weight * [5] + 1 * [
                    6
                ] + stargate_weight * [7] + pylon_weight * [8] + 1 * [
                    9
                ] + 1 * [10] + 1 * [11] + 1 * [12] + 1 * [13]
                choice = random.choice(choice_weights)

            try:
                await self.choices[choice]()
            except Exception as e:
                print(str(e))

            y = np.zeros(14)
            y[choice] = 1
            self.train_data.append([y, self.flipped])


while True:
    run_game(
        maps.get("AbyssalReefLE"),
        [
            Bot(Race.Protoss, SentdeBot()),
            #Bot(Race.Protoss, SentdeBot()),
            Computer(Race.Protoss, Difficulty.Easy)
        ],
        realtime=False)
Example #30
0
def main():
    sc2.run_game(sc2.maps.get("Abyssal Reef LE"), [
        Bot(Race.Zerg, ZergRushBot()),
        Computer(Race.Terran, Difficulty.Medium)
    ], realtime=False, save_replay_as="ZvT.SC2Replay")