Как написать бота для starcraft 2

Добро пожаловать в новую серию статей, где мы будем создавать ботов для игры StarCraft II при помощи алгоритмов искусственного интеллекта на языке Python. Примерно в середине 2017 года DeepMind и Blizzard (создатели StarCraft II) объявили о партнерстве и анонсировали API для взаимодействия со стратегической игрой.

До этого мы никогда не играли в StarCraft II, но зато играли во многие похожие игры, такие как Command and Conquer и Age of Empires. Смысл таких игр в том, чтобы соревноваться с другими игроками или компьютером.

Вы начинаете с некой «базы», ​​в которой вы можете строить базовые юниты, собирающие ресурсы. Далее можно строить из этого новые здания, что в свою очередь открывает для вас новые юниты, например боевые. А затем вы можете совершать разные покупки юнитов и всевозможным образом их модернизировать. Ваша конечная цель — собрать армию, чтобы победить вашего противника (одного или нескольких).

В StarCraft II есть три «расы»: терраны, протоссы и зерги. Игру мы начнем за расу протоссов, так как она нам кажется наиболее технологичной. А это важно, поскольку мы планируем создать искусственный интеллект!

На следующей диаграмме показаны все здания и юниты, которые вы можете создать, играя за протоссов:

starcraft ii protoss breakdown

Данное изображение нами взято отсюда. Это довольно полезный ресурс для тех, кто, как и мы, понятия не имеет, что делать в реальной игре.

Как вы можете заметить, эта диаграмма имеет древовидную структуру. Таким образом, чтобы создать Верховного храмовника (High Templar), у вас для начала должен быть Нексус (Nexus). С него вы начинаете, это своего рода «командный центр» для вас. Отсюда вы строите Врата (Gateaway), затем Кибернетическое Ядро (Cybernetics Core) , затем Сумеречный Совет (Twilight Council), и только ЗАТЕМ Архивы тамплиеров (Templar Archives).

Здания, рабочие и бойцы — все это требует от вас ресурсов и, возможно, самого важного элемента: времени. Довольно сложно даже просто разобраться во всех этих строениях, юнитах и их апгрейдах. А ведь мы еще и участвуем в различных сражениях на большом количестве карт с различной топологией. Одни карты относительно открыты, а в других есть довольно мало путей, по которым можно пройти. И вам нужно решить, в какие области можно безопасно расширить свою базу, а также многое другое.

И наконец, важную роль играют ваши противники. Они идут за вами по пятам? Или оставили вас на время в покое и собирают армию? Какой они расы? Они производят обновления? Насколько сильно они расширились? И многое, многое другое. Это очень сложная и конкурентная игра, несмотря на то, что на первый взгляд кажется довольно простой .

Мы, конечно, не эксперты, и поэтому не будем тратить много времени на объяснение самой игры. Чтобы ее освоить, мы просто создали базовых ботов и запускали их в режиме реального времени, внося изменения и наблюдая, что работает лучше и дольше. Затем переписывали ботов и запускали опять.

Итак, для начала нам нужен Starcraft II. Сейчас игра бесплатна, и все, что вам нужно, это создать аккаунт, скачать игру отсюда и установить ее.

Далее, мы будем использовать библиотеку python-sc2. Еще есть библиотека pysc2, которая является оболочкой для Python Deepmind. На данный момент мы остановились на библиотеке python-sc2, так как она нам кажется более простой для понимания. Однако заметим, что скорей всего pysc2 все же больше подходит для ботов с глубоким обучением, так как там есть много удобных вещей. В любом случае не забудьте установить python-sc2: pip install sc2.

С релизом Python 3.7 многие вещи были изменены, особенно веб-сокеты. Если у вас возникнут проблемы, откатитесь до Python 3.6.

Теперь нам понадобятся карты!

Перейдите в раздел Map Packs библиотеки Blizzard s2client и загрузите несколько карт. Мы скачали их все, но вам это делать необязательно. Когда вы загрузите эти архивы, распакуйте карты в каталог Maps, который находится в каталоге Starcraft II. Примерная файловая структура имеет следующий вид:

StarCraft II
-Maps
--Ladder2017Season1
---AbyssalReefLE.SC2Map

