我用 Python 写了一个AI 玩星际争霸2

PySC2 --- 星际争霸Ⅱ 学习环境搭建 欢迎使用Markdown编辑器写博客PySC2是DeepMind开发的星际争霸Ⅱ学习环境(SC2LE)的Python组件。 它封装Blizzard Entertainment的星际争霸Ⅱ机器学习API,提供Python 增强学习环境。 PySC2提供了增强学习Agents与星际争霸Ⅱ交互的接口,得到observations以及发送actions。 DeepMind PySC2提供了详细的安装说明,在 阅读详情

Deepmind 开放了自己的星际争霸机器学习环境,现在只需要安装对应的 pysc2 包,就可以自己写一个星际2 AI啦!本文是Rest探路者分享在博客园的一个相关项目,里面有非常详尽的代码,有兴趣的小伙伴可以参考。

文 | Rest探路者 

出处 | 博客园

准备

我的环境是python3.6,sc2包0.11.1,机器学习包:pysc2,地图下载链接maps:https://github.com/Blizzard/s2client-proto#downloads。

pysc2是DeepMind开发的星际争霸Ⅱ学习环境。它是封装星际争霸Ⅱ机器学习API,同时也提供Python增强学习环境。以神族为例编写代码,神族建筑科技图如下:

采矿

# -*- encoding: utf-8 -*-
'''
@File : __init__.py.py
@Modify Time @Author @Desciption
------------ ------- -----------
2019/11/3 12:32 Jonas None
'''

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: int):
await self.distribute_workers()


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

注意game_data.py的assert self.id != 0注释掉 pixel_map.py的assert self.bits_per_pixel % 8 == 0, "Unsupported pixel density"注释掉,否则会报错

运行结果如下,农民开始采矿

可以正常采矿

建造农民和水晶塔

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


class SentdeBot(sc2.BotAI):
async def on_step(self, iteration: int):
await self.distribute_workers()
await self.build_workers()
await self.build_pylons()

# 建造农民
async def build_workers(self):
# 星灵枢纽(NEXUS)无队列建造,可以提高晶体矿的利用率,不至于占用资源
for nexus in self.units(UnitTypeId.NEXUS).ready.noqueue:
# 是否有50晶体矿
if self.can_afford(UnitTypeId.PROBE):
await self.do(nexus.train(UnitTypeId.PROBE))

## 建造水晶
async def build_pylons(self):
## 供应人口和现有人口之差小于5且水晶不是正在建造
if self.supply_left<5 and not self.already_pending(UnitTypeId.PYLON):
nexuses = self.units(UnitTypeId.NEXUS).ready
if nexuses.exists:
if self.can_afford(UnitTypeId.PYLON):
await self.build(UnitTypeId.PYLON,near=nexuses.first)

## 启动游戏
run_game(maps.get("AcidPlantLE"), [
Bot(Race.Protoss, SentdeBot()), Computer(Race.Terran, Difficulty.Easy)
],realtime = True)

运行结果如下,基地造农民,农民造水晶

收集气体和开矿

代码如下

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


class SentdeBot(sc2.BotAI):
async def on_step(self, iteration: int):
await self.distribute_workers()
await self.build_workers()
await self.build_pylons()
await self.build_assimilators()
await self.expand()

# 建造农民
async def build_workers(self):
# 星灵枢纽(NEXUS)无队列建造,可以提高晶体矿的利用率,不至于占用资源
for nexus in self.units(UnitTypeId.NEXUS).ready.noqueue:
# 是否有50晶体矿
if self.can_afford(UnitTypeId.PROBE):
await self.do(nexus.train(UnitTypeId.PROBE))

## 建造水晶
async def build_pylons(self):
## 供应人口和现有人口之差小于5且建筑不是正在建造
if self.supply_left < 5 and not self.already_pending(UnitTypeId.PYLON):
nexuses = self.units(UnitTypeId.NEXUS).ready
if nexuses.exists:
if self.can_afford(UnitTypeId.PYLON):
await self.build(UnitTypeId.PYLON, near=nexuses.first)

## 建造吸收厂
async def build_assimilators(self):
for nexus in self.units(UnitTypeId.NEXUS).ready:
# 在瓦斯泉上建造吸收厂
vaspenes = self.state.vespene_geyser.closer_than(15.0,nexus)
for vaspene in vaspenes:
if not self.can_afford(UnitTypeId.ASSIMILATOR):
break
worker = self.select_build_worker(vaspene.position)
if worker is None:
break
if not self.units(UnitTypeId.ASSIMILATOR).closer_than(1.0,vaspene).exists:
await self.do(worker.build(UnitTypeId.ASSIMILATOR,vaspene))

## 开矿
async def expand(self):
if self.units(UnitTypeId.NEXUS).amount<3 and self.can_afford(UnitTypeId.NEXUS):
await self.expand_now()

## 启动游戏
run_game(maps.get("AcidPlantLE"), [
Bot(Race.Protoss, SentdeBot()), Computer(Race.Terran, Difficulty.Easy)
], realtime=False)

run_game的realtime设置成False,可以在加速模式下运行游戏。

运行效果如下:

可以建造吸收厂和开矿

建造军队

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


class SentdeBot(sc2.BotAI):
async def on_step(self, iteration: int):
await self.distribute_workers()
await self.build_workers()
await self.build_pylons()
await self.build_assimilators()
await self.expand()
await self.offensive_force_buildings()
await self.build_offensive_force()

# 建造农民
async def build_workers(self):
# 星灵枢纽(NEXUS)无队列建造,可以提高晶体矿的利用率,不至于占用资源
for nexus in self.units(UnitTypeId.NEXUS).ready.noqueue:
# 是否有50晶体矿
if self.can_afford(UnitTypeId.PROBE):
await self.do(nexus.train(UnitTypeId.PROBE))

## 建造水晶
async def build_pylons(self):
## 供应人口和现有人口之差小于5且建筑不是正在建造
if self.supply_left < 5 and not self.already_pending(UnitTypeId.PYLON):
nexuses = self.units(UnitTypeId.NEXUS).ready
if nexuses.exists:
if self.can_afford(UnitTypeId.PYLON):
await self.build(UnitTypeId.PYLON, near=nexuses.first)

## 建造吸收厂
async def build_assimilators(self):
for nexus in self.units(UnitTypeId.NEXUS).ready:
# 在瓦斯泉上建造吸收厂
vaspenes = self.state.vespene_geyser.closer_than(15.0,nexus)
for vaspene in vaspenes:
if not self.can_afford(UnitTypeId.ASSIMILATOR):
break
worker = self.select_build_worker(vaspene.position)
if worker is None:
break
if not self.units(UnitTypeId.ASSIMILATOR).closer_than(1.0,vaspene).exists:
await self.do(worker.build(UnitTypeId.ASSIMILATOR,vaspene))

## 开矿
async def expand(self):
if self.units(UnitTypeId.NEXUS).amount<2 and self.can_afford(UnitTypeId.NEXUS):
await self.expand_now()

