GithubHelp home page GithubHelp logo

dentosal / python-sc2 Goto Github PK

View Code? Open in Web Editor NEW
583.0 41.0 181.0 2.65 MB

A StarCraft II bot api client library for Python 3

License: MIT License

Python 99.87% Dockerfile 0.13%
python3 starcraft starcraft-ii starcraft-ii-bot starcraft2

python-sc2's Introduction

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.

python-sc2's People

Contributors

aiseeq avatar akheron avatar alexander-kazakov avatar alvarofpp avatar archiatrus avatar arcia125 avatar burnysc2 avatar connormulqueen avatar dentosal avatar drakonnan1st avatar eagleflo avatar frigerius avatar gusgus01 avatar h3nnn4n avatar islamelnabarawy avatar jaros3 avatar ljuti avatar maxmusing avatar merfolk avatar mjschuetze102 avatar raimohanska avatar reypader avatar tweakimp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-sc2's Issues

Simplify unit management by supporting trackable groups

Currently the API supports picking closest units. It would be beneficial to allow explicit grouping of units, since often they tend to wander off. if you increase your pick distances, it becomes more likely that you pick up "wrong" units.

One way to support this is to use unit.tag. One could quite easily add on_step that would process all units (using sets), and check all the given groups for casualties and other trivia ("group under attack"). This would allow tracking multiple groups of units, and moving reinforcements between them.

Game doesn't run

Hello,

I tried this tutorial : https://www.youtube.com/watch?v=v3LJ6VvpfgI&lc=z23dvvr5jvbiyzvtoacdp43boy35vhpmr4lyn3lug2lw03c010c.1530380446748170

The code :

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)

However, when I run the code, i have this message in shell :

=== ERROR MESSAGE ===
INFO:sc2.protocol:Client status changed to Status.launched (was None) INFO:sc2.controller:Creating new game INFO:sc2.controller:Map: AbyssalReefLE INFO:sc2.controller:Players: Bot(Race.Protoss, <__main__.SentdeBot object at 0x0 3919070>), Computer(Race.Terran, Difficulty.Easy) INFO:sc2.protocol:Client status changed to Status.init_game (was Status.launched ) INFO:sc2.protocol:Client status changed to Status.launched (was None) INFO:root:Player id: 0 INFO:sc2.sc2process:kill_switch: Process cleanup INFO:sc2.sc2process:Cleaning up... INFO:sc2.sc2process:Cleanup complete Traceback (most recent call last): File "E:\Documents\Programmes\Windows\Programmes_Python\IA_Sc2\hataoylachance. py", line 33, in <module> ], realtime=False) File "C:\Users\Anthony\AppData\Local\Programs\Python\Python36-32\lib\site-pack ages\sc2\main.py", line 187, in run_game _host_game(map_settings, players, **kwargs) File "C:\Users\Anthony\AppData\Local\Programs\Python\Python36-32\lib\asyncio\b ase_events.py", line 468, in run_until_complete return future.result() File "C:\Users\Anthony\AppData\Local\Programs\Python\Python36-32\lib\site-pack ages\sc2\main.py", line 115, in _host_game result = await _play_game(players[0], client, realtime, portconfig, step_tim e_limit, game_time_limit) File "C:\Users\Anthony\AppData\Local\Programs\Python\Python36-32\lib\site-pack ages\sc2\main.py", line 87, in _play_game result = await _play_game_ai(client, player_id, player.ai, realtime, step_ti me_limit, game_time_limit) File "C:\Users\Anthony\AppData\Local\Programs\Python\Python36-32\lib\site-pack ages\sc2\main.py", line 29, in _play_game_ai game_data = await client.get_game_data() File "C:\Users\Anthony\AppData\Local\Programs\Python\Python36-32\lib\site-pack ages\sc2\client.py", line 110, in get_game_data upgrade_id=True File "C:\Users\Anthony\AppData\Local\Programs\Python\Python36-32\lib\site-pack ages\sc2\protocol.py", line 56, in _execute raise ProtocolError(f"{response.error}") sc2.protocol.ProtocolError: ['A game has not been started yet']

=== SYSTEM ===
Windows 7 64 bits
Python 3.6.5
python-sc2 installed with pip
Version of python-sc2 : 0.8.4 (I think, I have the file sc2-0.8.4.dist-info in site-packages on python)

Have you an idea ?

Thank you !

Inconsistent iterations rate: 30 iterations = 40 seconds?

Hi guys,

Testing very simple bots against each other in realtime mode.