Если вы уже установили Starcraft II в определенную директорию, зайдите в каталог Python для сторонних разработчиков, найдите там директорию sc2, а в ней — файл paths.py. Далее поменяйте в нем значение переменной basedir на соответствующее вашей директории Starcraft II.

Теперь у нас есть карты, а значит, мы готовы к путешествиям! Начнем с простого примера.

Для начала произведем импорт необходимых модулей:

import sc2
from sc2 import run_game, maps, Race, Difficulty
from sc2.player import Bot, Computer

Чтобы упростить нашу жизнь, здесь все из пакета python-sc2, включая такие вещи, как запуск игр, выбор гонок и настройка нашего противника.

Далее нам нужно создать класс нашего бота. Своего бота мы назовем SentdeBot, но вы можете выбрать любое название, которое вам по душе. Наш бот будет наследником класса sc2.BotAI. Вы можете познакомиться с этим классом, заглянув в sc2/bot_ai.py. Как вы можете увидеть, в нем много методов. Такие вещи, как known_enemy_units, выглядят довольно полезными! Класс нашего бота будет начинаться так:

class SentdeBot(sc2.BotAI):

Итак, в игре мы, очевидно, хотим собрать армию и уничтожить наших врагов. Но чтобы это сделать, для начала нам потребуются определенные ресурсы. В Starcraft это минералы и газ. Что касается минералов (полезных ископаемых), нам просто нужно их добывать при помощи рабочих.

[machinelearning_ad_block]

Мы начинаем с 12-ти рабочих. В расе протоссов, к которой мы принадлежим, рабочие называются зондами (probes). Нашей первоочередной задачей должно быть равномерное распределение этих сотрудников по рабочим местам. Например, вам нужно не более 3 рабочих на участок минералов, так как наличие большего количества не ускорит добычу. К счастью для нас, в родительском классе sc2.BotAI есть метод distribute_workers, который делает это за нас!

Итак, обеспечиваем хорошее распределение рабочих на каждом этапе:

class SentdeBot(sc2.BotAI):
    async def on_step(self, iteration):
        # what to do every step
        await self.distribute_workers()  # in sc2/bot_ai.py

Ключевое слово async используется для создания данных асинхронных методов, поэтому нам не нужно ждать завершения каждого из них, чтобы исполнять другой код.

Давайте предположим, что все, чего мы хотим, это распределять рабочих в играх. В таком случае у нас все готово! Для запуска игры мы будем использовать метод run_game. Сперва эта функция принимает карту, которую вы хотите запустить, а затем — список игроков. После этого вы можете указать, хотите ли вы играть в режиме реального времени (по сути — обычная скорость или супербыстро).

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

Итак, мы будем играть по карте AbyssalReefLE. Играть будет бот, принадлежащий к расе протоссов, а класс бота будет называться SentdeBot. Вторым игроком будет компьютер, выступающий за расу терранов. Его уровень сложности будет невысоким. Больше игроков не будет.

Запускайте код: игра начнется и ваш бот будет работать!

Наш код на данный момент имеет следующий вид:

import sc2
from sc2 import run_game, maps, Race, Difficulty
from sc2.player import Bot, Computer


class SentdeBot(sc2.BotAI):
    async def on_step(self, iteration):
        # what to do every step
        await self.distribute_workers()  # in sc2/bot_ai.py


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

Не хотелось бы вас огорчать, но таким образом никакой игры не выиграть. Тем не менее, у нас уже есть бот! В следующей статье мы будем работать над добавлением в него дополнительных функций, которые позволят начать выигрывать в каких-нибудь играх.

Следующая статья — Python AI в StarCraft II. Часть II: рабочие и пилоны.

Время на прочтение
6 мин

Количество просмотров 8.8K


(с) Blizzard Entertainment

В StarCraft II есть встроенные боты, и все с ними хорошо, за исключением того, что они немного тупые, но речь пойдет не о них. В 2017 году разработчик игры компания Blizzard Entertainment опубликовала API, позволяющий создавать внешних ботов. Однако, по какой-то странной причине Blizzard рассматривает этот API как сугубо исследовательский проект, где боты должны сражаться только друг с другом. Нормальной возможности поиграть человеку с ботами они почему-то не сделали, хотя многие геймеры рассматривают ботов как довольно неплохой инструмент тренировок.

