def drawRectangleOnUnit(Broodwar, unit, width=20, height=20, color=cybw.Colors.Blue): '''Draws a rectangle with the unit being in the center of the drawn rectangle.''' half_width = int(width/2) half_height = int(height/2) position = unit.getPosition() Broodwar.drawBoxMap(cybw.Position(position.x-half_width, position.y-half_height), cybw.Position(position.x+half_width, position.y+half_height), color)
def draw_box(self): for u in Broodwar.self().getUnits(): Broodwar.drawBoxMap(u.getPosition() - cybw.Position(X_PIXELS/2,Y_PIXELS/2), u.getPosition() + cybw.Position(X_PIXELS/2,Y_PIXELS/2), cybw.Colors.Red) a = self.get_local_state_np(u) for x in range(X_SIZE): for y in range(Y_SIZE): # if a[x][y][0] == 1: # # left_top = u.getPosition() - cybw.Position(X_PIXELS/2, Y_PIXELS/2) # Broodwar.drawBoxMap(left_top + cybw.Position(x / X_SIZE * X_PIXELS, y / Y_SIZE * Y_PIXELS), # left_top + cybw.Position((x+1) / X_SIZE * X_PIXELS, (y+1) / Y_SIZE * Y_PIXELS), # cybw.Colors.Red) # el if a[x][y][5] > 0.1: left_top = u.getPosition() - cybw.Position(X_PIXELS / 2, Y_PIXELS / 2) Broodwar.drawBoxMap(left_top + cybw.Position(x / X_SIZE * X_PIXELS, y / Y_SIZE * Y_PIXELS), left_top + cybw.Position((x + 1) / X_SIZE * X_PIXELS, (y + 1) / Y_SIZE * Y_PIXELS), cybw.Colors.Blue, True) del a break
def update(self, allies, enemies): ''' Update loop for individual units and implementation of our hybrid algorithm Will find a path to its general target, then use flocking behavior for local control Flocking parameters will be tuned using a learning algorithm ''' #for now, values are harcoded just to make sure it works values = self.getGeneticParameters() visionRange = values[0] self.moveDirection = [0, 0] # Determine If using Flocking or A* flocking = False nearbyEnemies = [] nearbyAllies = [] for enemy in enemies: if self.unit.getDistance(enemy.getUnit()) < visionRange: flocking = True nearbyEnemies.append(enemy) for ally in allies: if self.unit.getDistance(ally.getUnit()) < visionRange: nearbyAllies.append(ally) if self.attackFrames > 0: self.attackFrames += -1 if flocking: self.flockingAlgorithm(nearbyAllies, nearbyEnemies, values) # TODO: Decide Movement vs Attack # print(self.unit.isAttackFrame()) # print(self.getType().groundWeapon().damageCooldown()) # print(self.unit.getGroundWeaponCooldown()) # if self.unit.getGroundWeaponCooldown() == 0: # print(self.attackFrames) # if self.unit.getGroundWeaponCooldown() == 0: # print(self.getType().groundWeapon().maxRange()) # print(self.attackFrames) if self.attackFrames == 0: target = self.decideAttackTarget(nearbyEnemies) # print(self.unit.getDistance(target.getUnit())) # if self.unit.getDistance(enemy.getUnit()) < self.getType().groundWeapon().maxRange() + 30: self.unit.rightClick(target.getUnit()) target.addAttacker() self.targetLocation = target self.attackFrames = self.attackCoooldown return elif self.attackFrames < self.attackCoooldown / 2: pos = self.unit.getPosition() move = cybw.Position(pos.getX() + self.moveDirection[0], pos.getY() + self.moveDirection[1]) self.unit.rightClick(move) self.targetLocation = move #[pos.getX() + self.moveDirection[0], pos.getY() + self.moveDirection[1]] else: # Run A* if self.generalTarget != cybw.Position(0, 0): self.unit.rightClick(self.generalTarget)
def drawGrid(Broodwar, unit, width=320, height=320, rows=2, columns=2, color=cybw.Colors.Blue): '''Draws a Grid with the unit being in the center of the drawn Grid.''' half_width = int(width/2) half_height = int(height/2) position = unit.getPosition() row_width = int(width/rows) column_height = int(height/columns) for row in range(rows): for column in range(columns): Broodwar.drawBoxMap(cybw.Position(position.x-half_width++row*row_width, position.y-half_height+column*column_height), cybw.Position(position.x-half_width+(row+1)*row_width, position.y-half_height++(column+1)*column_height), color)
def drawStats(self): line = 0 allUnitTypes = cybw.UnitTypes.allUnitTypes() Broodwar.drawTextScreen( cybw.Position(5, 0), "I have " + str(Broodwar.self().allUnitCount()) + " units:") for unitType in allUnitTypes: count = Broodwar.self().allUnitCount(unitType) if count > 0: line += 1 statStr = "- " + str(count) + " " + str(unitType) Broodwar.drawTextScreen(cybw.Position(5, 12 * line), statStr)
def drawRectangleOnUnit(Broodwar, unit, width=20, height=20, color=cybw.Colors.Blue): half_width = int(width / 2) half_height = int(height / 2) position = unit.getPosition() Broodwar.drawBoxMap( cybw.Position(position.x - half_width, position.y - half_height), cybw.Position(position.x + half_width, position.y + half_height), color)
def moveDiagnostics(self): ''' Print information about each boid''' line = 2 for unit in self.units: line += 1 statStr = str(unit.getType()) + ": " + str( unit.getPosition()) + " Target: " + str( unit.getTargetLocation()) #getTargetLocation() Broodwar.drawTextScreen(cybw.Position(5, 12 * line), statStr)
def getFleePosition(self): avgx = 0 avgy = 0 sx = self.singleAgent.getPosition().getX() sy = self.singleAgent.getPosition().getY() count = 0 for u in Broodwar.enemy().getUnits(): p = u.getPosition() dist = self.singleAgent.getDistance(u) + 0.01 if (dist < 32 * 8): avgx = avgx + (sx - p.getX()) / dist avgy = avgy + (sy - p.getY()) / dist count = count + 1 if (count is 0): return self.singleAgent.getPosition() length = math.sqrt(avgx * avgx + avgy * avgy) if (length > 0): vecx = avgx / length vecy = avgy / length else: print("LENGTH IS ZERO 11") leftR = max(0, self.margin - self.singleAgent.getPosition().getX()) / self.margin rightR = max( 0, self.margin - (Broodwar.mapWidth() * 32 - self.singleAgent.getPosition().getX())) / self.margin upR = max(0, self.margin - self.singleAgent.getPosition().getY()) / self.margin downR = max( 0, self.margin - (Broodwar.mapHeight() * 32 - self.singleAgent.getPosition().getY())) / self.margin vecx = vecx + (leftR - rightR) * self.repulsePower vecy = vecy + (upR - downR) * self.repulsePower length = math.sqrt(vecx * vecx + vecy * vecy) if (length > 0): vecx = vecx / length vecy = vecy / length else: print("LENGTH IS ZERO 22") npx = self.singleAgent.getPosition().getX() + int( 32 * vecx * self.FLEE_COEFF) npy = self.singleAgent.getPosition().getY() + int( 32 * vecy * self.FLEE_COEFF) npx = clamp(npx, 0, Broodwar.mapWidth() * 32) npy = clamp(npy, 0, Broodwar.mapHeight() * 32) return cybw.Position(npx, npy)
def enemyCenter(self): ''' a method to calculate the center of all enemies acts as a basic form of attack move on a group''' center = [0, 0] length = len(self.enemies) for enemy in self.enemies: center[0] = center[0] + enemy.getPosition().getX() / length center[1] = center[1] + enemy.getPosition().getY() / length return [cybw.Position(center[0], center[1])]
def drawGrid(X, Y, width=320, height=320, rows=2, columns=2, color=cybw.Colors.Blue): '''Draws a Grid with the unit being in the center of the drawn Grid.''' Broodwar = cybw.Broodwar half_width = width // 2 half_height = height // 2 row_width = width // rows column_height = height // columns for row in range(rows): for column in range(columns): Broodwar.drawBoxMap( cybw.Position(X + row * row_width, Y + column * column_height), cybw.Position(X + (row + 1) * row_width, Y + (column + 1) * column_height), color)
def get_terrain_distance(unit, direction): dx, dy = index_to_direction(direction) sight_range = unit.getType().sightRange() d = 0 while d < sight_range: wpos = cybw.WalkPosition(unit.getPosition() + cybw.Position(d * dx, d * dy)) if not Broodwar.isWalkable(wpos): return d else: d += 20 return d
def drawBullets(self): bullets = Broodwar.getBullets() for bullet in bullets: p = bullet.getPosition() velocityX = bullet.getVelocityX() velocityY = bullet.getVelocityY() lineColor = cybw.Colors.Red textColor = cybw.Text.Red if bullet.getPlayer == Broodwar.self(): lineColor = cybw.Colors.Green textColor = cybw.Text.Green Broodwar.drawLineMap(p, p + cybw.Position(velocityX, velocityY), lineColor) Broodwar.drawTextMap(p, chr(textColor) + str(bullet.getType()))
def drawVisibilityData(self): wid = Broodwar.mapWidth() hgt = Broodwar.mapHeight() for x in range(wid): for y in range(hgt): drawColor = cybw.Colors.Red if Broodwar.isExplored(tileX=x, tileY=y): if Broodwar.isVisible(tileX=x, tileY=y): drawColor = cybw.Colors.Green else: drawColor = cybw.Colors.Blue Broodwar.drawDotMap(cybw.Position(x * 32 + 16, y * 32 + 16), drawColor)
def __init__(self, actualUnit): self.unit = actualUnit self.generalTarget = '' self.attackTarget = [] self.moveDirection = [0, 0] self.flockingAlgorithm = self.flockingV1 self.targetLocation = cybw.Position(1000, 200) self.decideAttackTarget = self.attackLowEnemy self.visionRange = 130 self.attackState = False self.attackCoooldown = self.getType().groundWeapon().damageCooldown( ) + 3 self.attackFrames = 0 self.maxAttackers = 2
def get_minimap_state_np(self): local_force_map = np.zeros((X_SIZE, Y_SIZE, FORCE_TYPE), dtype=np.float32) local_terrain_map = np.zeros((X_SIZE, Y_SIZE, 1), dtype=np.float32) local_visible_map = np.zeros((X_SIZE, Y_SIZE, 1), dtype=np.float32) for ou in Broodwar.self().getUnits(): if not ou.exists(): continue oup = ou.getPosition() lx, ly = self.to_minimap_space(oup) local_force_map[lx, ly, self.get_force(ou)] = 1 for ou in Broodwar.enemy().getUnits(): if not ou.exists(): continue oup = ou.getPosition() lx, ly = self.to_minimap_space(oup) local_force_map[lx, ly, self.get_force(ou)] = 1 for x in range(X_SIZE): for y in range(Y_SIZE): gx, gy = self.minimap_to_world_space(x, y) wpos = cybw.WalkPosition(cybw.Position(gx, gy)) tpos = cybw.TilePosition(cybw.Position(gx, gy)) w = 1 if Broodwar.isWalkable(wpos) else 0 v = 1 if Broodwar.isVisible(tpos) else 0 local_terrain_map[x, y, 0] = w local_visible_map[x, y, 0] = v total_map = np.concatenate((local_force_map, local_terrain_map, local_visible_map), axis=2) #print(local_terrain_map.sum(), " TERRAIN SUM") del local_visible_map del local_terrain_map del local_force_map return total_map
def apply_action(unit, action): if (action == DIM_DIRECTION): target = get_attack_enemy_unit(unit) if target is not None: unit.stop() unit.attack(target) else: unit.holdPosition() else: dx, dy = index_to_direction(action) target = unit.getPosition() + cybw.Position(dx * 64, dy * 64) unit.rightClick(target) return target
def get_local_state_np(self, own): local_type_map = np.zeros((X_SIZE, Y_SIZE, UNIT_TYPE), dtype=np.float32) local_force_map = np.zeros((X_SIZE, Y_SIZE, FORCE_TYPE), dtype=np.float32) local_health_map = np.zeros((X_SIZE, Y_SIZE, 1), dtype=np.float32) local_terrain_map = np.zeros((X_SIZE, Y_SIZE, 1), dtype=np.float32) #local_type_map = np.zeros((X_SIZE, Y_SIZE)) #local_type_map = np.zeros((X_SIZE, Y_SIZE)) op = own.getPosition() for ou in Broodwar.self().getUnits(): if not self.include_self and ou.getID() == own.getID(): continue if not ou.exists(): continue oup = ou.getPosition() if self.in_rectangle(op, oup): lx, ly = self.to_observation_space(op, oup) local_type_map[lx, ly, self.get_type(ou)] = 1 local_force_map[lx, ly, self.get_force(ou)] = 1 local_health_map[lx, ly, 0] = self.get_health(ou) for ou in Broodwar.enemy().getUnits(): if not ou.exists(): continue oup = ou.getPosition() if self.in_rectangle(op, oup): lx, ly = self.to_observation_space(op, oup) local_type_map[lx, ly, self.get_type(ou)] = 1 local_force_map[lx, ly, self.get_force(ou)] = 1 local_health_map[lx, ly, 0] = self.get_health(ou) for x in range(X_SIZE): for y in range(Y_SIZE): gx, gy = self.local_to_world_space(own.getPosition(), x, y) wpos = cybw.WalkPosition(cybw.Position(gx, gy)) v = 1 if Broodwar.isWalkable(wpos) else 0 local_terrain_map[x, y, 0] = v #print(local_terrain_map[:,:,0]) total_map = np.concatenate((local_type_map, local_force_map, local_health_map, local_terrain_map), axis =2) del local_type_map del local_force_map del local_health_map del local_terrain_map return total_map
def drawVisibilityData(): #Gilberto: This function does not work. It breaks python. Not sure why. wid = Broodwar.mapWidth() hgt = Broodwar.mapHeight() for x in range(wid): for y in range(hgt): drawColor = cybw.Colors.Red if Broodwar.isExplored(tileX=x, tileY=y): if Broodwar.isVisible(tileX=x, tileY=y): drawColor = cybw.Colors.Green else: drawColor = cybw.Colors.Blue #used to test how many times this function was called #its called alot but its supposed to fill map with dots of certain color #so it makes sense its called alot #drawDotMap is an overloaded function of Drawdot but drawdot is not in CYBW #so maybe thats why it doesnt work, not sure though since it seems to work #but after alot of calls it breaks. Broodwar.drawDotMap(cybw.Position(x, y), drawColor)
def draw_minimap(self): u = self.get_minimap_state_np() w = 128 h = 128 Broodwar.drawBoxScreen(cybw.Position(0,0), cybw.Position(w,h), cybw.Colors.Red) for x in range(X_SIZE): for y in range(Y_SIZE): if u[x][y][3] > 0.5: Broodwar.drawBoxScreen(cybw.Position(x / X_SIZE * w, y / Y_SIZE * h), cybw.Position((x + 1) / X_SIZE * w, (y + 1) / Y_SIZE * h), cybw.Colors.Blue, True) if u[x][y][4] > 0.5: Broodwar.drawBoxScreen(cybw.Position(x / X_SIZE * w, y / Y_SIZE * h), cybw.Position((x + 1) / X_SIZE * w, (y + 1) / Y_SIZE * h), cybw.Colors.Red, True)
def run(self): if self.printing: print("Connecting...") self.reconnect() while True: if self.printing: print("waiting to enter match") while not Broodwar.isInGame(): client.update() if not client.isConnected(): if self.printing: print("Reconnecting...") self.reconnect() else: from array import array # if self.printing: print(bytes("MarinesEven.scm",'utf-8')) # Broodwar.setMap(bytes("C:\\Program Files (x86)\\StarCraft\\Maps\\Setups\\MarinesEven.scm",'utf-8')) if self.printing: print("starting match!") # input() print("QQQ\n") params = input() # params = "-1.185099772903194 3.471395551658338 1.7649202359637872 -0.4635785111165225 2.1450278377039105" # GA Kiting # params = "-16.91585822186874 -9.062535798255029 8.826841575468919 13.134050846598603 5.3999662460067155 107.17660196984967 6.117657532505485 1.6444357636550748" self.startTime = time.time() # sleep(3) Broodwar.sendText("Hello world from python!") Broodwar.printf("Hello world from python!") # need newline to flush buffer Broodwar << "The map is " << Broodwar.mapName() << ", a " \ << len(Broodwar.getStartLocations()) << " player map" << " \n" # Enable some cheat flags Broodwar.enableFlag(cybw.Flag.UserInput) show_bullets = False show_visibility_data = False # Set Variables for game speed, and automap switching Broodwar.setLocalSpeed(0) if Broodwar.isReplay(): Broodwar << "The following players are in this replay:\n" players = Broodwar.getPlayers() # TODO add rest of replay actions else: # Broodwar << "The matchup is " << Broodwar.self().getRace( ) << " vs " << Broodwar.enemy().getRace() << "\n" # send each worker to the mineral field that is closest to it # reload(Comba) commander = CombatManager(params) units = Broodwar.self().getUnits() minerals = Broodwar.getMinerals() # print("got", len(units), "units") # print("got", len(minerals), "minerals") for unit in units: if unit.getType().isWorker(): closestMineral = None # print("worker") for mineral in minerals: if closestMineral is None or unit.getDistance( mineral) < unit.getDistance( closestMineral): closestMineral = mineral if closestMineral: unit.rightClick(closestMineral) elif unit.getType().isResourceDepot(): unit.train(Broodwar.self().getRace().getWorker()) events = Broodwar.getEvents() # print(len(events)) # Broodwar.restartGame() while Broodwar.isInGame(): # if time.time() - self.startTime > 5: # Broodwar.restartGame() # Broodwar.setMap(bytes("MarinesEven.scm",'utf-8')) Broodwar.setMap( bytes( "C:\\Program Files (x86)\\StarCraft\\Maps\\Setups\\MarinesEven.scm", 'utf-8')) events = Broodwar.getEvents() for e in events: eventtype = e.getType() if eventtype == cybw.EventType.MatchEnd: # TODO: Signal The Combat Manager the score if e.isWinner(): Broodwar << "I won the game\n" commander.signalVictory() else: Broodwar << "I lost the game\n" commander.signalDefeat() index = str(params).split(" ")[0] #str(index) + ' ' + print( str(Broodwar.self().getKillScore() - Broodwar.enemy().getKillScore())) # Broodwar.pauseGame() exit() # print("Client Received") # Broodwar.restartGame() elif eventtype == cybw.EventType.SendText: if e.getText() == "/show bullets": show_bullets = not show_bullets elif e.getText() == "/show players": showPlayers() elif e.getText() == "/show forces": showForces() elif e.getText() == "/show visibility": show_visibility_data = not show_visibility_data elif e.getText() == "/reload": #Todo: Update this for dynamic reloading reload(CombatManager) elif e.getText() == "/attack": Broodwar << "ATTACK!!!" if len(e.getText().split(" ")) > 2: commander.setAttackPos( int(e.getText().split(" ")[1]), int(e.getText().split(" ")[2])) else: pass # Broodwar << "You typed \"" << e.getText() << "\"!\n" elif eventtype == cybw.EventType.ReceiveText: pass # Broodwar << e.getPlayer().getName() << " said \"" << e.getText() << "\"\n" elif eventtype == cybw.EventType.PlayerLeft: Broodwar << e.getPlayer().getName( ) << " left the game.\n" elif eventtype == cybw.EventType.NukeDetect: if e.getPosition() is not cybw.Positions.Unknown: Broodwar.drawCircleMap(e.getPosition(), 40, cybw.Colors.Red, True) Broodwar << "Nuclear Launch Detected at " << e.getPosition( ) << "\n" else: Broodwar << "Nuclear Launch Detected.\n" elif eventtype == cybw.EventType.UnitCreate: commander.takeUnit(e.getUnit()) if not Broodwar.isReplay(): pass # Broodwar << "A " << e.getUnit() << " has been created at " << e.getUnit().getPosition() << "\n" else: if (e.getUnit().getType().isBuilding() and (e.getUnit().getPlayer().isNeutral() == False)): seconds = Broodwar.getFrameCount() / 24 minutes = seconds / 60 seconds %= 60 Broodwar.sendText( str(minutes) + ":" + str(seconds) + ": " + e.getUnit().getPlayer().getName() + " creates a " + str(e.getUnit().getType()) + "\n") elif eventtype == cybw.EventType.UnitDestroy: commander.removeUnit(e.getUnit()) if not Broodwar.isReplay(): pass # Broodwar << "A " << e.getUnit() << " has been destroyed at " << e.getUnit().getPosition() << "\n" elif eventtype == cybw.EventType.UnitMorph: if not Broodwar.isReplay(): pass # Broodwar << "A " << e.getUnit() << " has been morphed at " << e.getUnit().getPosition() << "\n" else: # if we are in a replay, then we will print out the build order # (just of the buildings, not the units). if e.getUnit().getType().isBuilding( ) and not e.getUnit().getPlayer().isNeutral(): seconds = Broodwar.getFrameCount() / 24 minutes = seconds / 60 seconds %= 60 Broodwar << str(minutes) << ":" << str( seconds) << ": " << e.getUnit().getPlayer( ).getName() << " morphs a " << e.getUnit( ).getType() << "\n" elif eventtype == cybw.EventType.UnitShow: commander.takeUnit(e.getUnit()) if not Broodwar.isReplay(): pass #Broodwar << e.getUnit() << " spotted at " << e.getUnit().getPosition() << "\n" elif eventtype == cybw.EventType.UnitHide: if not Broodwar.isReplay(): pass # Broodwar << e.getUnit() << " was last seen at " << e.getUnit().getPosition() << "\n" elif eventtype == cybw.EventType.UnitRenegade: if not Broodwar.isReplay(): pass # Broodwar << e.getUnit() << " is now owned by " << e.getUnit().getPlayer() << "\n" elif eventtype == cybw.EventType.SaveGame: Broodwar << "The game was saved to " << e.getText( ) << "\n" if show_bullets: drawBullets() if show_visibility_data: drawVisibilityData() self.drawStats() Broodwar.drawTextScreen( cybw.Position(300, 0), "FPS: " + str(Broodwar.getAverageFPS())) # Run the combatManager commander.update() client.update()
def run_episode(): if __name__ == '__main__': #ENEMY_TYPE = cybw.UnitTypes.Protoss_Zealot ENEMY_TYPE = cybw.UnitTypes.Zerg_Zergling parser = argparse.ArgumentParser() parser.add_argument('port', help='The port which the server should connect to.', type=int) args = parser.parse_args() with TwoWayClient(host='localhost', port=args.port) as s: print("Connecting...") reconnect() wins = 0 total_games = 0 games = count(1) #games = tqdm(games) #games.set_description('Gathering data...') for game_no in games: while not Broodwar.isInGame(): client.update() if not client.isConnected(): print("Reconnecting...") reconnect() Broodwar.setLocalSpeed(0) #Broodwar.setGUI(False) Broodwar.setFrameSkip(0) frame = 0 K = 10 previous_actions = None if Broodwar.isInGame(): AllUnits = Broodwar.getAllUnits() ### # Helper Functions ### health = lambda x: x.getHitPoints() + x.getShields() if x.exists() else 0 isMarine = lambda x: x.exists() and x.getType() == cybw.UnitTypes.Terran_Marine isZealot = lambda x: x.exists() and x.getType() == ENEMY_TYPE ### zealots = [e for e in Broodwar.enemy().getUnits() if isZealot(e)] beginning_EnemyHealth = sum((health(e) for e in zealots)) agents = [t for t in Broodwar.self().getUnits() if isMarine(t)] beginning_AllyHealth = sum((health(t) for t in agents)) MarineMaxHealth = max((health(t) for t in agents)) previous_AllyHealth = beginning_AllyHealth previous_EnemyHealth = beginning_EnemyHealth while Broodwar.isInGame(): terminal = len([e for e in Broodwar.getEvents() if cybw.EventType.MatchEnd == e.getType()]) == 1 AllUnits = Broodwar.getAllUnits() EnemyHealth = sum((health(e) for e in zealots)) AllyHealth = sum((health(t) for t in agents if isMarine(t))) if EnemyHealth == 0 or frame >= 2**10 or AllyHealth == 0: terminal = True if frame%K == 0: observations = [] rewards = [] for i, unit in enumerate(agents): surround = grab_surroundings(unit, Broodwar, 1024, 1024) surround = reduce(surround, 16) observations.append(surround) reward = (previous_EnemyHealth - EnemyHealth) - (previous_AllyHealth - AllyHealth) rewards.append(reward) data = {'observations': observations, 'rewards': rewards 'Terminal': terminal} pick = pickle.dumps(data) s.send(pick) actions = pickle.loads(s.read()) previous_actions = actions else: actions = previous_actions for i, unit in enumerate(agents): if unit.exists(): ################################################################## # Detects surroundings of the unit ################################################################## action = actions[i, :] #drawGrid(Broodwar, unit, width=256, height=256, rows=4, columns=4, color=cybw.Colors.Blue) #drawRectangleOnUnit(Broodwar, unit, width=1024, height=1024, color=cybw.Colors.Yellow) P = unit.getPosition() Broodwar.setScreenPosition(cybw.Position(P.x-250, P.y-250)) X = P.x - 256/2 Y = P.y - 256/2 if np.argmax(action) == 16: pass else: X = X + 64*((np.argmax(action))%4)+32 Y = Y + 64*(int((np.argmax(action))/4))+32 Position = cybw.Position(X, Y) if frame%K == 0: unit.attack(Position) #Broodwar.drawCircleMap(Position, 10, cybw.Colors.Red) '''elif np.argmax(action) < 16: X = X + 64*(np.argmax(action)%4)+32 Y = Y + 64*(int(np.argmax(action)/4))+32 Position = cybw.Position(X, Y) if frame%K == 0: unit.move(Position) Broodwar.drawCircleMap(Position, 10, cybw.Colors.Green)''' if terminal == True: observations = [] AllyHealth = [] for i, unit in enumerate(agents): surround = grab_surroundings(unit, Broodwar, 1024, 1024) surround = reduce(surround, 16) observations.append(surround) AllyHealth.append(health(unit)/MarineMaxHealth) data = {'observations': observations, 'EnemyHealth': EnemyHealth/beginning_EnemyHealth, 'AllyHealth': AllyHealth, 'Terminal': terminal} pick = pickle.dumps(data) s.send(pick) actions = pickle.loads(s.read()) previous_actions = actions frame = 0 terminal = False if game_no%5 == 0: Broodwar.leaveGame() else: Broodwar.restartGame() previous_AllyHealth = beginning_AllyHealth previous_EnemyHealth = beginning_EnemyHealth else: frame = (frame+1) previous_AllyHealth = AllyHealth previous_EnemyHealth = EnemyHealth Broodwar.drawTextScreen(cybw.Position(300, 0), "FPS: " + str(Broodwar.getAverageFPS())) client.update()
seconds) << ": " << e.getUnit().getPlayer( ).getName() << " morphs a " << e.getUnit().getType( ) << "\n" elif eventtype == cybw.EventType.UnitShow: if not Broodwar.isReplay(): Broodwar << e.getUnit() << " spotted at " << e.getUnit( ).getPosition() << "\n" elif eventtype == cybw.EventType.UnitHide: if not Broodwar.isReplay(): Broodwar << e.getUnit( ) << " was last seen at " << e.getUnit().getPosition( ) << "\n" elif eventtype == cybw.EventType.UnitRenegade: if not Broodwar.isReplay(): Broodwar << e.getUnit( ) << " is now owned by " << e.getUnit().getPlayer() << "\n" elif eventtype == cybw.EventType.SaveGame: Broodwar << "The game was saved to " << e.getText() << "\n" if show_bullets: drawBullets() if show_visibility_data: drawVisibilityData() drawStats() Broodwar.drawTextScreen(cybw.Position(300, 0), "FPS: " + str(Broodwar.getAverageFPS())) client.update() subprocess.run([ "echo", 'Win Rate: {!s} Out of: {!s}'.format(100 * wins / total_games, total_games) ])
def set_viewbox_position(self, position): '''Set the current viewbox on a given position.''' X, Y = position cybw_position = cybw.Position(X, Y) self.__Broodwar.setScreenPosition(cybw_position)
def move_to_position(self, unit_id, position): '''Move a unit to a position given its ID.''' X, Y = position cybw_position = cybw.Position(X, Y) unit = self.__Broodwar.getUnit(unit_id) return unit.move(cybw_position)
def attack_position(self, unit_id, position): '''Attack a position with a given unit ID.''' X, Y = position cybw_position = cybw.Position(X, Y) unit = self.__Broodwar.getUnit(unit_id) return unit.attack(cybw_position)
def goalDiagnostics(self): statStr = "Commander Goal: " + str(self.targetStrategy()) Broodwar.drawTextScreen(cybw.Position(40, 0), statStr)
def drawCircle(X, Y, radius=5): Broodwar = cybw.Broodwar Position = cybw.Position(X, Y) Broodwar.drawCircleMap(Position, radius, cybw.Colors.Green)
def setAttackPos(self, posx, posy): ''' Takes a positon and treats it like an attack move for all combat units ''' result = cybw.Position(posx, posy) self.target = [result]