Issues:

  1. Iteration 0 is called in the code at the ~1 minute 21 seconds of the game.
    And it is run at different times for each bots. Shouldn't it be run on the first second of the match?

https://i.imgur.com/nuFomNk.png

  1. Once some attacking happens between the workers, the iterations stop ticking at regular intervals. And it can take ~40 seconds to count 30 iterations while normally 1 second contains ~30 iterations.

https://i.imgur.com/QWkUSBn.png
https://i.imgur.com/shcsjR7.png

This makes it impossible to code any reasonable bot strategy. For example it takes multiple minutes for defending bot workers to actually attack each of the invading workers. And there are 10-20 seconds gaps between one target is destroyed and the next target attack command is executed.

Have anyone experienced the same?

My Machine: MacOS 10.13.5, Python 3.6.5, Installed the SC2 client and Python API yesterday.

Source code:

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

class DefendingBot(sc2.BotAI):
async def on_step(self, iteration):
if iteration == 0:
await self.chat_send(f"I am a Defending Bot")
if (iteration % 30 == 0): # Detection is run every few frames
await self.chat_send(f"Iteration: {iteration}")
await self.chat_send(f"Enemies detected: {self.known_enemy_units.amount}")
if (self.known_enemy_units.amount > 0):
for worker in self.workers:
await self.do(worker.attack(self.known_enemy_units.first))

class InvadingBot(sc2.BotAI):
async def on_step(self, iteration):
if iteration == 0: # If this is the first frame
await self.chat_send(f"I am an Invading Bot")
for worker in self.workers:
# Send all workers to the other bot's location
await self.do(worker.move(self.enemy_start_locations[0]))