Тем не менее все не так плохо. Раз штатной возможности нет, то будем использовать нештатную. Мы все же настроим ботов и повоюем против них. Потом мы с вами, движимые исследовательским порывом, разберемся как устроен АPI, и поднимем окружение разработки, в котором сможем сами писать подобных ботов.

Лабораторный стенд

В качестве лабораторного стенда использовалась виртуальная машина. Это было сделано по множеству причин, одна из которых заключалась в необходимости запускать неизвестные исполняемые файлы «из Интернета». Игра на виртуалке запустилась нормально и даже вполне играбельно, правда с минимальными настройками графики. Использование виртуалки в качестве стенда дает ряд преимуществ: во-первых, можно запускать игру на не-Windows компьютерах, во-вторых, виртуалку можно использовать как основу для необнаруживаемых ботов-кликеров.

Виртуальная машина, используемая в экспериментах, работала под управлением (важно) Windows 10 x64. Операционная система устанавливалась с параметрами по умолчанию (Next, Next, Next…), и в ней был создан единственный пользователь «user», обладающий правами администратора.

Установка и подготовка игры

StarCraft II бесплатная игра, и процесс ее установки довольно простой:

  1. На сайте Battle.net создаем учетную запись.
  2. Скачиваем и устанавливаем Battle.net клиент.
  3. Авторизуемся в клиенте под ранее созданной учетной записью и устанавливаем StarCraft II (важно) в каталог «C:Program Files (x86)StarCraft II» (это каталог по умолчанию).

Для использования внешних ботов нам необходимо установить локальные игровые карты. По идее боты могут работать на любых картах, хоть на тех, что вы создадите с помощью встроенного редактора. Однако, для первого знакомства рекомендуется скачать карты, на которых проводятся соревнования ботов между собой (да-да, и такое есть). Дело в том, что в некоторых ботах названия карт жестко забиты в код, и поначалу будет довольно сложно понять, почему тот или иной бот не запускается.

Скачивать карты будем со специального репозитория Blizzard на GitHub. Рекомендуется скачать все доступные карты. Они там разложены по архивам на каждый сезон.

(Важно) В каталоге игры нужно сделать подкаталог «Maps» и распаковать архивы с картами туда. Пароль на архивы «iagreetotheeula». Распаковывать архивы надо с сохранением структуры каталогов.

В нашем случае игра установлена в «C:Program Files (x86)StarCraft II», соответственно каталог с картами будет «C:Program Files (x86)StarCraft IIMaps». После распаковки карт все должно получиться как на скриншоте ниже:

Играем против ботов

Для того чтобы попробовать свои силы против внешних ботов, нам потребуется специальный лаунчер — SC2AI Mannager (только Win10) от Cryptious админа Discord канала SC2 AI. Справедливости ради стоит сказать, что некоторых ботов можно запустить и без лаунчера, но это, как говорится, следующий уровень сложности, и мы его рассмотрим чуть позже.

SC2AI Mannager позволяет как играть против ботов, так и стравливать различных ботов между собой. Запускать лаунчер с произвольными ботами мы в данной статье не будем, а вместо этого возьмем готовый набор (лаунчер, карты, боты), который использовался в демонстрационных боях ProBots 2021 Season 3 — ProBots vs Humans Exhibition.

Использование набора сводится к следующим простым шагам:

  1. Скачиваем набор и распаковываем его в произвольную папку на диске.
  2. Карты из набора, то есть файлы имеющие расширение *.SC2Map, копируем в «C:Program Files (x86)StarCraft IIMaps».
  3. Запускаем лаунчер Sc2AiApp.exe.

  4. Он просит авторизоваться, но можно и без авторизации, жмем «Continue Without Login», затем переходим на вкладку «Play Vs Bot».

  5. Выбираем расу, которой хотим играть и нажимаем «Launch». В результате должны запуститься 2 игровых клиента и консольное приложение бота.

  6. Для нормальной игры в пользовательском окне нужно включить отображение на полный экран. Для этого необходимо нажать F10 (Option)->Graphics выбрать Windowed (Fullscreen)

Архитектура StarCraft II и организация API