## 建造进攻性建筑
async def offensive_force_buildings(self):
if self.units(UnitTypeId.PYLON).ready.exists:
pylon = self.units(UnitTypeId.PYLON).ready.random
if self.units(UnitTypeId.PYLON).ready.exists:
# 根据神族建筑科技图,折跃门建造过后才可以建造控制核心
if self.units(UnitTypeId.GATEWAY).ready.exists:
if not self.units(UnitTypeId.CYBERNETICSCORE):
if self.can_afford(UnitTypeId.CYBERNETICSCORE) and not self.already_pending(UnitTypeId.CYBERNETICSCORE):
await self.build(UnitTypeId.CYBERNETICSCORE,near = pylon)
# 否则建造折跃门
else:
if self.can_afford(UnitTypeId.GATEWAY) and not self.already_pending(UnitTypeId.GATEWAY):
await self.build(UnitTypeId.GATEWAY,near=pylon)

# 造兵
async def build_offensive_force(self):
# 无队列化建造
for gw in self.units(UnitTypeId.GATEWAY).ready.noqueue:
if self.can_afford(UnitTypeId.STALKER) and self.supply_left>0:
await self.do(gw.train(UnitTypeId.STALKER))



## 启动游戏
run_game(maps.get("AcidPlantLE"), [
Bot(Race.Protoss, SentdeBot()), Computer(Race.Terran, Difficulty.Easy)
], realtime=False)

运行结果如下:

可以看到,我们建造了折跃门和控制核心并训练了追猎者

控制部队进攻

代码如下

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

class SentdeBot(sc2.BotAI):
async def on_step(self, iteration: int):
await self.distribute_workers()
await self.build_workers()
await self.build_pylons()
await self.build_assimilators()
await self.expand()
await self.offensive_force_buildings()
await self.build_offensive_force()
await self.attack()

# 建造农民
async def build_workers(self):
# 星灵枢纽(NEXUS)无队列建造,可以提高晶体矿的利用率,不至于占用资源
for nexus in self.units(UnitTypeId.NEXUS).ready.noqueue:
# 是否有50晶体矿
if self.can_afford(UnitTypeId.PROBE):
await self.do(nexus.train(UnitTypeId.PROBE))

## 建造水晶
async def build_pylons(self):
## 供应人口和现有人口之差小于5且建筑不是正在建造
if self.supply_left < 5 and not self.already_pending(UnitTypeId.PYLON):
nexuses = self.units(UnitTypeId.NEXUS).ready
if nexuses.exists:
if self.can_afford(UnitTypeId.PYLON):
await self.build(UnitTypeId.PYLON, near=nexuses.first)

## 建造吸收厂
async def build_assimilators(self):
for nexus in self.units(UnitTypeId.NEXUS).ready:
# 在瓦斯泉上建造吸收厂
vaspenes = self.state.vespene_geyser.closer_than(15.0,nexus)
for vaspene in vaspenes:
if not self.can_afford(UnitTypeId.ASSIMILATOR):
break
worker = self.select_build_worker(vaspene.position)
if worker is None:
break
if not self.units(UnitTypeId.ASSIMILATOR).closer_than(1.0,vaspene).exists:
await self.do(worker.build(UnitTypeId.ASSIMILATOR,vaspene))

## 开矿
async def expand(self):
if self.units(UnitTypeId.NEXUS).amount<3 and self.can_afford(UnitTypeId.NEXUS):
await self.expand_now()

## 建造进攻性建筑
async def offensive_force_buildings(self):
if self.units(UnitTypeId.PYLON).ready.exists:
pylon = self.units(UnitTypeId.PYLON).ready.random
# 根据神族建筑科技图,折跃门建造过后才可以建造控制核心
if self.units(UnitTypeId.GATEWAY).ready.exists and not self.units(UnitTypeId.CYBERNETICSCORE):
if self.can_afford(UnitTypeId.CYBERNETICSCORE) and not self.already_pending(UnitTypeId.CYBERNETICSCORE):
await self.build(UnitTypeId.CYBERNETICSCORE,near = pylon)
# 否则建造折跃门
elif len(self.units(UnitTypeId.GATEWAY))<=3:
if self.can_afford(UnitTypeId.GATEWAY) and not self.already_pending(UnitTypeId.GATEWAY):
await self.build(UnitTypeId.GATEWAY,near=pylon)

## 造兵
async def build_offensive_force(self):
# 无队列化建造
for gw in self.units(UnitTypeId.GATEWAY).ready.noqueue:
if self.can_afford(UnitTypeId.STALKER) and self.supply_left>0:
await self.do(gw.train(UnitTypeId.STALKER))

## 寻找目标
def find_target(self,state):
if len(self.known_enemy_units)>0:
# 随机选取敌方单位
return random.choice(self.known_enemy_units)
elif len(self.known_enemy_units)>0:
# 随机选取敌方建筑
return random.choice(self.known_enemy_structures)
else:
# 返回敌方出生点位
return self.enemy_start_locations[0]

## 进攻
async def attack(self):
# 追猎者数量超过15个开始进攻
if self.units(UnitTypeId.STALKER).amount>15:
for s in self.units(UnitTypeId.STALKER).idle:
await self.do(s.attack(self.find_target(self.state)))

# 防卫模式:视野范围内存在敌人,开始攻击
if self.units(UnitTypeId.STALKER).amount>5:
if len(self.known_enemy_units)>0:
for s in self.units(UnitTypeId.STALKER).idle:
await self.do(s.attack(random.choice(self.known_enemy_units)))

## 启动游戏
run_game(maps.get("AcidPlantLE"), [
Bot(Race.Protoss, SentdeBot()), Computer(Race.Terran, Difficulty.Medium)
], realtime=False)

运行结果如下

可以看到,4个折跃门训练追猎者并发动进攻。

击败困难电脑

我们目前的代码只能击败中等和简单电脑,那么如何击败困难电脑呢?代码如下

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


class SentdeBot(sc2.BotAI):
def __init__(self):
# 经过计算,每分钟大约165迭代次数
self.ITERATIONS_PER_MINUTE = 165
# 最大农民数量
self.MAX_WORKERS = 65

async def on_step(self, iteration: int):
self.iteration = iteration
await self.distribute_workers()
await self.build_workers()
await self.build_pylons()
await self.build_assimilators()
await self.expand()
await self.offensive_force_buildings()
await self.build_offensive_force()
await self.attack()

# 建造农民
async def build_workers(self):
# 星灵枢钮*16(一个基地配备16个农民)大于农民数量并且现有农民数量小于MAX_WORKERS
if len(self.units(UnitTypeId.NEXUS))*16>len(self.units(UnitTypeId.PROBE)) and len(self.units(UnitTypeId.PROBE))<self.MAX_WORKERS:
# 星灵枢纽(NEXUS)无队列建造,可以提高晶体矿的利用率,不至于占用资源
for nexus in self.units(UnitTypeId.NEXUS).ready.noqueue:
# 是否有50晶体矿建造农民
if self.can_afford(UnitTypeId.PROBE):
await self.do(nexus.train(UnitTypeId.PROBE))