run_game(maps.get("AbyssalReefLE"), [
Bot(Race.Protoss, DefendingBot()),
Bot(Race.Protoss, InvadingBot()),
], realtime=True) `

problem with activate ability - assert self.can_afford(action)

code:

forces3 = self.units(VIKINGFIGHTER)
for unit2 in forces3.idle:
await self.do(unit2(MORPH_VIKINGASSAULTMODE))

error:

File "C:\Users\xxx\Desktop\sc2\piconAI1.py", line 641, in on_step
await self.attack()
File "C:\Users\xxx\Desktop\sc2\piconAI1.py", line 674, in attack
await self.do(unit2(MORPH_VIKINGASSAULTMODE))
File "C:\Users\xxx\AppData\Roaming\Python\Python36\site-packages\sc2\bot_ai.py", line 317, in do
File "C:\Users\xxx\AppData\Roaming\Python\Python36\site-packages\sc2\bot_ai.py", line 317, in do
assert self.can_afford(action)

I think it's bug

Can not find_placement for Stalker Blink

I'm trying to get the Stalker to use the blink ability. Unfortunately, they don't always find a position to blink to. I find a position to try and blink to (pos) but it was not always working.

So I took the find_placement method from the WarpGate example for spawning stalkers and tried to have possible positions created from that, however the method is always returning None.

I would like for the Stalkers to "always" have a position to blink to, but I can't find a suitable function that will locate a position if find_placement will not work and pos is not a valid blink location.

if AbilityId.EFFECT_BLINK_STALKER in abilities:
    pos = s.position.to2.towards_with_random_angle(
                         self.units(UnitTypeId.NEXUS).closest_to(s).position)

    placement = await self.find_placement(AbilityId.EFFECT_BLINK_STALKER, pos,
                                          max_distance=8, placement_step=1)
    if placement is None:
         print("Stalker is not able to blink")

    await self.do(s(AbilityId.EFFECT_BLINK_STALKER, pos))

Running a game with two bots in real-time mode.

Hi,

I'm trying to run a game with two bots in real-time mode, but it looks like it doesn't register end of the game.
If i run bot vs computer both in real-time and in not real-time mode, or bot vs bot in not real-time mode, it works, but not when running bot vs bot in real-time.
Do anyone know a solution for that?

I was trying to debug that problem and it looks like response object:
response.ParseFromString(response_bytes)
doesn't contain player_result

Example from non-real-time mode:

  player_result {
    player_id: 1
    result: Victory
  }
  player_result {
    player_id: 2
    result: Defeat
  }

Path issues during Windows execution

The path values are treated as WindowsPath which causes _launch() to fail because subprocess require string paths.

Also, base_dir in paths.py is unresolved.

run_game() without closing process?

Is it possible to leave the process opened after bot finished it's executing?
Asking for that because it would help to reduce the time it takes for the bot to launch for the second time, because otherwise we have to wait for the game process to be relaunched after we launch the bot.
Yes, leaving inactive process takes memory but it would greatly help in terms of development and debugging speed.

Absence of the ability to "attack move"

In the SC2 you can command your units to move to a position while attacking any nearby enemy units they encounter along the way. The base move function does not work in this way. I searched and experimented with several abilities found in the abilities id's file and the closest thing I could find that functioned in this manner was "PATROL". Sadly this results in units running back and forth instead of just forth like I want. I thought perhaps "ATTACK_ATTACKTOWARDS" might work but that's a no go as well.

From what I can tell, the ability isn't implemented currently. If it is however, mind sharing the ID?

ModuleNotFoundError: No module named 'sc2.ids'

Did my best to follow the instructions and run an example and got this.

โžœ  python-sc2 git:(master) python3 examples/worker_rush.py
Traceback (most recent call last):
  File "examples/worker_rush.py", line 1, in <module>
    import sc2
  File "/Users/jpaanane/Library/Python/3.6/lib/python/site-packages/sc2/__init__.py", line 5, in <module>
    from .data import *
  File "/Users/jpaanane/Library/Python/3.6/lib/python/site-packages/sc2/data.py", line 9, in <module>
    from .ids.unit_typeid import PROBE, SCV, DRONE
ModuleNotFoundError: No module named 'sc2.ids'

Get game time or game frame

Is it possible to get the in game time in any reliable way?

Using iteration doesn't seem to be reliable as a source for time.
When using parameter realtime=True 300 iterations mean 10 seconds in game time (in step event: print(iteration) ), while using realtime=False I end up at 110 seconds with the same amount of iterations.

This stat would be very useful when microing (stutter stepping especially) or basing build orders on time (e.g. build engineering bay @ 3:00).

Remote

Hi,

Is it possible with your framework to connect to a remotely started client, e.g., one that is started by the ladderManager of sc2ai.net? For reference this how it is done with the c++ api, this is used for pysc2 (host port is given, so agent () is used), and here is a c# bot that can connect.

Regards

Use `stableid.json` to generate ID enums

The sc2_typeenums.h in sc2client-api doesn't seem to contain all of the currently available abilities. This could potentially make sure that we always have the complete ID. However, this would make using the enums as globals impossible because some abilities have the same name as units. This is particularly true for build and train abilities.

see #24

Document correct upgrade procedure for Terran buildings

Terran buildings seemed to be fairly picky for applying upgrades. The correct way to do this seems to be like this:

if self.units(BARRACKSTECHLAB).ready.exists:
  for lab in self.units(BARRACKSTECHLAB).ready:
    abilities = await self.get_available_abilities(lab)
    if AbilityId.RESEARCH_COMBATSHIELD in abilities and \
       self.can_afford(AbilityId.RESEARCH_COMBATSHIELD):
       await self.do(lab(AbilityId.RESEARCH_COMBATSHIELD))

Add example for building the basic upgrades.

ValueError: 1 is not a valid UnitTypeId

This looks great!
But when I run any of the examples I get:

Original exception was:
Traceback (most recent call last):
  File "/home/noju/Documents/python-sc2/examples/cannon_rush.py", line 60, in <module>
    main()
  File "/home/noju/Documents/python-sc2/examples/cannon_rush.py", line 57, in main
    ], realtime=False)
  File "/home/noju/Documents/python-sc2/sc2/main.py", line 105, in run_game
    _host_game(map_settings, players, **kwargs)
  File "/usr/lib/python3.6/asyncio/base_events.py", line 467, in run_until_complete
    return future.result()
  File "/home/noju/Documents/python-sc2/sc2/main.py", line 79, in _host_game
    result = await _play_game(players[0], client, realtime, portconfig)
  File "/home/noju/Documents/python-sc2/sc2/main.py", line 65, in _play_game
    return await _play_game_ai(client, player_id, player.ai, realtime)
  File "/home/noju/Documents/python-sc2/sc2/main.py", line 50, in _play_game_ai
    await ai.on_step(gs, iteration)
  File "/home/noju/Documents/python-sc2/examples/cannon_rush.py", line 21, in on_step
    if self.can_afford(PROBE):
  File "/home/noju/Documents/python-sc2/sc2/bot_ai.py", line 89, in can_afford
    cost = self._game_data.calculate_ability_cost(unit.creation_ability)
  File "/home/noju/Documents/python-sc2/sc2/game_data.py", line 28, in calculate_ability_cost
    if unit.id == ZERGLING:
  File "/home/noju/Documents/python-sc2/sc2/game_data.py", line 68, in id
    return UnitTypeId(self._proto.unit_id)
  File "/usr/lib/python3.6/enum.py", line 291, in __call__
    return cls.__new__(cls, value)
  File "/usr/lib/python3.6/enum.py", line 533, in __new__
    return cls._missing_(value)
  File "/usr/lib/python3.6/enum.py", line 546, in _missing_
    raise ValueError("%r is not a valid %s" % (value, cls.__name__))
ValueError: 1 is not a valid UnitTypeId

Also, do I need a specific version of pysc2?

Use ExecuteInfo.txt

If python-sc2 would use C:\Users\<username>\Documents\StarCraft II\ExecuteInfo.txt instead of a hard-coded path it could easily support non-standard installation paths. I assume there is also a ExecuteInfo.txt for mac.

Regards

"int" object is not iterable exception at PixelMap object

While trying to get access to the "print" method of PixelMap object I got TypeError exception: 'int' object is not iterable.

More specifically, I tried to print pathing_grid object stored as an attribute of "_game_info" object of sc2.BotAI class.

The line traceback is pointing at:

print("#" if self.is_set((x, y)) else " ", end=(" " if wide else ""))

Trying to run worker rush returns "sc2.protocol.ProtocolError: ['A game has not been started yet']"

Hi,

I'm trying to run the worker rush example and get this error. Happens with all other example bots I try. Happens when I try different maps too.Not sure myself what the error means.

PS C:\Users\Matt\Google Drive\Python\Starcraft 2> python QuilBot.py
INFO:sc2.protocol:Client status changed to Status.launched (was None)
INFO:sc2.controller:Creating new game
INFO:sc2.controller:Map: FrostLE
INFO:sc2.controller:Players: Bot(Race.Zerg, <main.WorkerRushBot object at 0x000001B4D79AEF98>), Computer(Race.Protoss, Di

fficulty.Medium)
INFO:sc2.protocol:Client status changed to Status.init_game (was Status.launched)
INFO:sc2.protocol:Client status changed to Status.launched (was None)
INFO:root:Player id: 0
INFO:sc2.sc2process:kill_switch: Process cleanup
INFO:sc2.sc2process:Cleaning up...
INFO:sc2.sc2process:Cleanup complete
Traceback (most recent call last):
File "QuilBot.py", line 16, in
], realtime=True)
File "C:\Users\Matt\AppData\Roaming\Python\Python36\site-packages\sc2\main.py", line 187, in run_game
_host_game(map_settings, players, **kwargs)
File "C:\Users\Matt\AppData\Local\Programs\Python\Python36\lib\asyncio\base_events.py", line 467, in run_until_complete
return future.result()
File "C:\Users\Matt\AppData\Roaming\Python\Python36\site-packages\sc2\main.py", line 115, in _host_game
result = await _play_game(players[0], client, realtime, portconfig, step_time_limit, game_time_limit)
File "C:\Users\Matt\AppData\Roaming\Python\Python36\site-packages\sc2\main.py", line 87, in _play_game
result = await _play_game_ai(client, player_id, player.ai, realtime, step_time_limit, game_time_limit)
File "C:\Users\Matt\AppData\Roaming\Python\Python36\site-packages\sc2\main.py", line 29, in _play_game_ai
game_data = await client.get_game_data()
File "C:\Users\Matt\AppData\Roaming\Python\Python36\site-packages\sc2\client.py", line 110, in get_game_data
upgrade_id=True
File "C:\Users\Matt\AppData\Roaming\Python\Python36\site-packages\sc2\protocol.py", line 56, in _execute
raise ProtocolError(f"{response.error}")
sc2.protocol.ProtocolError: ['A game has not been started yet']

Any help appreciated. Thanks.

Incorrect cost for Orbital Command upgrade (with fix)

Seems like there's a known problem in the SC2 API where orbital command upgrade cost is counted as CC cost + upgrade cost, i.e. 550 minerals, although the upgrade itself is only 150. This messes up can_afford() and similar, because the cost appears to be much higher than it actually is. I've heard that the same goes for other building upgrades such as Lair, although I haven't looked into that yet.

I've created a quickfix/monkey patch for the orbital cost. It's basically a copy of GameData.calculate_ability_cost() with an adjustment for orbital upgrade. This can be added at the top of your bot script, but should probably be patched into the code base in the long run.

# Monky-patch for incorrect orbital cost
# TODO: Also fix other building upgrade costs
from sc2.game_data import GameData, AbilityData, Cost
from sc2.unit_command import UnitCommand
from sc2.ids.ability_id import AbilityId
from functools import lru_cache

@lru_cache(maxsize=256)
def calculate_ability_cost_fix(self, ability):
	if isinstance(ability, AbilityId):
		ability = self.abilities[ability.value]
	elif isinstance(ability, UnitCommand):
		ability = self.abilities[ability.ability.value]

	assert isinstance(ability, AbilityData), f"C: {ability}"

	for unit in self.units.values():
		if unit.creation_ability == ability:
			if ability.id == UPGRADETOORBITAL_ORBITALCOMMAND:
				# Orbital upgrades shouldn't cost 550 but 150
				return Cost(
					unit.cost.minerals - 400,
					unit.cost.vespene,
					unit.cost.time
				)
			if unit.id == ZERGLING:
				# HARD CODED: zerglings are generated in pairs
				return Cost(
					unit.cost.minerals * 2,
					unit.cost.vespene * 2,
					unit.cost.time
				)
			return unit.cost

	for upgrade in self.upgrades.values():
		if upgrade.research_ability == ability:
			return upgrade.cost

	return Cost(0, 0)

GameData.calculate_ability_cost = calculate_ability_cost_fix

Access to any time reference?

I've not seen a reliable way to measure the passage of game-time. The passing of iterations varies greatly between realtime true/false modes, and the numbers I need also differ from the sentdex tutorial.

Is there any way to access that game-clock near the bottom left of the screen?

Thanks.

VScode "from sc2.constants import *" not working

VScode "from sc2.constants import *" not working, and i have below error massage
E0602:Undefined variable 'PROBE'

Also, I tried:

from sc2.constants import PROBE
[pylint] E0611:No name 'PROBE' in module 'sc2.constants'

Position.towards_random_angle seems to orient incorrectly by default

We tested Position.towards_random_angle for positioning buildings, and it seems to work quite unintuitively by default.

For example, cc.position.towards_random_angle(self.game_info.map_center, distance=7) seemed to position buildings behind the mineral deposits on Abyssal Reef LE.

Flipping the direction, self.game_info.map_center.towards_random_angle(cc.position, distance=7) then put the buildings (obviously) to middle of the map.

Is the default angle handling off by a PI?

Add convenience method to redistribute workers

We can re-structure the output of BotAI.expansion_locations to become a dictionary of a rounded Point2D with resource groups instead of just a list of rounded Point2D. This, alongside a convenience method to get owned expansions would allow us to potentially get nearby workers, compare them with the amount of resource nodes, and redistribute.

EDIT:
I just found out there's a assigned_harvesters and ideal_harvesters property on units. I presume these are for the townhall and extractors. Instead of counting the nodes, we can use these instead. Though, turning the expansions into dictionaries could still be useful. I reckon when someone manages to make a script to drop into the enemy mineral line, they'd prioritze attacking expansions with more nodes.

Resign game --> Both accept and offer

Is it possible to accept/offer the defeat of/to the opponent?

Some bot Difficulty level will send gg and offer to end the game earlier, since the remaing game is not interesting.

The latest version cannot run on linux

I upgrade the python-sc2 package to 0.4.5 and I find I cannot run even the worker rush script on my computer whose operation system is linux. Here is the error report:

Error: expected response: 2, actual response: 0
Error reported: Must first start a game with CreateGame or specify ports to join another client's game
Traceback (most recent call last):
INFO:sc2.sc2process:Cleanup complete
File "/home/wangjian/DeepLearning/starcraft/MacroOperation/MacroOperation.py", line 18, in
main()
File "/home/wangjian/DeepLearning/starcraft/MacroOperation/MacroOperation.py", line 15, in main
], realtime=True)
File "/home/wangjian/anaconda3/lib/python3.6/site-packages/sc2/main.py", line 127, in run_game
_host_game(map_settings, players, **kwargs)
File "/home/wangjian/anaconda3/lib/python3.6/asyncio/base_events.py", line 467, in run_until_complete
return future.result()
File "/home/wangjian/anaconda3/lib/python3.6/site-packages/sc2/main.py", line 88, in _host_game
result = await _play_game(players[0], client, realtime, portconfig, step_time_limit)
File "/home/wangjian/anaconda3/lib/python3.6/site-packages/sc2/main.py", line 65, in _play_game
player_id = await client.join_game(player.race, portconfig=portconfig)
File "/home/wangjian/anaconda3/lib/python3.6/site-packages/sc2/client.py", line 52, in join_game
result = await self._execute(join_game=req)
File "/home/wangjian/anaconda3/lib/python3.6/site-packages/sc2/protocol.py", line 56, in _execute
raise ProtocolError(f"{response.error}")
sc2.protocol.ProtocolError: ["Must first start a game with CreateGame or specify ports to join another client's game"]

Add/document support for tracking action failures

Currently there seems to be no way to track if the action actually succeeds. This makes it possible for the bot to continue repeating actions that will continuously fail.

One way to handle this would be to allow passing a optional on_error callback to self.do(...) function. This would allow easier debugging for cases when you continuously fail to apply an upgrade to building, for example.

can_afford() sometimes leads to ERROR:sc2.bot_ai:Error: ActionResult.NotSupported

Ordering a unit by larvae sometimes resulting in getting an error:
ERROR:sc2.bot_ai:Error: ActionResult.NotSupported (action: UnitCommand(AbilityId.LARVATRAIN_DRONE, Unit(name='Larva', tag=4314628097), None, False))

I believe this is because the method can_afford() of the class sc2.BotAI sometimes returning true even if we cannot afford the unit.
This is happening, I assuming, because there are sequential queue of orders that happening one frame (step) after another, and the information that can_afford() is referring to is not keeping up to date.

Can not install python-sc2 BUT pysc2...

In Cmd: Collecting python-sc2
Error: Could not find a version that satisfies the requirement python-sc2 (from versions: )
No matching distribution found for python-sc2

So I extracted the folder "sc2" manually...could this be the reason?

Duplicate actions in Realtime mode

I noticed that some actions are run twice when realtime=True in sc2.run_game(), even though they shouldn't. This doesn't seem to happen when realtime=False.

For example, if I run examples/proxy_rax.py in realtime, there is sometimes an extra SCV queued at the CC, even though the code says that it should only train an SCV if the CC queue is empty. I also sometimes get NotEnoughMinerals error for the same reason, because it runs the build SCV action twice, but can't afford the second one (even though there's the self.can_afford(SCV) check).

I'm on Windows 10, if this has anything to do with it.

self.find_placement() not working for creep tumors

I've been trying to make my bot spread creep across the map, however I've run into an issue with the

loc = await self.find_placement(CREEPTUMORBURROWED, near, placement_step=1, max_distance=5)

function. It only returns None, and never a location.
Creep tumors are the only 1x1 size buildings, the next bigger sized unit (that requires creep also) is the spine / spore crawler with 2x2. So far I've been using

loc = await self.find_placement(SPINECRAWLER, near, placement_step=1, max_distance=5)

instead, but that does not work well for ramps, edges or maps with (walkable) water (map example: Odyssey has lots of water), where normal buildings cannot be placed but creep tumors can.

Another issue is trying to access the

locationAttempts = 30
ability = self._game_data.abilities[BUILD_CREEPTUMOR_QUEEN.value]
# or the following:
ability = self._game_data.units[CREEPTUMORQUEEN.value].creation_ability
# in a circular motion around the location, figure out which is a valid location:
positions = [Point2((location.x + spreadDistance * math.cos(math.pi * alpha * 2 / locationAttempts), location.y + spreadDistance * math.sin(math.pi * alpha * 2 / locationAttempts))) for alpha in range(locationAttempts)]
validPlacements = await self._client.query_building_placement(ability, positions)

self._client.query_building_placemen() function from the client.py file. The issue might be related as all the results report <ActionResult.NotSupported>.
This function is very useful when trying to check many locations in one await sweep.

How can a bot quit the game?

I'm writing sc2 AI scripts with python-sc2 but I don't know how to let the bot quit the game.
Is there anyway of doing that?

Importing problem with pycharm

I pip installed the SC2 , and now in pycharm and I can import it , I can also import sc2.player , but I can't do "from sc2.constants import PROBE" , is there a fix?

Units won't be idle after moving

After I do something like this: await self.do(unit.move(target.position))
That unit will never go back to being idle even after it's made it to the location. Currently I'm having to keep a list of units I moved, checking their distance from the desired location and manually calling unit.stop() so that they'll have cleared orders again.

Better support for build orders

I'm thinking about something like build order class, that could just specify step-by-step instructions for the first parts of the game. Also simplifying expansion-taking and building placement would be a good thing to add.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.