Что ж, быстрый старт позади. Давайте теперь разберемся чуть глубже. По умолчанию API внешних ботов в игре не работает, для его активации необходимо запустить клиент с особыми параметрами командной строки. Процедура запуска выглядит следующим образом:

  1. Необходимо определить путь установки SC2 и определить разрядность клиента
  2. Необходимо сделать рабочим каталогом директорию в которой хранятся библиотеки для клиента соответствующей разрядности. Для x64 клиента это «c:Program Files (x86)StarCraft IISupport64»
  3. Запустить клиент с указанием параметров командной строки. Например так: ««C:\Program Files (x86)\StarCraft II\Versions\Base87702\SC2_x64.exe» -listen «127.0.0.1» -port «18080» -dataDir «C:\Program Files (x86)\StarCraft II» -tempDir «C:\Users\user\AppData\Local\Temp\SC2_xp3zu_33» -displayMode «0» -verbose»
    Примечание. Указанный пример взят из исходного текста одного из исследованных ботов.

Если все сделали правильно, то запустится просто черное окно с заголовком StarCraft II, и больше ничего происходить не будет.

По факту клиент запустился нормально, он перешел в режим ожидания подключения по сетевому сокету (IP адрес + порт), который мы указали в качестве параметров командной строки. В примере выше это адрес 127.0.0.1 и порт 18080.

Для управления клиентом применяется специальный сетевой протокол, использующий в качестве транспорта WebSockets, поверх которого реализован протокол Google Protocol Buffers, параметры сериализации которого определены Blizzard и описаны в спецификации.

API рассматривает игру как конечный автомат, имеющий следующие состояния:


(с) Blizzard Entertainment

Соответственно, когда мы запустили игру с помощью примера выше, она вошла в состояние «Launched» и далее ждала запросов на перевод в следующее состояние. Вот поэтому и был просто черный экран.

Этих знаний нам хватит для первого знакомства с устройством внешних SC2 ботов и того, как они могут работать в принципе. В дальнейшем, если будет желание что-то написать самому, то необходимо будет подробно ознакомиться с документацией на API из GitHub репозитория Blizzard/s2client-proto.

Развертывание среды разработки (Python)

За счет того что API основан на стандартном сетевом протоколе, разработка ботов может вестись на любом языке программирования, но мы рассмотрим только Python. Это обусловлено следующими причинами:

  • Во-первых, Python довольно популярен среди разработчиков ботов, и для него написаны неплохие библиотеки (например, BurnySc2/python-sc2, deepmind/pysc2), помогающие в разработки собственных ботов.
  • Во-вторых, подготовить подобную среду будет достаточно просто и доступно даже новичкам.

Приступим к подготовке среды:

  1. Установим Python, скачав его с официального сайта. В текущем примере использовалась версия 3.10.4, однако некоторые боты могут требовать другую версию, так что перед началом посмотрите, какую версию рекомендует разработчик бота. Во время установки не забудьте добавить путь к python в переменную окружения PATH. Если вы все сделали правильно, то после установки, запустив консоль (cmd) и набрав «python», у вас должен запуститься интерпретатор.
  2. Следующий этап — это развертывание одной из Python-библиотек, используемых для написания ботов. В этом примере мы воспользуемся BurnySc2/python-sc2. Для её установки в консоли наберем: pip install burnysc2

    Если библиотека установилась правильно, то в консоли не должно быть сообщений об ошибках, а в каталоге Python-библиотек (например, c:usersuserappdatalocalprogramspythonpython310libsite-packages) должен появиться каталог «sc2».

  3. Установим дополнительную библиотеку six, которая потребуется для работы burnysc2
    pip install six
  4. Перейдем в Web-интерфейс GitHub-репозитория BurnySc2 и скачаем его весь как архив. Для этого нажмем на зеленую кнопку «Code», а затем в появившемся меню «Download ZIP».

    Скачанный архив распакуем в произвольную папку, например, в c:python-sc2-develop.

Среда разработки готова. Теперь попробуем запустить бот-пример «Zerg-rush». Для этого откроем консоль и перейдем в каталог «C:python-sc2-developexampleszerg». После этого введем команду: python zerg_rush.py

В результате у нас должно запуститься консольное окно бота и окно клиента StarCraft II, где в ускоренном режиме бот «Zerg-rush» будет воевать со встроенным ботом среднего уровня сложности. По окончании боя будет записан реплей ZvT.SC2Replay.