## 建造水晶
async def build_pylons(self):
## 供应人口和现有人口之差小于5且建筑不是正在建造
if self.supply_left < 5 and not self.already_pending(UnitTypeId.PYLON):
nexuses = self.units(UnitTypeId.NEXUS).ready
if nexuses.exists:
if self.can_afford(UnitTypeId.PYLON):
await self.build(UnitTypeId.PYLON, near=nexuses.first)

## 建造吸收厂
async def build_assimilators(self):
for nexus in self.units(UnitTypeId.NEXUS).ready:
# 在瓦斯泉上建造吸收厂
vaspenes = self.state.vespene_geyser.closer_than(15.0,nexus)
for vaspene in vaspenes:
if not self.can_afford(UnitTypeId.ASSIMILATOR):
break
worker = self.select_build_worker(vaspene.position)
if worker is None:
break
if not self.units(UnitTypeId.ASSIMILATOR).closer_than(1.0,vaspene).exists:
await self.do(worker.build(UnitTypeId.ASSIMILATOR,vaspene))

## 开矿
async def expand(self):
# (self.iteration / self.ITERATIONS_PER_MINUTE)是一个缓慢递增的值,动态开矿
if self.units(UnitTypeId.NEXUS).amount<self.iteration / self.ITERATIONS_PER_MINUTE and self.can_afford(UnitTypeId.NEXUS):
await self.expand_now()

## 建造进攻性建筑
async def offensive_force_buildings(self):
print(self.iteration / self.ITERATIONS_PER_MINUTE)
if self.units(UnitTypeId.PYLON).ready.exists:
pylon = self.units(UnitTypeId.PYLON).ready.random
# 根据神族建筑科技图,折跃门建造过后才可以建造控制核心
if self.units(UnitTypeId.GATEWAY).ready.exists and not self.units(UnitTypeId.CYBERNETICSCORE):
if self.can_afford(UnitTypeId.CYBERNETICSCORE) and not self.already_pending(UnitTypeId.CYBERNETICSCORE):
await self.build(UnitTypeId.CYBERNETICSCORE, near=pylon)
# 否则建造折跃门
# (self.iteration / self.ITERATIONS_PER_MINUTE)/2 是一个缓慢递增的值
elif len(self.units(UnitTypeId.GATEWAY)) < ((self.iteration / self.ITERATIONS_PER_MINUTE) / 2):
if self.can_afford(UnitTypeId.GATEWAY) and not self.already_pending(UnitTypeId.GATEWAY):
await self.build(UnitTypeId.GATEWAY, near=pylon)
# 控制核心存在的情况下建造星门
if self.units(UnitTypeId.CYBERNETICSCORE).ready.exists:
if len(self.units(UnitTypeId.STARGATE)) < ((self.iteration / self.ITERATIONS_PER_MINUTE) / 2):
if self.can_afford(UnitTypeId.STARGATE) and not self.already_pending(UnitTypeId.STARGATE):
await self.build(UnitTypeId.STARGATE, near=pylon)

## 造兵
async def build_offensive_force(self):
# 无队列化建造
for gw in self.units(UnitTypeId.GATEWAY).ready.noqueue:
if not self.units(UnitTypeId.STALKER).amount > self.units(UnitTypeId.VOIDRAY).amount:

if self.can_afford(UnitTypeId.STALKER) and self.supply_left > 0:
await self.do(gw.train(UnitTypeId.STALKER))