В библиотеке BurnySc2 есть еще множество примеров ботов, но отдельного внимания стоит уделить примеру play_tvz.py. В нем показано, как запустить бота против человека.
Примечание. Пример содержит ошибку: в первой строке указан некорректный путь для импорта. Исправленный пример, предназначенный для запуска из каталога «C:python-sc2-developexamples» выглядит следующим образом:

from zerg.zerg_rush import ZergRushBot
from sc2 import maps
from sc2.data import Race
from sc2.main import run_game
from sc2.player import Bot, Human


def main():
    run_game(maps.get("Abyssal Reef LE"), [Human(Race.Terran), Bot(Race.Zerg, ZergRushBot())], realtime=True)


if __name__ == "__main__":
    main()

Успешный запуск данного примера приведет к запуску 2-х клиентов SC2, в одном из которых будет бот, а во втором можно будет играть человеку.

Дополнительные материалы

  • SC2 AI Arena ladder — сайт, посвященный соревнованиям ботов между собой.
  • SC2 AI Wiki — Вики, по всему что связано с ботами для SC2.
  • GitHub компании Blizzard — в нем следует обратить внимание на репозитории s2client-proto, s2client-api и s2protocol.
  • Статья компании DeepMind: AlphaStar: Mastering the real-time strategy game StarCraft II — в ней говорится об опыте создания ботов для SC2 на базе глубоких нейронных сетей. Русский перевод этой же статьи.

MicroMachine: AI Bot for StarCraft II

This bot is built on top of CommandCenter, a popular C++ bot that is great for beginners. The main improvements over CommandCenter is the micro management of units in combat, notably the focus fire, dancing and kiting. The current strategy is to rush with Marines with the Terran race and hope that the great micro management will be enough to overcome the defenses of the enemy early in the game.

CommandCenter: AI Bot for Broodwar and Starcraft II

CommandCenter is a StarCraft AI bot that can play both StarCraft: Broodwar and StarCraft 2.

CommandCenter Screenshot

CommandCenter is written in C++ using BWAPI and Blizzard’s StarCraft II AI API. It provides many wrapper functions around both APIs that allow it to perform the same functionality in both games via the same source code. It is written by David Churchill, Assistant Professor of Computer Science at Memorial University, and organizer of the AIIDE StarCraft AI Competition.

CommandCenter is based on the architecture of UAlbertaBot, and is intended to be an easy to use architecture for you to quickly modify, play with, and build your own bot. The bot itself does not contain much in the way of hard-coded strategy or tactics, however it provides a good starting point for you to implement your own strategies for any race.

CommandCenter currently provides the following features:

  • Plays both Starcraft games with the same source code
  • Plays all 3 races with generalized micro controllers for combat units
  • Performs online map analysis, extracting information such as base locations and expansions
  • Keeps track of all previously seen enemy units and their last known locations on the map
  • Has a WorkerManager which manages resource gathering and worker allocation / buiding
  • Is able to carry out predefined build-orders written in a configuration file
  • Allows you to easily create your own build-orders and modify them on the fly in-game
  • Contains a building placement algorithm, finding the closest buildable location to a given position for a given building
  • Scouts the map with a worker unit, discovering where the enemy base is located
  • Once a specific condition has been reached (having 12 combat units, by default), it will commence an attack, sending waves of units at the enemy base
  • Squads can be formed, consisting of multiple units following a specific order such as attack or defend a given location

CommandCenter should eventually have all of the functionality of UAlbertaBot, however much of its features are not currently completed. Here is an up-to-date list of features currently missing from CommandCenter that will be implemented soon:

  • Only units and basic buildings can be constructed via the ProductionManager. No add-ons, research, or upgrades yet.
  • There is no automatic build-order planning system
  • There is no combat simulation package for predicting combat battle victory
  • The bot only plays 1v1, and will have undefined behavior / crash if played against multiple enemies or on teams

Download and Run CommandCenter

StarCraft BW: You must have StarCraft: Broodwar version 1.16.1 installed, as well as BWAPI.

StarCraft 2: You must have an up-to-date retail version of StarCraft II installed to run the bot. You must also download and install some maps to use with the bot, which you can find here: https://github.com/Blizzard/s2client-proto#downloads. Please note that there is a password provided on that page to extract the maps from the zip files.

The bot comes with a configuration file named BotConfig.txt in which you can modify build orders, print various debug information to the screen, and set some bot parameters. You can define multiple builds orders in the ‘Strategies’ section of the file, and choose which named strategy to implement when the bot plays a specific race. Unit names in the build-order are case sensitive, and must be exactly how they appear in-game with no spaces. Some of the options in the configuration file are currently not implemented, such as the KiteWithRangedUnits option.

Please note that this config file is in JSON format, and the bot will not run unless it is well-formatted JSON. The configuration file must be in the same directory as CommandCenter.exe in order for the bot to run correctly. If you have made an error in the JSON syntax and can’t find it on your own, you can use an online JSON Validator to check for you.

By default when you run CommandCenter.exe, it will play as Random race vs. a Random race built-in SC2 Easy AI. You can modify which races are played in the configuration file via the «BotRace» and «EnemyRace» options. You can also modify which map to be played by specifying the «MapFile» option. Please note that the MapFile option is relative to your StarCraft II maps directory, which by default is located in your StarCraft_Install_Directory/maps/, and the bot will not run without specifying a valid map file.

If the bot crashes or does other nasty things, please bear with me while I make it more stable :)

Developer Install / Compile Instructions (Windows)

  • Download and install Visual Studio 2017
  • To play BW, you must download and install StarCraft BW v1.16.1 as well as BWAPI
  • To play SC2, you must download and install the StarCraft II AI API. The easiest way to do this is to download the Precompiled Libraries at the bottom of the page, and simply extract them to a folder on your PC (make sure they are up to date). If you are getting the SC2API via cloning the Blizzard github repo and compiling it from scratch, you may need to point VS to different directories for include and lib than the ones described below.
  • Clone this git repository to a folder on your PC
  • Open «CommandCenter/vs/CommandCenter.sln» in VS2017
  • If you compile the CommandCenter project with the x64 Platform, it will compile the SC2 bot
  • If you compile the CommandCenter project with the x86 or Win32 Platform, it will compile the BW bot
  • Set the VS Project include and lib folders to point to the directories
    • Right click the CommandCenter project in VS2017
    • Select «Properties»
    • Select the correct configuration that you want to build in the top left («Release» or «Debug»)
    • Select the target platform you want to build (x64 = SC2, Win32 = BW)
    • Select «VC++ Directories» on the left
    • Select the «Include Directories» option in the table on the right
    • Click the dropdown arrow on the right and click Edit…
    • Modify the existing directory entry to point to your (SC2API|BWAPI)/include directory
    • Select the «Library Directories» option in the table on the right
    • Click the dropdown arrow on the right and click Edit…
    • Modify the existing directory entry to point to your (SC2API|BWAPI)/lib directory
  • From the «Build» menu, click «Build Solution»
  • The binary «CommandCenter_API.exe» should appear in the CommandCenter/bin/ directory
  • Run the CommandCenter bot by either:
    • Double clicking the executable in the CommandCenter/bin/ directory
    • Running the program from the console
    • Click «Local Windows Debugger» in VS to launch the program from within VS. To do this, you need to set the «Working Directory» option under «Debugging» to «$(ProjectDir)/../bin/» (I don’t know why this option won’t save)
  • If you are running the BW version of the bot, you must then start BW via Chaoslauncher with BWAPI injected
  • The CommandCenter/bin/BotConfig.txt file must be in the same directory as the .exe to run properly

Developer Install / Compile Instructions (Linux and OS X)

With these steps you should be able to build and install the SC2 API and include it into CommandCenter. It has been tested successfully for aba2d3813571c344090f3de5b58a5c912cd5acb3, so if the install instructions below don’t work checkout that version of the SC2 API

$ git checkout aba2d3813571c344090f3de5b58a5c912cd5acb3 .

and repeat the instructions.

  • Build SC2 API project
$ git clone --recursive https://github.com/Blizzard/s2client-api && cd s2client-api
$ mkdir build && cd build
$ cmake ../
$ make
  • Install the SC2 API libraries and headers to your system
# Assuming that you are located in the 'build' directory
# after you finished the previous step
$ cd ../

# Install SC2 API headers
$ sudo mkdir -p /opt/local/include
$ sudo cp -R include/sc2api /opt/local/include
$ sudo cp -R include/sc2utils /opt/local/include
$ sudo cp -R build/generated/s2clientprotocol /opt/local/include