for sg in self.units(UnitTypeId.STARGATE).ready.noqueue:
if self.can_afford(UnitTypeId.VOIDRAY) and self.supply_left > 0:
await self.do(sg.train(UnitTypeId.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_units)>0:
# 随机选取敌方建筑
return random.choice(self.known_enemy_structures)
else:
# 返回敌方出生点位
return self.enemy_start_locations[0]

## 进攻
async def attack(self):
# {UNIT: [n to fight, n to defend]}
aggressive_units = {UnitTypeId.STALKER: [15, 5],
UnitTypeId.VOIDRAY: [8, 3]}

for UNIT in aggressive_units:
# 攻击模式
if self.units(UNIT).amount > aggressive_units[UNIT][0] and self.units(UNIT).amount > aggressive_units[UNIT][
1]:
for s in self.units(UNIT).idle:
await self.do(s.attack(self.find_target(self.state)))
# 防卫模式
elif self.units(UNIT).amount > aggressive_units[UNIT][1]:
if len(self.known_enemy_units) > 0:
for s in self.units(UNIT).idle:
await self.do(s.attack(random.choice(self.known_enemy_units)))
## 启动游戏
run_game(maps.get("AcidPlantLE"), [
Bot(Race.Protoss, SentdeBot()), Computer(Race.Terran, Difficulty.Hard)
], realtime=False)

运行结果如下

可以看到,击败了困难人族电脑,但是电脑选择了rush战术,我们写得AI脚本会输掉游戏。显然,这不是最佳方案。“只有AI才能拯救我的胜率”,请看下文。

采集地图数据

这次我们只造一个折跃门,全力通过星门造虚空光辉舰 修改offensive_force_buildings(self)方法的判断

elif len(self.units(GATEWAY)) < 1:
if self.can_afford(GATEWAY) and not self.already_pending(GATEWAY):
await self.build(GATEWAY, near=pylon)

注释或者删除build_offensive_force(self)的建造追猎者的代码

        ## 造兵
async def build_offensive_force(self):
# 无队列化建造
# for gw in self.units(UnitTypeId.GATEWAY).ready.noqueue:
# if not self.units(UnitTypeId.STALKER).amount > self.units(UnitTypeId.VOIDRAY).amount:
#
# if self.can_afford(UnitTypeId.STALKER) and self.supply_left > 0:
# await self.do(gw.train(UnitTypeId.STALKER))

for sg in self.units(UnitTypeId.STARGATE).ready.noqueue:
if self.can_afford(UnitTypeId.VOIDRAY) and self.supply_left > 0:
await self.do(sg.train(UnitTypeId.VOIDRAY))

attack(self)中的aggressive_units注释掉Stalker 导入numpy和cv2库

game_data = np.zeros((self.game_info.map_size[1], self.game_info.map_size[0], 3), np.uint8)

建立以地图Heigt为行,Width为列的三维矩阵

for nexus in self.units(NEXUS):
nex_pos = nexus.position
print(nex_pos)
cv2.circle(game_data, (int(nex_pos[0]), int(nex_pos[1])), 10, (0, 255, 0), -1) # BGR

遍历星灵枢纽,获取下一个位置,画圆,circle(承载圆的img, 圆心, 半径, 颜色, thickness=-1表示填充),接下来我们要垂直翻转三维矩阵,因为我们建立的矩阵左上角是原点(0,0),纵坐标向下延申,横坐标向右延申。翻转之后就成了正常的坐标系。

flipped = cv2.flip(game_data, 0)

图像缩放,达到可视化最佳。

        resized = cv2.resize(flipped, dsize=None, fx=2, fy=2)
cv2.imshow('Intel', resized)
cv2.waitKey(1)

至此,完整代码如下

import sc2
from sc2 import run_game, maps, Race, Difficulty
from sc2.player import Bot, Computer
from sc2.constants import *
import random
import numpy as np
import cv2


class SentdeBot(sc2.BotAI):
def __init__(self):
# 经过计算,每分钟大约165迭代次数
self.ITERATIONS_PER_MINUTE = 165
# 最大农民数量
self.MAX_WORKERS = 65

async def on_step(self, iteration: int):
self.iteration = iteration
await self.distribute_workers()
await self.build_workers()
await self.build_pylons()
await self.build_assimilators()
await self.expand()
await self.offensive_force_buildings()
await self.build_offensive_force()
await self.intel()
await self.attack()

async def intel(self):
# 根据地图建立的三维矩阵
game_data = np.zeros((self.game_info.map_size[1], self.game_info.map_size[0], 3), np.uint8)
for nexus in self.units(UnitTypeId.NEXUS):
nex_pos = nexus.position
# circle(承载圆的img, 圆心, 半径, 颜色, thickness=-1表示填充)
# 记录星灵枢纽的位置
cv2.circle(game_data, (int(nex_pos[0]), int(nex_pos[1])), 10, (0, 255, 0), -1)
# 图像翻转垂直镜像
flipped = cv2.flip(game_data, 0)
# 图像缩放
# cv2.resize(原图像,输出图像的大小,width方向的缩放比例,height方向缩放的比例)
resized = cv2.resize(flipped, dsize=None, fx=2, fy=2)
cv2.imshow('Intel', resized)

# cv2.waitKey(每Xms刷新图像)
cv2.waitKey(1)

# 建造农民
async def build_workers(self):
# 星灵枢钮*16(一个基地配备16个农民)大于农民数量并且现有农民数量小于MAX_WORKERS
if len(self.units(UnitTypeId.NEXUS)) * 16 > len(self.units(UnitTypeId.PROBE)) and len(
self.units(UnitTypeId.PROBE)) < self.MAX_WORKERS:
# 星灵枢纽(NEXUS)无队列建造,可以提高晶体矿的利用率,不至于占用资源
for nexus in self.units(UnitTypeId.NEXUS).ready.noqueue:
# 是否有50晶体矿建造农民
if self.can_afford(UnitTypeId.PROBE):
await self.do(nexus.train(UnitTypeId.PROBE))

## 建造水晶
async def build_pylons(self):
## 供应人口和现有人口之差小于5且建筑不是正在建造
if self.supply_left < 5 and not self.already_pending(UnitTypeId.PYLON):
nexuses = self.units(UnitTypeId.NEXUS).ready
if nexuses.exists:
if self.can_afford(UnitTypeId.PYLON):
await self.build(UnitTypeId.PYLON, near=nexuses.first)

## 建造吸收厂
async def build_assimilators(self):
for nexus in self.units(UnitTypeId.NEXUS).ready:
# 在瓦斯泉上建造吸收厂
vaspenes = self.state.vespene_geyser.closer_than(15.0, nexus)
for vaspene in vaspenes:
if not self.can_afford(UnitTypeId.ASSIMILATOR):
break
worker = self.select_build_worker(vaspene.position)
if worker is None:
break
if not self.units(UnitTypeId.ASSIMILATOR).closer_than(1.0, vaspene).exists:
await self.do(worker.build(UnitTypeId.ASSIMILATOR, vaspene))

## 开矿
async def expand(self):
# (self.iteration / self.ITERATIONS_PER_MINUTE)是一个缓慢递增的值,动态开矿
if self.units(UnitTypeId.NEXUS).amount < self.iteration / self.ITERATIONS_PER_MINUTE and self.can_afford(
UnitTypeId.NEXUS):
await self.expand_now()

## 建造进攻性建筑
async def offensive_force_buildings(self):
print(self.iteration / self.ITERATIONS_PER_MINUTE)
if self.units(UnitTypeId.PYLON).ready.exists:
pylon = self.units(UnitTypeId.PYLON).ready.random
# 根据神族建筑科技图,折跃门建造过后才可以建造控制核心
if self.units(UnitTypeId.GATEWAY).ready.exists and not self.units(UnitTypeId.CYBERNETICSCORE):
if self.can_afford(UnitTypeId.CYBERNETICSCORE) and not self.already_pending(UnitTypeId.CYBERNETICSCORE):
await self.build(UnitTypeId.CYBERNETICSCORE, near=pylon)
# 否则建造折跃门
# (self.iteration / self.ITERATIONS_PER_MINUTE)/2 是一个缓慢递增的值
# elif len(self.units(UnitTypeId.GATEWAY)) < ((self.iteration / self.ITERATIONS_PER_MINUTE) / 2):
elif len(self.units(UnitTypeId.GATEWAY)) < 1:
if self.can_afford(UnitTypeId.GATEWAY) and not self.already_pending(UnitTypeId.GATEWAY):
await self.build(UnitTypeId.GATEWAY, near=pylon)
# 控制核心存在的情况下建造星门
if self.units(UnitTypeId.CYBERNETICSCORE).ready.exists:
if len(self.units(UnitTypeId.STARGATE)) < ((self.iteration / self.ITERATIONS_PER_MINUTE) / 2):
if self.can_afford(UnitTypeId.STARGATE) and not self.already_pending(UnitTypeId.STARGATE):
await self.build(UnitTypeId.STARGATE, near=pylon)

## 造兵
async def build_offensive_force(self):
# 无队列化建造
for sg in self.units(UnitTypeId.STARGATE).ready.noqueue:
if self.can_afford(UnitTypeId.VOIDRAY) and self.supply_left > 0:
await self.do(sg.train(UnitTypeId.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_units) > 0:
# 随机选取敌方建筑
return random.choice(self.known_enemy_structures)
else:
# 返回敌方出生点位
return self.enemy_start_locations[0]

## 进攻
async def attack(self):
# {UNIT: [n to fight, n to defend]}
aggressive_units = {UnitTypeId.VOIDRAY: [8, 3]}

for UNIT in aggressive_units:
# 攻击模式
if self.units(UNIT).amount > aggressive_units[UNIT][0] and self.units(UNIT).amount > aggressive_units[UNIT][1]:
for s in self.units(UNIT).idle:
await self.do(s.attack(self.find_target(self.state)))
# 防卫模式
elif self.units(UNIT).amount > aggressive_units[UNIT][1]:
if len(self.known_enemy_units) > 0:
for s in self.units(UNIT).idle:
await self.do(s.attack(random.choice(self.known_enemy_units)))


## 启动游戏
run_game(maps.get("AcidPlantLE"), [
Bot(Race.Protoss, SentdeBot()), Computer(Race.Terran, Difficulty.Hard)
], realtime=False)

运行结果如下

采集到了地图位置。

侦察

在intel(self)里创建一个字典draw_dict,UnitTypeId作为key,半径和颜色是value


draw_dict = {
UnitTypeId.NEXUS: [15, (0, 255, 0)],
UnitTypeId.PYLON: [3, (20, 235, 0)],
UnitTypeId.PROBE: [1, (55, 200, 0)],
UnitTypeId.ASSIMILATOR: [2, (55, 200, 0)],
UnitTypeId.GATEWAY: [3, (200, 100, 0)],
UnitTypeId.CYBERNETICSCORE: [3, (150, 150, 0)],
UnitTypeId.STARGATE: [5, (255, 0, 0)],
UnitTypeId.ROBOTICSFACILITY: [5, (215, 155, 0)],

UnitTypeId.VOIDRAY: [3, (255, 100, 0)]
}

迭代同上

for unit_type in draw_dict:
for unit in self.units(unit_type).ready:
pos = unit.position
cv2.circle(game_data, (int(pos[0]), int(pos[1])), draw_dict[unit_type][0], draw_dict[unit_type][1], -1)

存储三族的主基地名称(星灵枢纽,指挥中心,孵化场),刻画敌方建筑。

# 主基地名称
main_base_names = ["nexus", "supplydepot", "hatchery"]
# 记录敌方基地位置
for enemy_building in self.known_enemy_structures:
pos = enemy_building.position
if enemy_building.name.lower() not in main_base_names:
cv2.circle(game_data, (int(pos[0]), int(pos[1])), 5, (200, 50, 212), -1)
for enemy_building in self.known_enemy_structures:
pos = enemy_building.position
if enemy_building.name.lower() in main_base_names:
cv2.circle(game_data, (int(pos[0]), int(pos[1])), 15, (0, 0, 255), -1)

刻画敌方单位,如果是农民画得小些,其他单位则画大些。

        for enemy_unit in self.known_enemy_units:

if not enemy_unit.is_structure:
worker_names = ["probe", "scv", "drone"]
# if that unit is a PROBE, SCV, or DRONE... it's a worker
pos = enemy_unit.position
if enemy_unit.name.lower() in worker_names:
cv2.circle(game_data, (int(pos[0]), int(pos[1])), 1, (55, 0, 155), -1)
else:
cv2.circle(game_data, (int(pos[0]), int(pos[1])), 3, (50, 0, 215), -1)

在offensive_force_buildings(self)方法中添加建造机械台

            if self.units(CYBERNETICSCORE).ready.exists:
if len(self.units(ROBOTICSFACILITY)) < 1:
if self.can_afford(ROBOTICSFACILITY) and not self.already_pending(ROBOTICSFACILITY):
await self.build(ROBOTICSFACILITY, near=pylon)

创建scout(),训练Observer

async def scout(self):
if len(self.units(OBSERVER)) > 0:
scout = self.units(OBSERVER)[0]
if scout.is_idle:
enemy_location = self.enemy_start_locations[0]
move_to = self.random_location_variance(enemy_location)
print(move_to)
await self.do(scout.move(move_to))

else:
for rf in self.units(ROBOTICSFACILITY).ready.noqueue:
if self.can_afford(OBSERVER) and self.supply_left > 0:
await self.do(rf.train(OBSERVER))

生成随机位置,很简单。意思是横坐标累计递增-0.2和0.2倍的横坐标,限制条件为如果x超过横坐标,那么就是横坐标最大值。

纵坐标同理。

    def random_location_variance(self, enemy_start_location):
x = enemy_start_location[0]
y = enemy_start_location[1]

x += ((random.randrange(-20, 20))/100) * enemy_start_location[0]
y += ((random.randrange(-20, 20))/100) * enemy_start_location[1]

if x < 0:
x = 0
if y < 0:
y = 0
if x > self.game_info.map_size[0]:
x = self.game_info.map_size[0]
if y > self.game_info.map_size[1]:
y = self.game_info.map_size[1]

go_to = position.Point2(position.Pointlike((x,y)))
return go_to

完整代码如下

# -*- encoding: utf-8 -*-
'''
@File : demo.py
@Modify Time @Author @Desciption
------------ ------- -----------
2019/11/3 12:32 Jonas None
'''

import sc2
from sc2 import run_game, maps, Race, Difficulty, position
from sc2.player import Bot, Computer
from sc2.constants import *
import random
import numpy as np
import cv2


class SentdeBot(sc2.BotAI):
def __init__(self):
# 经过计算,每分钟大约165迭代次数
self.ITERATIONS_PER_MINUTE = 165
# 最大农民数量
self.MAX_WORKERS = 50

async def on_step(self, iteration: int):
self.iteration = iteration
await self.scout()
await self.distribute_workers()
await self.build_workers()
await self.build_pylons()
await self.build_assimilators()
await self.expand()
await self.offensive_force_buildings()
await self.build_offensive_force()
await self.intel()
await self.attack()

## 侦察
async def scout(self):
if len(self.units(UnitTypeId.OBSERVER)) > 0:
scout = self.units(UnitTypeId.OBSERVER)[0]
if scout.is_idle:
enemy_location = self.enemy_start_locations[0]
move_to = self.random_location_variance(enemy_location)
print(move_to)
await self.do(scout.move(move_to))

else:
for rf in self.units(UnitTypeId.ROBOTICSFACILITY).ready.noqueue:
if self.can_afford(UnitTypeId.OBSERVER) and self.supply_left > 0:
await self.do(rf.train(UnitTypeId.OBSERVER))

async def intel(self):
game_data = np.zeros((self.game_info.map_size[1], self.game_info.map_size[0], 3), np.uint8)

# UnitTypeId作为key,半径和颜色是value
draw_dict = {
UnitTypeId.NEXUS: [15, (0, 255, 0)],
UnitTypeId.PYLON: [3, (20, 235, 0)],
UnitTypeId.PROBE: [1, (55, 200, 0)],
UnitTypeId.ASSIMILATOR: [2, (55, 200, 0)],
UnitTypeId.GATEWAY: [3, (200, 100, 0)],
UnitTypeId.CYBERNETICSCORE: [3, (150, 150, 0)],
UnitTypeId.STARGATE: [5, (255, 0, 0)],
UnitTypeId.ROBOTICSFACILITY: [5, (215, 155, 0)],

UnitTypeId.VOIDRAY: [3, (255, 100, 0)],
# OBSERVER: [3, (255, 255, 255)],
}

for unit_type in draw_dict:
for unit in self.units(unit_type).ready:
pos = unit.position
cv2.circle(game_data, (int(pos[0]), int(pos[1])), draw_dict[unit_type][0], draw_dict[unit_type][1], -1)

# 主基地名称
main_base_names = ["nexus", "supplydepot", "hatchery"]
# 记录敌方基地位置
for enemy_building in self.known_enemy_structures:
pos = enemy_building.position
# 不是主基地建筑,画小一些
if enemy_building.name.lower() not in main_base_names:
cv2.circle(game_data, (int(pos[0]), int(pos[1])), 5, (200, 50, 212), -1)
for enemy_building in self.known_enemy_structures:
pos = enemy_building.position
if enemy_building.name.lower() in main_base_names:
cv2.circle(game_data, (int(pos[0]), int(pos[1])), 15, (0, 0, 255), -1)

for enemy_unit in self.known_enemy_units:

if not enemy_unit.is_structure:
worker_names = ["probe", "scv", "drone"]
# if that unit is a PROBE, SCV, or DRONE... it's a worker
pos = enemy_unit.position
if enemy_unit.name.lower() in worker_names:
cv2.circle(game_data, (int(pos[0]), int(pos[1])), 1, (55, 0, 155), -1)
else:
cv2.circle(game_data, (int(pos[0]), int(pos[1])), 3, (50, 0, 215), -1)

for obs in self.units(UnitTypeId.OBSERVER).ready:
pos = obs.position
cv2.circle(game_data, (int(pos[0]), int(pos[1])), 1, (255, 255, 255), -1)

# flip horizontally to make our final fix in visual representation:
flipped = cv2.flip(game_data, 0)
resized = cv2.resize(flipped, dsize=None, fx=2, fy=2)

cv2.imshow('Intel', resized)
cv2.waitKey(1)

def random_location_variance(self, enemy_start_location):
x = enemy_start_location[0]
y = enemy_start_location[1]

x += ((random.randrange(-20, 20)) / 100) * enemy_start_location[0]
y += ((random.randrange(-20, 20)) / 100) * enemy_start_location[1]

if x < 0:
x = 0
if y < 0:
y = 0
if x > self.game_info.map_size[0]:
x = self.game_info.map_size[0]
if y > self.game_info.map_size[1]:
y = self.game_info.map_size[1]

go_to = position.Point2(position.Pointlike((x, y)))
return go_to

# 建造农民
async def build_workers(self):
# 星灵枢钮*16(一个基地配备16个农民)大于农民数量并且现有农民数量小于MAX_WORKERS
if len(self.units(UnitTypeId.NEXUS)) * 16 > len(self.units(UnitTypeId.PROBE)) and len(
self.units(UnitTypeId.PROBE)) < self.MAX_WORKERS:
# 星灵枢纽(NEXUS)无队列建造,可以提高晶体矿的利用率,不至于占用资源
for nexus in self.units(UnitTypeId.NEXUS).ready.noqueue:
# 是否有50晶体矿建造农民
if self.can_afford(UnitTypeId.PROBE):
await self.do(nexus.train(UnitTypeId.PROBE))

## 建造水晶
async def build_pylons(self):
## 供应人口和现有人口之差小于5且建筑不是正在建造
if self.supply_left < 5 and not self.already_pending(UnitTypeId.PYLON):
nexuses = self.units(UnitTypeId.NEXUS).ready
if nexuses.exists:
if self.can_afford(UnitTypeId.PYLON):
await self.build(UnitTypeId.PYLON, near=nexuses.first)

## 建造吸收厂
async def build_assimilators(self):
for nexus in self.units(UnitTypeId.NEXUS).ready:
# 在瓦斯泉上建造吸收厂
vaspenes = self.state.vespene_geyser.closer_than(15.0, nexus)
for vaspene in vaspenes:
if not self.can_afford(UnitTypeId.ASSIMILATOR):
break
worker = self.select_build_worker(vaspene.position)
if worker is None:
break
if not self.units(UnitTypeId.ASSIMILATOR).closer_than(1.0, vaspene).exists:
await self.do(worker.build(UnitTypeId.ASSIMILATOR, vaspene))

## 开矿
async def expand(self):
# (self.iteration / self.ITERATIONS_PER_MINUTE)是一个缓慢递增的值,动态开矿
if self.units(UnitTypeId.NEXUS).amount < self.iteration / self.ITERATIONS_PER_MINUTE and self.can_afford(
UnitTypeId.NEXUS):
await self.expand_now()

## 建造进攻性建筑
async def offensive_force_buildings(self):
print(self.iteration / self.ITERATIONS_PER_MINUTE)
if self.units(UnitTypeId.PYLON).ready.exists:
pylon = self.units(UnitTypeId.PYLON).ready.random
# 根据神族建筑科技图,折跃门建造过后才可以建造控制核心
if self.units(UnitTypeId.GATEWAY).ready.exists and not self.units(UnitTypeId.CYBERNETICSCORE):
if self.can_afford(UnitTypeId.CYBERNETICSCORE) and not self.already_pending(UnitTypeId.CYBERNETICSCORE):
await self.build(UnitTypeId.CYBERNETICSCORE, near=pylon)
# 否则建造折跃门
# (self.iteration / self.ITERATIONS_PER_MINUTE)/2 是一个缓慢递增的值
# elif len(self.units(UnitTypeId.GATEWAY)) < ((self.iteration / self.ITERATIONS_PER_MINUTE) / 2):
elif len(self.units(UnitTypeId.GATEWAY)) < 1:
if self.can_afford(UnitTypeId.GATEWAY) and not self.already_pending(UnitTypeId.GATEWAY):
await self.build(UnitTypeId.GATEWAY, near=pylon)
# 控制核心存在的情况下建造机械台
if self.units(UnitTypeId.CYBERNETICSCORE).ready.exists:
if len(self.units(UnitTypeId.ROBOTICSFACILITY)) < 1:
if self.can_afford(UnitTypeId.ROBOTICSFACILITY) and not self.already_pending(
UnitTypeId.ROBOTICSFACILITY):
await self.build(UnitTypeId.ROBOTICSFACILITY, near=pylon)

# 控制核心存在的情况下建造星门
if self.units(UnitTypeId.CYBERNETICSCORE).ready.exists:
if len(self.units(UnitTypeId.STARGATE)) < ((self.iteration / self.ITERATIONS_PER_MINUTE) / 2):
if self.can_afford(UnitTypeId.STARGATE) and not self.already_pending(UnitTypeId.STARGATE):
await self.build(UnitTypeId.STARGATE, near=pylon)

## 造兵
async def build_offensive_force(self):
# 无队列化建造
# for gw in self.units(UnitTypeId.GATEWAY).ready.noqueue:
# if not self.units(UnitTypeId.STALKER).amount > self.units(UnitTypeId.VOIDRAY).amount:
#
# if self.can_afford(UnitTypeId.STALKER) and self.supply_left > 0:
# await self.do(gw.train(UnitTypeId.STALKER))

for sg in self.units(UnitTypeId.STARGATE).ready.noqueue:
if self.can_afford(UnitTypeId.VOIDRAY) and self.supply_left > 0:
await self.do(sg.train(UnitTypeId.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_units) > 0:
# 随机选取敌方建筑
return random.choice(self.known_enemy_structures)
else:
# 返回敌方出生点位
return self.enemy_start_locations[0]

## 进攻
async def attack(self):
# {UNIT: [n to fight, n to defend]}
aggressive_units = {UnitTypeId.VOIDRAY: [8, 3]}

for UNIT in aggressive_units:
# 攻击模式
if self.units(UNIT).amount > aggressive_units[UNIT][0] and self.units(UNIT).amount > aggressive_units[UNIT][
1]:
for s in self.units(UNIT).idle:
await self.do(s.attack(self.find_target(self.state)))
# 防卫模式
elif self.units(UNIT).amount > aggressive_units[UNIT][1]:
if len(self.known_enemy_units) > 0:
for s in self.units(UNIT).idle:
await self.do(s.attack(random.choice(self.known_enemy_units)))


## 启动游戏
run_game(maps.get("AcidPlantLE"), [
Bot(Race.Protoss, SentdeBot()), Computer(Race.Terran, Difficulty.Hard)
], realtime=False)

运行结果如下,红色和粉红色是敌方单位。

作者:Rest探路者 出处:http://www.cnblogs.com/Java-Starter/

回复下方「关键词」,获取优质资源

回复关键词「 pybook03」,立即获取主页君与小伙伴一起翻译的《Think Python 2e》电子版

回复关键词「入门资料」,立即获取主页君整理的 10 本 Python 入门书的电子版

回复关键词「m」,立即获取Python精选优质文章合集

回复关键词「book 数字」,将数字替换成 0 及以上数字,有惊喜好礼哦~

推荐阅读

题图:pexels,CC0 授权。

详解 pysc2 中的 Observation 和 Action 详解 pysc2 中的 Observation 和 Action SCII 环境具有非常丰富的动作空间和状态空间。Pysc2 接口从游戏中读取并提供给我们使用的信息有两类:空间/视觉类的(spatial/visual);结构性的元素(structured elements),其中结构性的元素主要是提供一些重要的数据,而且这些数据对于机器来说往往很难通过游戏画面直接读取,比如燃料的数量,所以接口直接提供这些数据。 Important! 从observation中获取得到的坐标信息是 (y,x) 形式的,即纵坐 阅读详情

相关推荐

基于AI挑战《星际争霸II(StarCraft II)》的Windows版本下载安装详细教程

2、双击打开Battle.net-Setup,选择安装语言(我选的是US版本的)这个根据需要就行,什么语言都可,然后点击Continue继续,等几十秒;我以为下载US版本的战网可以安装英文的星际争霸II,事实证明不行,所以选简体中文的完全OK。8、点击ChangeFolder改安装路径(默认C盘,建议更改不然29G可不是闹着玩的);3、如果需要更改安装路径点Change更改就行,然后点击Continue就开始安装了;4、安装好后需要登录自己的战网账号,没有的需要点免费。5、登录后点账号下的离线登录;

m0_37802038的博客 5922

【python-sc2】详细解析!!!手把手教你学会实现星际争霸2游戏AI智能体的基础知识!!!

超级详细的python-sc2环境的介绍,帮助读者实现自己的星际争霸2游戏AI智能体!!!

ZhuanShangNiDeXin的博客 4404

贼好玩!我用Python写了一个AI玩星际争霸2!

Deepmind 开放了自己的星际争霸机器学习环境,现在只需要安装对应的 pysc2 包,就可以自己写一个星际2 AI啦!本文是Rest探路者分享在博客园的一个相关项目,里面有非常详尽的代码,有兴趣的小伙伴可以参考。 作者:Rest探路者 出处:http://www.cnblogs.com/Java-Starter/ 准备 我的环境是python3.6,sc2包0.11.1,机器学习包:pysc2,地图下载链接maps:https://github.com/Blizzard/s2client-..

爬遍所有网站 1222

配置PySC2 - 星际争霸 II 学习环境

星际争霸ai

weixin_51568130的博客 881

用Python做的小游戏合集来咯~自行开发一个星际争霸小游戏~

导语:哈喽铁汁们今天我们就用Python做一个炒鸡酷炫的小游戏——星际争霸!! 玩游戏的高端玩法就是玩自己发放的~如果你跟小编一样喜欢玩各式各样的小游戏那可就得关注我啦! 想领取完整源码跟更多Python学习资料的可私信我或点击这行字体 正文:废话不多说了~咱就开始吧???????? 游戏介绍:星际争霸(UniWar)——最好的多人在线回合制战略游戏现在登陆Android系统! UniWar(星际争霸)是Android平台上的一款多人在线回合制战略游戏。这款游戏更早是在iPhone平台上的,大

L010409的博客 1249

保姆级教程:用Python-sc2为星际争霸2写个AI,从环境配置到第一个能动的Bot

本文提供了一份详细的Python-sc2教程,教你如何从零开始为星际争霸2编写AI机器人。内容涵盖环境配置、基础Bot实现、游戏数据理解、经济运营、调试优化以及进阶战术AI开发,帮助开发者快速掌握游戏AI编程技巧,打造能实际对战的智能体。

weixin_33696106的博客 242

Python深度学习SC2(星际争霸2)AI

战网下载sc2 python3(这里用python3.9) 下载游戏地图,前往Blizzard s2client的“ 地图包”部分并下载一些地图。 https://github.com/Blizzard/s2client-proto#map-packs 下载好后将地图放入SC2的安装目录的Maps下(没有Maps则新建)结构为: 为了方便以星灵种族为例: 游戏内容参考资料 https://liquipedia.net/starcraft2/Protoss_Units_(Legacy_of_the_Void

Kilvin的博客 5065

星际争霸AI对战开发:Python与机器学习实战

星际争霸AI研究的重要性在于其为AI技术的挑战和创新提供了广阔的舞台。这项研究不仅能够推动游戏AI本身的进步,还能够促进相关技术在医疗、金融、自动驾驶等领域的实际应用。通过不断优化AI算法,解决星际争霸中复杂的决策和实时操作问题,研究人员在提高AI性能和智能水平方面取得了显著成效,为未来AI技术的发展开辟了新的可能。

weixin_35516624的博客 1090

星际争霸2 AI 强化学习环境部署

星际争霸2 AI 强化学习环境部署 PySC2是DeepMind开发的星际争霸Ⅱ学习环境(SC2LE)的Python组件。 它封装Blizzard Entertainment的星际争霸Ⅱ机器学习API,提供Python 增强学习环境。 1、安装Pysc2 在CMD 下 使用 pip 自动安装 pip install pysc2 并且安装深度学习组件TensorFlow pip install Te...

qq_44469621的博客 2618

PySC2:星际争霸II学习环境-开源

PySC2 是 DeepMind 的星际争霸 II 学习环境 (SC2LE) 的 Python 组件。 它将暴雪娱乐的星际争霸 II 机器学习 API 作为 Python RL 环境公开。 这是 DeepMind 和暴雪之间的合作,旨在将星际争霸 II 开发成一个丰富的 RL 研究环境。 PySC2 为 RL 代理提供了一个接口,用于与星际争霸 2 交互、获取观察和发送动作。 获得 PySC2 的最简单方法是使用 pip。 这将安装 pysc2 包以及所有必需的依赖项。 virtualenv 可以帮助管理您的依赖项。 您可能还需要升级 pip: pip install --upgrade pip 才能使 pysc2 安装工作。 如果您在旧系统上运行,您可能需要为 pygame 依赖项安装 libsdl 库。

斗罗大陆叙事体系与战斗系统设计解析

在文学创作与游戏设计中,世界观构建和战斗系统设计是两大核心技术要素。世界观作为故事发生的背景框架,需要融合东西方文化元素并建立量化标准,如《斗罗大陆》中武魂觉醒与魂环等级体系。战斗系统则需突破简单数值对抗,发展出武魂特性、魂技组合与环境互动的三维体系,其中魂导器技术的引入展现了科技与魔法的创新融合。这些设计原理在RPG游戏开发、网络文学创作等领域具有广泛应用价值,特别是对需要长期运营的IP作品,完善的系统设定能有效支撑剧情延展与商业化开发。本文以现象级作品为例,剖析其武魂拟态理论和魂师工业化构思如何成就经典

weixin_29291069的博客 258

星际争霸2 AI开发

准备 我的环境是python3.6,sc2包0.11.1 机器学习包下载链接:pysc2 地图下载链接:maps 游戏下载链接:国际服 国服 pysc2是DeepMind开发的星际争霸Ⅱ学习环境。 它是封装星际争霸Ⅱ机器学习API,同时也提供Python增强学习环境。 以神族为例编写代码,神族建筑科技图如下: 教程 采矿 # -*- encoding: utf-8 -*- ''' ...

Jinyao的博客 1106

STM32CubeMX 6.4.0 + STM32F407ZGT6 实战:基于YT8512C PHY的lwIP以太网配置与调试

本文详细介绍了使用STM32CubeMX 6.4.0为STM32F407ZGT6微控制器配置YT8512C PHY芯片,并成功移植lwIP以太网协议栈的实战过程。文章从硬件差异分析入手,逐步讲解时钟配置、ETH外设设置、PHY寄存器适配以及lwIP协议栈剪裁等关键步骤,旨在帮助开发者解决非标准PHY芯片的联网难题,最终实现网络连通与Ping测试。

n8m7b6v5c4的博客 600

python-sc2 星际争霸2接口的运行-随笔

跑出来sc2py的一路踩坑记录

natural_Caduceus 1072

Dify整合FireCrawl与百度搜索实战:手把手教你打造全能研究助手

本文手把手教你基于Dify平台,整合FireCrawl网页爬虫与百度搜索能力,构建一个能同时处理本地文档与实时网络信息的全能研究助手。通过部署核心环境、配置模型、接入两大工具并设计自动化工作流,实现从问题提出到深度分析报告生成的一站式解决方案,极大提升信息调研与整合效率。

weixin_29062963的博客 501

工业视觉检测实战指南:从硬件配置到AI算法部署

本文提供了一套完整的工业视觉检测系统搭建实战指南。从硬件选型(相机、光源、镜头、工控机)到AI算法(深度学习模型)部署,详细解析了如何为生产线配置一双“会思考的眼睛”。重点探讨了深度学习算法在复杂缺陷识别中的应用,并分享了模型训练、优化及云边协同部署的实战心得,旨在帮助工程师实现从实验室Demo到7x24小时稳定运行的工业落地。

weixin_29051193的博客 465

使用API制作星际争霸2AI

项目地址 https://github.com/AI-for-starcraft2 https://github.com/AI-for-starcraft2/mod-for-starcraft2 aphstar 因为图像识别技术不成熟,所以aphstar使用暴雪后台提供的接口来进行识别和检测单位,并不是真正意义像玩家一样操控单位。 aphstar原理 https://github.com/zhoubolei/introRL/blob/master/lecture_alphastar.pdf 很美,不是吗。我

fengmao31的博客 2201

使用AI预测彩票的架构思路

彩票是随机的数字游戏,不要过度依赖AI,本文仅供娱乐研究

14 年后端老兵,专注工程实战与银河麒麟信创运维。把每个真实生产事故,拆成能复现、能上线的保姆级教程。代码开源,评论区一起排错。 9435

星际争霸2 AI开发(持续更新)

准备 我的环境是python3.6,sc2包0.11.1 机器学习包下载链接:pysc2 地图下载链接maps pysc2是DeepMind开发的星际争霸Ⅱ学习环境。 它是封装星际争霸Ⅱ机器学习API,同时也提供Python增强学习环境。 以神族为例编写代码,神族建筑科技图如下: 采矿 # -*- encoding: utf-8 -*- ''' @File : __init_...

Jinyao的博客 2211

SCSA,scCATCH,SciBet,SingleR 四种注释方法比较

以下是和四种细胞类型注释方法的详细对比,从。

qq_40256654的博客 1219

100天精通Python(可视化篇)——第89天:Bokeh库绘图可视化基础入门(参数说明+案例实战)

专栏导读 一、Bokeh是什么? 二、安装与导入 三、Bokeh接口介绍 四、创建图表 五、添加自定义渲染器 切换主题 添加图例 图例位置 图例方向 图例背景和边界 图例文本的外观 行列布局 网格布局

努力让自己发光,对的人才能迎着光而来 1万+

探索星际争霸II的AI世界:Python-SC2库介绍

在数字世界的星际战场上,星际争霸II(StarCraft II)不仅是一款深受玩家喜爱的即时战略游戏,也是人工智能研究的沃土。今天,我们要介绍的是一个专为Python 3开发者设计的星际争霸II API客户端——Python-SC2库。这个项目的目标是提供一个简单易用的接口,让开发者能够轻松编写AI机器人,参与到这场星际的较量中。 ## 项目技术分析 Python-SC2库是一个专注于提供高效

gitblog_00201的博客 617

nvidia系列教程-AGX-Orin基础环境搭建

NVIDIA Jetson AGX Orin 是一款功能强大的嵌入式AI平台,专为需要高性能和低功耗的边缘计算应用设计。无论是自动驾驶、机器人,还是智能监控系统,Jetson AGX Orin 都能为这些应用提供强大的计算能力。本篇博客将为大家详细介绍如何在AGX Orin(32GB)上搭建基础开发环境,包括系统安装、CUDA和cuDNN的配置等,帮助你快速上手这个强大的平台。架构: 搭载 56 个 Tensor Core 的 1792 核 NVIDIA Ampere c GPUCUDA Cores。

flypig has a dream! 2802

推荐:Python-SC2 - 使用Python玩转《星际争霸II》API

推荐:Python-SC2 - 使用Python玩转《星际争霸II》API 项目地址:https://gitcode.com/gh_mirrors/pyt/python-sc2 如果你是《星际争霸II》(StarCraft II)的爱好者,并对编程和AI有兴趣,那么项目绝对值得你关注。这是一个由BurnySc2开发的库,它提供了一个简洁、易于使用的Python接口,让你能够编写程序与《星际争霸II...

gitblog_00044的博客 777

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

python-sc2快速上手指南:20行代码写出第一个星际争霸II AI机器人

python-sc2 是一个用于 StarCraft II(星际争霸II)的 Python 3 AI 机器人 API 客户端库,它的核心目标是"简单":一个能实战的 worker rush 机器人只需要约20行代码,而不是200行。无论你是游戏AI初学者还是想研究机器学习的开发者,这篇 python-sc2 入门教程都能帮你快速写出并运行第一个星际争霸II AI机器人。 ## 一、python-

gitblog_00120的博客 512

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: 想不想在手机上敲 Python 代码?!这里有一款推荐方案
下一篇: 如何用 Python 预测房价走势?
codingpy
博客等级 码龄11年 1891粉丝 104原创
评论 7
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值