# Install protobuf headers
$ sudo cp -R contrib/protobuf/src/google /opt/local/include/sc2api

# Install SC2 API libraries
$ sudo mkdir -p /opt/local/lib/sc2api
$ sudo cp build/bin/libcivetweb.a /opt/local/lib/sc2api
$ sudo cp build/bin/libprotobuf.a /opt/local/lib/sc2api
$ sudo cp build/bin/libsc2api.a /opt/local/lib/sc2api
$ sudo cp build/bin/libsc2lib.a /opt/local/lib/sc2api
$ sudo cp build/bin/libsc2protocol.a /opt/local/lib/sc2api
$ sudo cp build/bin/libsc2utils.a /opt/local/lib/sc2api
  • Build the bot
$ git clone https://github.com/RaphaelRoyerRivard/commandcenter.git && cd commandcenter
$ cmake .
$ make

Bot Development

If you are familiar with the architecture of UAlbertaBot, the logic of CommandCenter is quite similar. The biggest difference is that information relating to the map, baselocation, etc are no longer globally accessible. This data now lives inside the main CCBot class, and must be accessed via a reference to the instance of that class. Because of this, most classes in CommandCenter carry with them a reference to the bot’s main CCBot object, from which all game related information, observations, and queries can be made.

An in-depth development guide will be coming soon, but please refer to the UAlbertaBot wiki for now since the architecture is so similar (minus the build order planner and combat simulator).

ESChamp

Loading

A StarCraft II API Client for Python 3 (Modified)

Code in this repository is modified for Sentdex’s tutorials

An easy-to-use library for writing AI Bots for StarCraft II in Python 3. The ultimate goal is simplicity and ease of use, while still preserving all functionality. A really simple worker rush bot should be no more than twenty lines of code, not two hundred. However, this library intends to provide both high and low level abstractions.

This library (currently) covers only the raw scripted interface. At this time I don’t intend to add support for graphics-based interfaces.

Documentation is in the Wiki.

For automaticly running multiple matches, check out Dentosal/sc2-bot-match-runner.

Installation

You’ll need Python 3.6 or newer.

pip install --user --upgrade sc2

Requirements

pip install websockets
conda install opencv
# to prevent some async errors
pip install tornado==4.5.3

Game Path

If CRITICAL:sc2.paths installation not found

#on Starcraft2-Bot/sc2 folder, edit path.py:
BASEDIR = {
    "Windows": "C:/Program Files (x86)/StarCraft II",
    "Darwin": "/Applications/StarCraft II",
    "Linux": "~/StarCraftII"
}

Maps

Maybe you need to create a lower case maps folder:

Dentosal/python-sc2#105

Please note that not all commits are not released to PyPI. Releases are tagged with version number. You can see latest released versions from tags page.

You’ll also need an StarCraft II executable. If you are running Windows or macOS, just install the normal SC2 from blizzard app. The free starter edition works too.. Linux users must use the Linux binary.

You probably want some maps too. Official map downloads are available from Blizzard/s2client-proto. Notice: the map files are to be extracted into subdirectories of the install-dir/Maps directory.

Running

After installing the library, a StarCraft II executable, and some maps, you’re ready to get started. Simply run a bot file to fire up an instance of StarCraft II with the bot running. For example:

python3 examples/protoss/cannon_rush.py

Example

As promised, worker rush in less than twenty lines:

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=True)

This is probably the simplest bot that has any realistic chances of winning the game. I have ran it against the medium AI a few times, and once in a while it wins.

You can find more examples in the examples/ folder.

Bug reports, ideas and contributing

If you have any issues, ideas or feedback, please create a new issue. Pull requests are also welcome!

A StarCraft II API Client for Python 3 (Modified)

Code in this repository is modified for Sentdex’s tutorials

An easy-to-use library for writing AI Bots for StarCraft II in Python 3. The ultimate goal is simplicity and ease of use, while still preserving all functionality. A really simple worker rush bot should be no more than twenty lines of code, not two hundred. However, this library intends to provide both high and low level abstractions.

This library (currently) covers only the raw scripted interface. At this time I don’t intend to add support for graphics-based interfaces.

Documentation is in the Wiki.

For automaticly running multiple matches, check out Dentosal/sc2-bot-match-runner.

Installation

You’ll need Python 3.6 or newer.

pip install --user --upgrade sc2

Requirements

pip install websockets
conda install opencv
# to prevent some async errors
pip install tornado==4.5.3

Game Path

If CRITICAL:sc2.paths installation not found

#on Starcraft2-Bot/sc2 folder, edit path.py:
BASEDIR = {
    "Windows": "C:/Program Files (x86)/StarCraft II",
    "Darwin": "/Applications/StarCraft II",
    "Linux": "~/StarCraftII"
}

Maps

Maybe you need to create a lower case maps folder:

Dentosal/python-sc2#105

Please note that not all commits are not released to PyPI. Releases are tagged with version number. You can see latest released versions from tags page.

You’ll also need an StarCraft II executable. If you are running Windows or macOS, just install the normal SC2 from blizzard app. The free starter edition works too.. Linux users must use the Linux binary.

You probably want some maps too. Official map downloads are available from Blizzard/s2client-proto. Notice: the map files are to be extracted into subdirectories of the install-dir/Maps directory.

Running

After installing the library, a StarCraft II executable, and some maps, you’re ready to get started. Simply run a bot file to fire up an instance of StarCraft II with the bot running. For example:

python3 examples/protoss/cannon_rush.py

Example

As promised, worker rush in less than twenty lines:

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=True)

This is probably the simplest bot that has any realistic chances of winning the game. I have ran it against the medium AI a few times, and once in a while it wins.

You can find more examples in the examples/ folder.

Bug reports, ideas and contributing

If you have any issues, ideas or feedback, please create a new issue. Pull requests are also welcome!

This repository is no longer maintained and may not work with the latest version of the StarCraft 2 client. You can use this fork instead which aims to stay updated for both the latest windows StarCraft 2 client and latest linux client, while also being available on pypi.org.

A StarCraft II API Client for Python 3

An easy-to-use library for writing AI Bots for StarCraft II in Python 3. The ultimate goal is simplicity and ease of use, while still preserving all functionality. A really simple worker rush bot should be no more than twenty lines of code, not two hundred. However, this library intends to provide both high and low level abstractions.

This library (currently) covers only the raw scripted interface. At this time I don’t intend to add support for graphics-based interfaces.

Documentation is in the Wiki.

For automatically running multiple matches, check out Dentosal/sc2-bot-match-runner.

Installation

By installing this library you agree to be bound by the terms of the AI and Machine Learning License.

You’ll need Python 3.6 or newer.

pip3 install --user --upgrade sc2

Please note that not all commits are released to PyPI. Releases are tagged with version number. You can see latest released versions from tags page.

You’ll also need an StarCraft II executable. If you are running Windows or macOS, just install the normal SC2 from blizzard app. The free starter edition works too.. Linux users get the best experience by installing the Windows version of StarCraft II with Wine. Linux user can also use the Linux binary, but it’s headless so you cannot actually see the game.

You probably want some maps too. Official map downloads are available from Blizzard/s2client-proto. Notice: the map files are to be extracted into subdirectories of the install-dir/Maps directory.

Running

After installing the library, a StarCraft II executable, and some maps, you’re ready to get started. Simply run a bot file to fire up an instance of StarCraft II with the bot running. For example:

python3 examples/protoss/cannon_rush.py

If you installed StarCraft II on Linux with Wine, set the SC2PF environment variable to WineLinux:

SC2PF=WineLinux python3 examples/protoss/cannon_rush.py

Example

As promised, worker rush in less than twenty lines:

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=True)

This is probably the simplest bot that has any realistic chances of winning the game. I have ran it against the medium AI a few times, and once in a while it wins.

You can find more examples in the examples/ folder.

Help and support

You have questions but don’t want to create an issue? Join the Starcraft 2 AI Discord. Questions about this repository can be asked in channel #python-sc2.

Bug reports, feature requests and ideas

If you have any issues, ideas or feedback, please create a new issue. Pull requests are also welcome!

Contributing & style guidelines

Git commit messages use imperative-style messages, start with capital letter and do not have trailing commas.

Понравилась статья? Поделить с друзьями:
  • Как написать бот кил
  • Как написать бот для торговли на бирже
  • Как написать бот для регистрации
  • Как написать боссу что заболел
  • Как написать босс на английском