async def init_app(): app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader( str(PROJECT_ROOT / 'templates'))) app['game'] = {} app['game']['public'] = Colorfight() app['game']['public'].replay_lock = asyncio.Lock( loop=asyncio.get_event_loop()) app['game_sockets'] = [] app['admin_password'] = os.getenv('ADMIN_PASSWORD', "") app['firebase'] = Firebase() app['process_executor'] = concurrent.futures.ProcessPoolExecutor() app['thread_executor'] = concurrent.futures.ThreadPoolExecutor() setup_routes(app) setup_static_routes(app) return app
async def init_app(): app = web.Application() aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader( str(PROJECT_ROOT / 'templates'))) app['game'] = Colorfight() app['game_sockets'] = [] setup_routes(app) setup_static_routes(app) return app
async def create_gameroom(request): data = await request.json() try: gameroom_id = data['gameroom_id'] if not url_safe(gameroom_id): return web.json_response({"success": False, "err_msg": "You have illegal special characters in you gameroom id"}) if gameroom_id in request.app['game']: return web.json_response({"success": False, "err_msg": "Same id exists"}) if len(request.app['game']) >= 10: return web.json_response({"success": False, "err_msg": "Max room number reached"}) if 'config' in data: # If it's an official game, we require a password if data['config'] == 'official': if 'admin_password' not in data: return web.json_response({"success": False, "err_msg": "You need to set a password for official game!"}) config = get_config(data['config']) else: config = get_config('default') request.app['game'][gameroom_id] = Colorfight(config = config) request.app['game'][gameroom_id].save_replay = lambda replay, data: request.app['firebase'].upload_replay(replay, data) request.app['game'][gameroom_id].replay_lock = asyncio.Lock(loop = asyncio.get_event_loop()) if 'admin_password' in data: request.app['game'][gameroom_id].admin_password = data['admin_password'] if 'join_key' in data: request.app['game'][gameroom_id].join_key = data['join_key'] except Exception as e: return web.json_response({"success": False, "err_msg": str(e)}) return web.json_response({"success": True})
def init_gamerooms(app): app['game'] = {} app['game']['public'] = Colorfight(config=get_config('constant-run'), admin_room=True) app['game']['public'].admin_password = ''
from colorfight import Colorfight import time import random from colorfight.constants import BLD_GOLD_MINE, BLD_ENERGY_WELL, BLD_FORTRESS, BLD_HOME game = Colorfight() game.connect(room='groupd') if game.register(username = '******', \ password = '******'): while True: cmd_list = [] my_attack_list = [] # update_turn() is required to get the latest information from the # server. This will halt the program until it receives the updated # information. # After update_turn(), game object will be updated. game.update_turn() # Check if you exist in the game. If not, wait for the next round. # You may not appear immediately after you join. But you should be # in the game after one round. if game.me == None: continue me = game.me # game.me.cells is a dict, where the keys are Position and the values # are MapCell. Get all my cells. newlist = list() for i in game.me.cells.values():
class Inevitable: def __init__(self): self.game = Colorfight() pass def Start(self): self.game.connect(room='public') if self.game.register(username='******', password="******"): while True: if self.Refresh(): self.FetchInfo() self.GameLoop() self.Send() def GetCell(self, pos): return self.game.game_map[pos] def Attack(self, cell, energy=None): if energy == None: energy = cell.attack_cost self.me.energy -= energy self.cmdList.append(self.game.attack(cell.position, energy)) self.attackList.append(cell.position) def Upgrade(self, cell): cellType = cell.building.name cellLevel = cell.building.level if cellType == "home": if cellLevel == 1: self.me.energy -= HOME_I[0] self.me.gold -= HOME_I[1] elif cellLevel == 2: self.me.energy -= HOME_II[0] self.me.gold -= HOME_II[1] elif cellType == "energy_well": if cellLevel == 1: self.me.energy -= ENERGY_I[0] self.me.gold -= ENERGY_I[1] elif cellLevel == 2: self.me.energy -= ENERGY_II[0] self.me.gold -= ENERGY_II[1] elif cellType == "gold_mine": if cellLevel == 1: self.me.energy -= GOLD_I[0] self.me.gold -= GOLD_I[1] elif cellLevel == 2: self.me.energy -= GOLD_II[0] self.me.gold -= GOLD_II[1] elif cellType == "fortress": if cellLevel == 1: self.me.energy -= FORTRESS_I[0] self.me.gold -= FORTRESS_I[1] elif cellLevel == 2: self.me.energy -= FORTRESS_II[0] self.me.gold -= FORTRESS_II[1] self.cmdList.append(self.game.upgrade(cell.position)) def CanBuild(self, building): if building == BLD_ENERGY_WELL: return self.me.energy >= ENERGY_I[0] and self.me.gold >= ENERGY_I[1] elif building == BLD_GOLD_MINE: return self.me.energy >= GOLD_I[0] and self.me.gold >= GOLD_I[1] elif building == BLD_FORTRESS: return self.me.energy >= FORTRESS_I[ 0] and self.me.gold >= FORTRESS_I[1] def CanUpgrade(self, cell): cellType = cell.building.name cellLevel = cell.building.level if cellType == "home": if cellLevel == 1: return self.me.energy >= HOME_I[0] and self.me.gold >= HOME_I[1] elif cellLevel == 2: return self.me.energy >= HOME_II[ 0] and self.me.gold >= HOME_II[1] else: return False elif cellType == "energy_well": if cellLevel == 1: return self.me.energy >= ENERGY_I[ 0] and self.me.gold >= ENERGY_I[1] elif cellLevel == 2: return self.me.energy >= ENERGY_II[ 0] and self.me.gold >= ENERGY_II[1] else: return False elif cellType == "gold_mine": if cellLevel == 1: return self.me.energy >= GOLD_I[0] and self.me.gold >= GOLD_I[1] elif cellLevel == 2: return self.me.energy >= GOLD_II[ 0] and self.me.gold >= GOLD_II[1] else: return False elif cellType == "fortress": if cellLevel == 1: return self.me.energy >= FORTRESS_I[ 0] and self.me.gold >= FORTRESS_I[1] elif cellLevel == 2: return self.me.energy >= FORTRESS_II[ 0] and self.me.gold >= FORTRESS_II[1] else: return False def Build(self, cell, building): if building == BLD_ENERGY_WELL: self.me.energy -= ENERGY_I[0] self.me.gold -= ENERGY_I[1] elif building == BLD_GOLD_MINE: self.me.energy -= GOLD_I[0] self.me.gold -= GOLD_I[1] elif building == BLD_FORTRESS: self.me.energy -= FORTRESS_I[0] self.me.gold -= FORTRESS_I[1] self.cmdList.append(self.game.build(cell.position, building)) def FetchAdjacent(self, cell): return [ self.game.game_map[pos] for pos in cell.position.get_surrounding_cardinals() ] def Empty(self, cell): return cell.owner == 0 def Own(self, cell): return cell.owner == self.game.uid def Enemy(self, cell): return not (cell.owner == 0 or not cell.owner == self.game.uid) def FetchInfo(self): self.me = self.game.me self.mode = 0 self.tech = 0 self.data = {} self.data["adjacent"] = {} self.data["adjacent"]["all"] = set() self.data["adjacent"]["empty"] = set() self.data["adjacent"]["enemy"] = {} self.data["adjacent"]["enemy"]["all"] = set() self.data["adjacent"]["enemy"]["empty"] = set() self.data["adjacent"]["enemy"]["energy"] = [set(), set(), set()] self.data["adjacent"]["enemy"]["gold"] = [set(), set(), set()] self.data["adjacent"]["enemy"]["bases"] = [set(), set(), set()] self.data["adjacent"]["enemy"]["forts"] = [set(), set(), set()] self.data["own"] = {} self.data["own"]["all"] = set() self.data["own"]["empty"] = set() self.data["own"]["energy"] = [set(), set(), set()] self.data["own"]["gold"] = [set(), set(), set()] self.data["own"]["bases"] = [set(), set(), set()] self.data["own"]["forts"] = [set(), set(), set()] self.data["enemy"] = {} self.data["enemy"]["all"] = set() self.data["enemy"]["empty"] = set() self.data["enemy"]["energy"] = [set(), set(), set()] self.data["enemy"]["gold"] = [set(), set(), set()] self.data["enemy"]["bases"] = [set(), set(), set()] self.data["enemy"]["forts"] = [set(), set(), set()] self.cmdList = [] self.attackList = [] for x in range(30): for y in range(30): pos = Position(x, y) cell = self.GetCell(pos) if self.Own(cell): self.data["own"]["all"].add(pos) cellType = cell.building.name if cellType == "empty": self.data["own"]["empty"].add(pos) elif cellType == "home": self.data["own"]["bases"][cell.building.level - 1].add(pos) elif cellType == "energy_well": self.data["own"]["energy"][cell.building.level - 1].add(pos) elif cellType == "gold_mine": self.data["own"]["gold"][cell.building.level - 1].add(pos) elif cellType == "fortress": self.data["own"]["forts"][cell.building.level - 1].add(pos) for adj in self.FetchAdjacent(cell): if not self.Own(adj): self.data["adjacent"]["all"].add(adj.position) if self.Enemy(adj): self.data["adjacent"]["enemy"]["all"].add( adj.position) adjType = adj.building.name if adjType == "empty": self.data["own"]["empty"].add(adj.position) elif adjType == "home": self.data["own"]["bases"][ adj.building.level - 1].add( adj.position) elif adjType == "energy_well": self.data["own"]["energy"][ adj.building.level - 1].add( adj.position) elif adjType == "gold_mine": self.data["own"]["gold"][adj.building.level - 1].add( adj.position) elif adjType == "fortress": self.data["own"]["forts"][ adj.building.level - 1].add( adj.position) else: self.data["adjacent"]["empty"].add( adj.position) def Refresh(self): self.game.update_turn() return not self.game.me == None def Send(self): self.game.send_cmd(self.cmdList) def Defend(self): base = None if len(self.data["own"]["bases"][0]) > 0: base = self.GetCell(list(self.data["own"]["bases"][0])[0]) if len(self.data["own"]["bases"][1]) > 0: base = self.GetCell(list(self.data["own"]["bases"][1])[0]) if len(self.data["own"]["bases"][2]) > 0: base = self.GetCell(list(self.data["own"]["bases"][2])[0]) if base: self.tech = base.building.level if self.CanUpgrade(base): self.Upgrade(base) def Expand(self): if self.me.gold <= 500: self.BuildEnergy() targets = [self.GetCell(t) for t in self.data["adjacent"]["empty"]] targets.sort(key=lambda cell: (cell.natural_energy, -cell.attack_cost), reverse=True) for target in targets: if target.attack_cost <= self.me.energy: self.Attack(target) def Loot(self): self.BuildGold() targets = [self.GetCell(t) for t in self.data["adjacent"]["empty"]] targets.sort(key=lambda cell: (cell.natural_gold, -cell.attack_cost), reverse=True) for target in targets: if target.attack_cost <= self.me.energy: self.Attack(target) def BuildEnergy(self): energyTargets = [self.GetCell(e) for e in self.data["own"]["empty"]] energyTargets.sort(key=lambda cell: (cell.natural_energy), reverse=True) for energyTarget in energyTargets: if self.CanBuild(BLD_ENERGY_WELL): self.Build(energyTarget, BLD_ENERGY_WELL) def BuildGold(self): goldTargets = [self.GetCell(e) for e in self.data["own"]["empty"]] goldTargets.sort(key=lambda cell: (cell.natural_gold), reverse=True) for goldTarget in goldTargets: if self.CanBuild(BLD_GOLD_MINE): self.Build(goldTarget, BLD_GOLD_MINE) def UpgradeEnergy(self, level): energyTargets = [ self.GetCell(e) for e in self.data["own"]["energy"][level - 1] ] energyTargets.sort(key=lambda cell: (cell.natural_energy), reverse=True) for energyTarget in energyTargets: if self.CanUpgrade(energyTarget): self.Upgrade(energyTarget) def UpgradeGold(self, level): goldTargets = [ self.GetCell(e) for e in self.data["own"]["gold"][level - 1] ] goldTargets.sort(key=lambda cell: (cell.natural_energy), reverse=True) for goldTarget in goldTargets: if self.CanUpgrade(goldTarget): self.Upgrade(goldTarget) def Snap(self): if len(self.data["adjacent"]): pass def AllSpark(self): if random.choice((0, 1)) == 0: self.UpgradeEnergy(1) self.UpgradeEnergy(2) self.BuildEnergy() else: self.UpgradeGold(1) self.UpgradeGold(2) self.BuildGold() targets = [self.GetCell(t) for t in self.data["adjacent"]["all"]] targets.sort(key=lambda cell: (cell.attack_cost)) for target in targets: if target.attack_cost <= self.me.energy: self.Attack(target) def GameLoop(self): print("Energy Source: " + str(self.me.energy_source - self.me.tax_amount)) print("Energy Source: " + str(self.me.gold_source - self.me.tax_amount)) print("") self.Defend() if self.tech == 1: self.Expand() elif self.tech == 2: self.Loot() else: self.AllSpark()
def main(): game = Colorfight() play_game(game)
import time import random from colorfight.constants import BLD_GOLD_MINE, BLD_ENERGY_WELL, BLD_FORTRESS import operator import collections # def findHome(): # for cell in game.me.cells.values(): # if cell.building.name == "home": # print("Found Home") # return cell # Create a Colorfight Instance. This will be the object that you interact # with. global game game = Colorfight() # Connect to the server. This will connect to the public room. If you want to # join other rooms, you need to change the argument game.connect(room='smallpublic') # game.register should return True if succeed. # As no duplicate usernames are allowed, a random integer string is appended # to the example username. You don't need to do this, change the username # to your ID. # You need to set a password. For the example AI, the current time is used # as the password. You should change it to something that will not change # between runs so you can continue the game if disconnected. if game.register(username = '******', \ password = '******'): # This is the game loop
for cell2 in adjcells: dist = math.sqrt((home.position.x - cell2.position.x)**2 + (home.position.y - cell2.position.y)**2) potential.append([cell2, dist]) potential.sort(key=lambda x: x[1]) for attackcell in potential: if attackcell[0].attack_cost < me.energy: cmd_list.append( game.attack(attackcell[0].position, attackcell[0].attack_cost)) # print("We are attacking ({}, {}) with {} energy".format( # attackcell[0].position.x, attackcell[0].position.y, attackcell[0].attack_cost)) game.me.energy -= attackcell[0].attack_cost game = Colorfight() game.connect(room='Hi') if game.register(username='******' + str(random.randint(1, 100)), password=str(int(time.time())), join_key="testing123"): # This is the game loop numEn = 0 numGold = 0 numFort = 0 while True: cmd_list = []
async def create_gameroom(request): data = await request.json() try: if not request.app['config']['allow_create_room']: return web.json_response({ "success": False, "err_msg": "Creating room is disabled now" }) gameroom_id = data['gameroom_id'] if not url_safe(gameroom_id): return web.json_response({ "success": False, "err_msg": "You have illegal special characters in you gameroom id" }) if gameroom_id in request.app['game']: return web.json_response({ "success": False, "err_msg": "Same id exists" }) if len(request.app['game'] ) >= request.app['config']['max_gameroom_number']: return web.json_response({ "success": False, "err_msg": "Max room number reached" }) if 'config' in data: # If it's an official game, we require a password if data['config'] == 'official': if 'admin_password' not in data: return web.json_response({ "success": False, "err_msg": "You need to set a password for official game!" }) config = get_config(data['config']) else: config = get_config('default') # If this is an admin room admin_room = False if 'admin' in request.query and request.query['admin'].lower( ) == 'true': if 'master_admin_password' in data and data[ 'master_admin_password'] == request.app['admin_password']: admin_room = True else: return web.json_response({ "success": False, "err_msg": "To create an admin room, you need admin" }) request.app['game'][gameroom_id] = Colorfight(config=config, admin_room=admin_room) request.app['game'][ gameroom_id].save_replay = lambda replay, data: request.app[ 'firebase'].upload_replay(replay, data) request.app['game'][gameroom_id].replay_lock = asyncio.Lock( loop=asyncio.get_event_loop()) if 'admin_password' in data: request.app['game'][gameroom_id].admin_password = data[ 'admin_password'] if 'join_key' in data: request.app['game'][gameroom_id].join_key = data['join_key'] except Exception as e: return web.json_response({"success": False, "err_msg": str(e)}) return web.json_response({"success": True})
# cmd_list.append(game.build(cell.position, building)) # print("We build {} on ({}, {})".format(building, cell.position.x, cell.position.y)) # me.gold -= 100 # Send the command list to the server result = game.send_cmd(cmd_list) print(result) # Do this to release all the allocated resources. game.disconnect() if __name__ == '__main__': # Create a Colorfight Instance. This will be the object that you interact # with. game = Colorfight() # ================== Find a random non-full rank room ================== #room_list = game.get_gameroom_list() #rank_room = [room for room in room_list if room["rank"] and room["player_number"] < room["max_player"]] #room = random.choice(rank_room)["name"] # ====================================================================== room = 'public' # Delete this line if you have a room from above username = '******' password = '******' # ========================== Play game once =========================== play_game( game = game, \ room = room, \
from colorfight import Colorfight import time import random from colorfight.constants import BLD_GOLD_MINE, BLD_ENERGY_WELL, BLD_FORTRESS game = Colorfight() TOP = 1 LEFT = 2 BOTTOM = 3 RIGHT = 4 MIN_ENERGY = 500 side = 1 ring = 1 is_first_move = True continue_moving = True ring_finished = False is_stopping = False moved_this_side = 0 game.connect(room = 'public1') if game.register(username = '******', \ password = '******'): while True: cmd_list = [] my_attack_list = [] game.update_turn() if game.me == None: continue me = game.me
def update_cost(pos): cell = game.game_map[pos] return gold_val * [200, 400][cell.building.level] def update_eval(pos): return update_gain(pos) - update_cost(pos) def cal_tax(num): return num // 100 game = Colorfight() game.connect(room='gold') # game.register should return True if succeed. # As no duplicate usernames are allowed, a random integer string is appended # to the example username. You don't need to do this, change the username # to your ID. # You need to set a password. For the example AI, the current time is used # as the password. You should change it to something that will not change # between runs so you can continue the game if disconnected. cell_num = 0 building_num = 0 if game.register(username = '******' + str(random.randint(1, 100)), \
import random from colorfight.constants import BLD_GOLD_MINE, BLD_ENERGY_WELL, BLD_FORTRESS import operator import collections # def findHome(): # for cell in game.me.cells.values(): # if cell.building.name == "home": # print("Found Home") # return cell # Create a Colorfight Instance. This will be the object that you interact # with. global game game = Colorfight() # Connect to the server. This will connect to the public room. If you want to # join other rooms, you need to change the argument game.connect(room = 'groupb') # game.register should return True if succeed. # As no duplicate usernames are allowed, a random integer string is appended # to the example username. You don't need to do this, change the username # to your ID. # You need to set a password. For the example AI, the current time is used # as the password. You should change it to something that will not change # between runs so you can continue the game if disconnected. if game.register(username = '******', \ password = '******'): # This is the game loop
from colorfight import Colorfight import time import random import math from colorfight.constants import BLD_GOLD_MINE, BLD_ENERGY_WELL g = Colorfight() g.connect(room = 'nicoderek') #returns position of (top-left corner) of closest affinity area def affinityArea(): #alterable constants areaLen = 5 avgMin = 5 #desired minimum avg resource total of the cells in the area suffAvgAffinity = [] for X in range(0, g.width() - areaLen): for Y in range(0, g.height() - areaLen): resourceSum = 0 #find avg affinity for area for x in range(X, X + areaLen - 1): for y in range(Y, Y + areaLen - 1): resourceSum += x.gold + x.energy avgAffinity = resourceSum / (areaLen * areaLen) #if suffices minimum, add to sufficient list if avgAffinity > avgMin: suffAvgAffinity.append(Position(X, Y))
from colorfight import Colorfight import time import random from colorfight.constants import BLD_GOLD_MINE, BLD_ENERGY_WELL, BLD_FORTRESS from ai1 import ai1 from petry_ai import ai_petry gamers = [] for gamer_id in range(8): # register game = Colorfight() game.connect(room='public') game.register(username='******' + str(gamer_id), password='******') # param param = [1] for i in range(14): param.append(random.random() * 100 - 50) with open("param.txt", "a") as f: f.write(str(gamer_id)) f.write(' ') f.write(str(param)) f.write('\n') f.close() game.param = param gamers.append(game)
from colorfight import Colorfight import time import random from colorfight.constants import BLD_GOLD_MINE, BLD_ENERGY_WELL, BLD_FORTRESS from math import * def distance(p1, p2): return fabs(p2[0] - p1[0]) + fabs(p2[1] - p1[1]) # Create a Colorfight Instance. This will be the object that you interact # with. game = Colorfight() # Connect to the server. This will connect to the public room. If you want to # join other rooms, you need to change the argument game.connect(room='final') # game.register should return True if succeed. # As no duplicate usernames are allowed, a random integer string is appended # to the example username. You don't need to do this, change the username # to your ID. # You need to set a password. For the example AI, the current time is used # as the password. You should change it to something that will not change # between runs so you can continue the game if disconnected. if game.register(username = '******', \ password = str(int(time.time()))): # This is the game loop while True:
from colorfight import Colorfight from colorfight.constants import BLD_GOLD_MINE, BLD_ENERGY_WELL, BLD_FORTRESS from petry_ai import ai_petry game = Colorfight() game.connect(room='final') game.register(username='******', password='******') if not game.me: game.connect(room='final') game.register(username='******', password='******') # This is the game loop while True: game.update_turn() params = [ 1, -18.53341319688236, -0.8219475924979506, 2.2963243078751745, -2.12995591256858, -5.172858499022022, 16.968696086066522, -1.4114154156601832, -1.0770153231601682, -12.082107075648503, -2.1421765673156354, 18.795280713849472, 14.66617744870164, -0.39348099194405034, 4.819134378406117, 17.67588494142681, -31.470563592117514 ] cmd_list = ai_petry(game, params) result = game.send_cmd(cmd_list) print(result)
from colorfight import Colorfight import time import random from colorfight.constants import BLD_GOLD_MINE, BLD_ENERGY_WELL, BLD_FORTRESS # Create a Colorfight Instance. This will be the object that you interact # with. game = Colorfight() # Connect to the server. This will connect to the public room. If you want to # join other rooms, you need to change the argument game.connect(room='public1') # game.register should return True if succeed. # As no duplicate usernames are allowed, a random integer string is appended # to the example username. You don't need to do this, change the username # to your ID. # You need to set a password. For the example AI, the current time is used # as the password. You should change it to something that will not change # between runs so you can continue the game if disconnected def optimizeBld(cell): e = cell.natural_energy g = cell.natural_gold if game.turn < 100: if (g < 3 and e < 3): #return BLD_HOME #return BLD_FORTRESS print("f**k forts") if (g > (e + 4)):
from colorfight import Colorfight import time import random from colorfight.constants import BLD_GOLD_MINE, BLD_ENERGY_WELL, BLD_FORTRESS, BLD_HOME game = Colorfight() game.connect(room = 'public') mode = 'expansion' def formation(): if mode == 'defense' and cell.owner == me.uid and cell.building.is_empty and me.gold >= 100: building = random.choice([BLD_FORTRESS, BLD_FORTRESS, BLD_FORTRESS, BLD_FORTRESS, BLD_GOLD_MINE, BLD_ENERGY_WELL]) cmd_list.append(game.build(cell.position, building)) print("We build {} on ({}, {})".format(building, cell.position.x, cell.position.y)) me.gold -= 100 if game.register(username = '******', password = "******"): # This is the game loop while True: # The command list we will send to the server cmd_list = [] # The list of cells that we want to attack my_attack_list = [] # update_turn() is required to get the latest information from the # server. This will halt the program until it receives the updated # information. # After update_turn(), game object will be updated. game.update_turn()
from colorfight import Colorfight import time import random from colorfight.constants import BLD_GOLD_MINE, BLD_ENERGY_WELL, BLD_FORTRESS # Create a Colorfight Instance. This will be the object that you interact # with. game = Colorfight() # Connect to the server. This will connect to the public room. If you want to # join other rooms, you need to change the argument game.connect(room = 'public1') # game.register should return True if succeed. # As no duplicate usernames are allowed, a random integer string is appended # to the example username. You don't need to do this, change the username # to your ID. # You need to set a password. For the example AI, the current time is used # as the password. You should change it to something that will not change # between runs so you can continue the game if disconnected. if game.register(username = '******' + str(random.randint(1, 100)), \ password = str(int(time.time()))): # This is the game loop while True: # The command list we will send to the server cmd_list = [] # The list of cells that we want to attack my_attack_list = [] # update_turn() is required to get the latest information from the # server. This will halt the program until it receives the updated # information.
from colorfight import Colorfight import time import websockets import random from colorfight.constants import BLD_GOLD_MINE, BLD_ENERGY_WELL, BLD_FORTRESS, BLD_HOME # Create a Colorfight Instance. This will be the object that you interact # with. game = Colorfight() upgrade_home_flag = False max_out_pace = False def check_to_upgrade_home(home_cell): global game global upgrade_home_flag print("CHECKING IF CAN UPGRADE") print("home cell building level: %d" % home_cell.building.level) print("gold i will have: %d" % (game.me.gold + game.me.gold_source)) print("energy I will have: %d" % (game.me.energy + game.me.energy_source)) print("flag: %r" % upgrade_home_flag) if home_cell.building.level < 3 and game.me.gold + game.me.gold_source > home_cell.building.level * 1000 and game.me.energy + game.me.energy_source > home_cell.building.level * 1000: upgrade_home_flag = True def upgrade_home(home_cell, cmd_list): global game global upgrade_home_flag if game.me.gold > home_cell.building.level * 1000 and game.me.energy > home_cell.building.level * 1000: c = game.game_map[home_cell.position]
cellIndex = j highestScore = benefitScore newList.append(listIn[cellIndex]) del listIn[cellIndex] highestScore = 0 cellIndex = 0 return newList #-----------------END FUNCTION DEFINITIONS------------------# #------------------------BEGIN TURN-------------------------# # Create a Colorfight Instance game = Colorfight() # Connect to the server. This will connect to the public room. If you want to # join other rooms, you need to change the argument game.connect(room='Acropolis') #Musikverein #public #Acropolis # game.register should return True if succeed. # As no duplicate usernames are allowed, a random integer string is appended # to the example username. You don't need to do this, change the username # to your ID. # You need to set a password. For the example AI, the current time is used # as the password. You should change it to something that will not change
def test(self): test = self.lowestDist() test2 = self.lowestDistBuilding() print(test) print(test2) def findHome(game): for cell in game.me.cells.values(): c = game.game_map[cell.position] if c.is_home: return c if __name__ == "__main__": game = Colorfight() game.connect(room='Hi') print("STARTING PROGRAM") game.update_turn() if game.register(username='******', password="******", join_key="testing123"): game.update_turn() me = game.me home = findHome(game) myai = AI(game, home, me) while True: game.update_turn()
from colorfight import Colorfight import time import random from colorfight.constants import BLD_GOLD_MINE, BLD_ENERGY_WELL, BLD_FORTRESS # Create a Colorfight Instance. This will be the object that you interact # with. game = Colorfight() # Connect to the server. This will connect to the public room. If you want to # join other rooms, you need to change the argument game.connect(room='groupa') def sortFirst(y): return (y.attack_cost / (2 * y.energy) + (y.attack_cost / 6 * y.gold)) def sortSecond(x): return (x.attack_cost / (1 * x.energy) + (x.attack_cost / 2 * x.gold)) # game.register should return True if succeed. # As no duplicate usernames are allowed, a random integer string is appended # to the example username. You don't need to do this, change the username # to your ID. # You need to set a password. For the example AI, the current time is used # as the password. You should change it to something that will not change # between runs so you can continue the game if disconnected. if game.register(username = '******', \ password = "******" ):#, join_key="66466"):
from colorfight import Colorfight import time import random from colorfight.constants import BLD_GOLD_MINE, BLD_ENERGY_WELL, BLD_FORTRESS, BUILDING_COST game = Colorfight() # Connect to the server. Designate argument for the room game.connect(room='Musikverein') # game.register should return True if succeed. # input relevant username and pw if game.register(username="******", password="******"): # Determines the growth of the colony # Increments by one every X number of rounds for which no command is executed scaling_factor = 100 # Counts number of turns where no commands were executed no_growth = 0 # number of turns spent scaling growth_turn_ceiling = 200 # number of cells spent scaling growth_cell_ceiling = 300 # This is the game loop while True: # The command list we will send to the server cmd_list = []
from colorfight import Colorfight import time import random from colorfight.constants import BLD_GOLD_MINE, BLD_ENERGY_WELL, BLD_FORTRESS # Create a Colorfight Instance. This will be the object that you interact # with. game = Colorfight() # Connect to the server. This will connect to the public room. If you want to # join other rooms, you need to change the argument game.connect(room='public4') # game.register should return True if succeed. # As no duplicate usernames are allowed, a random integer string is appended # to the example username. You don't need to do this, change the username # to your ID. # You need to seuut a password. For the example AI, the current time is used # as the password. You should change it to something that will not change # between runs so you can continue the game if disconnected. if game.register(username = '******', \ password = str(int(time.time()))): # This is the game loop while True: # The command list we will send to the server cmd_list = [] # The list of cells that we want to attack, #this is here so that you dont attack the same ome multiple times (BAD!) my_attack_list = [] # update_turn() is required to get the latest information from the # server. This will halt the program until it receives the updated
from colorfight import Colorfight import time import random import math from colorfight.constants import BLD_GOLD_MINE, BLD_ENERGY_WELL, BLD_FORTRESS # Create a Colorfight Instance. This will be the object that you interact # with. game = Colorfight() # Connect to the server. This will connect to the public room. If you want to # join other rooms, you need to change the argument game.connect(room='Hi') # game.register should return True if succeed. # As no duplicate usernames are allowed, a random integer string is appended # to the example username. You don't need to do this, change the username # to your ID. # You need to set a password. For the example AI, the current time is used # as the password. You should change it to something that will not change # between runs so you can continue the game if disconnected. def lowestDist(): # find adjacent cells adjcells = [] for cell in game.me.cells.values(): for pos in cell.position.get_surrounding_cardinals(): c = game.game_map[pos] dist = math.sqrt((home.position.x - c.position.x)**2 + (home.position.y - c.position.y)**2)
def __init__(self): self.game = Colorfight() pass
class Inevitable: def __init__(self): self.game = Colorfight() pass def Start(self): self.defenseEnergy = 1 self.attackEnergy = 0 self.energyChance = 2 self.rechargeNow = False self.command = "" self.hold = False self.game.connect(room='final') if self.game.register(username='******', password="******"): self.starkThread = Thread(target=self.Stark) self.starkThread.start() while True: if self.Refresh(): self.FetchInfo() self.GameLoop() self.Send() def GetCell(self, pos): return self.game.game_map[pos] def GetUser(self, uid): return self.game.users[uid] def Attack(self, cell, energy=None): if energy == None: energy = cell.attack_cost + self.attackEnergy self.me.energy -= energy self.cmdList.append(self.game.attack(cell.position, energy)) self.attackList.append(cell.position) def Upgrade(self, cell): cellType = cell.building.name cellLevel = cell.building.level if cellType == "home": if cellLevel == 1: self.me.energy -= HOME_I[0] self.me.gold -= HOME_I[1] elif cellLevel == 2: self.me.energy -= HOME_II[0] self.me.gold -= HOME_II[1] elif cellType == "energy_well": if cellLevel == 1: self.me.energy -= ENERGY_I[0] self.me.gold -= ENERGY_I[1] elif cellLevel == 2: self.me.energy -= ENERGY_II[0] self.me.gold -= ENERGY_II[1] elif cellType == "gold_mine": if cellLevel == 1: self.me.energy -= GOLD_I[0] self.me.gold -= GOLD_I[1] elif cellLevel == 2: self.me.energy -= GOLD_II[0] self.me.gold -= GOLD_II[1] elif cellType == "fortress": if cellLevel == 1: self.me.energy -= FORTRESS_I[0] self.me.gold -= FORTRESS_I[1] elif cellLevel == 2: self.me.energy -= FORTRESS_II[0] self.me.gold -= FORTRESS_II[1] self.cmdList.append(self.game.upgrade(cell.position)) def CanSnap(self, base): owner = self.GetUser(base.owner) if self.me.energy >= (owner.energy_source + base.attack_cost): return owner.energy_source + base.attack_cost else: return -1 def CanBuild(self, building): if building == BLD_ENERGY_WELL: return self.me.energy >= ENERGY_I[0] and self.me.gold >= ENERGY_I[1] elif building == BLD_GOLD_MINE: return self.me.energy >= GOLD_I[0] and self.me.gold >= GOLD_I[1] elif building == BLD_FORTRESS: return self.me.energy >= FORTRESS_I[ 0] and self.me.gold >= FORTRESS_I[1] def CanUpgrade(self, cell): cellType = cell.building.name cellLevel = cell.building.level if cellType == "home": if cellLevel == 1: return self.me.energy >= HOME_I[0] and self.me.gold >= HOME_I[1] elif cellLevel == 2: return self.me.energy >= HOME_II[ 0] and self.me.gold >= HOME_II[1] else: return False elif cellType == "energy_well": if cellLevel == 1: return self.me.energy >= ENERGY_I[ 0] and self.me.gold >= ENERGY_I[1] elif cellLevel == 2: return self.me.energy >= ENERGY_II[ 0] and self.me.gold >= ENERGY_II[1] else: return False elif cellType == "gold_mine": if cellLevel == 1: return self.me.energy >= GOLD_I[0] and self.me.gold >= GOLD_I[1] elif cellLevel == 2: return self.me.energy >= GOLD_II[ 0] and self.me.gold >= GOLD_II[1] else: return False elif cellType == "fortress": if cellLevel == 1: return self.me.energy >= FORTRESS_I[ 0] and self.me.gold >= FORTRESS_I[1] elif cellLevel == 2: return self.me.energy >= FORTRESS_II[ 0] and self.me.gold >= FORTRESS_II[1] else: return False def Build(self, cell, building): if building == BLD_ENERGY_WELL: self.me.energy -= ENERGY_I[0] self.me.gold -= ENERGY_I[1] elif building == BLD_GOLD_MINE: self.me.energy -= GOLD_I[0] self.me.gold -= GOLD_I[1] elif building == BLD_FORTRESS: self.me.energy -= FORTRESS_I[0] self.me.gold -= FORTRESS_I[1] self.cmdList.append(self.game.build(cell.position, building)) def FetchAdjacent(self, cell): return [ self.game.game_map[pos] for pos in cell.position.get_surrounding_cardinals() ] def Empty(self, cell): return cell.owner == 0 def Own(self, cell): return cell.owner == self.game.uid def Enemy(self, cell): return not (cell.owner == 0 or cell.owner == self.game.uid) def FetchInfo(self): self.me = self.game.me self.mode = 0 self.tech = 0 self.data = {} self.data["adjacent"] = {} self.data["adjacent"]["all"] = set() self.data["adjacent"]["empty"] = set() self.data["adjacent"]["enemy"] = {} self.data["adjacent"]["enemy"]["all"] = set() self.data["adjacent"]["enemy"]["empty"] = set() self.data["adjacent"]["enemy"]["energy"] = [set(), set(), set()] self.data["adjacent"]["enemy"]["gold"] = [set(), set(), set()] self.data["adjacent"]["enemy"]["bases"] = [set(), set(), set()] self.data["adjacent"]["enemy"]["forts"] = [set(), set(), set()] self.data["own"] = {} self.data["own"]["all"] = set() self.data["own"]["empty"] = set() self.data["own"]["energy"] = [set(), set(), set()] self.data["own"]["gold"] = [set(), set(), set()] self.data["own"]["bases"] = [set(), set(), set()] self.data["own"]["forts"] = [set(), set(), set()] self.data["edges"] = set() self.data["enemy"] = {} self.data["enemy"]["all"] = set() self.data["enemy"]["empty"] = set() self.data["enemy"]["energy"] = [set(), set(), set()] self.data["enemy"]["gold"] = [set(), set(), set()] self.data["enemy"]["bases"] = [set(), set(), set()] self.data["enemy"]["forts"] = [set(), set(), set()] self.cmdList = [] self.attackList = [] for x in range(30): for y in range(30): pos = Position(x, y) cell = self.GetCell(pos) if self.Own(cell): self.data["own"]["all"].add(pos) cellType = cell.building.name if cellType == "empty": self.data["own"]["empty"].add(pos) elif cellType == "home": self.data["own"]["bases"][cell.building.level - 1].add(pos) elif cellType == "energy_well": self.data["own"]["energy"][cell.building.level - 1].add(pos) elif cellType == "gold_mine": self.data["own"]["gold"][cell.building.level - 1].add(pos) elif cellType == "fortress": self.data["own"]["forts"][cell.building.level - 1].add(pos) for adj in self.FetchAdjacent(cell): if not self.Own(adj): self.data["adjacent"]["all"].add(adj.position) if self.Enemy(adj): self.data["edges"].add(pos) self.data["adjacent"]["enemy"]["all"].add( adj.position) adjType = adj.building.name if adjType == "empty": self.data["enemy"]["empty"].add( adj.position) elif adjType == "home": self.data["enemy"]["bases"][ adj.building.level - 1].add( adj.position) elif adjType == "energy_well": self.data["enemy"]["energy"][ adj.building.level - 1].add( adj.position) elif adjType == "gold_mine": self.data["enemy"]["gold"][ adj.building.level - 1].add( adj.position) elif adjType == "fortress": self.data["enemy"]["forts"][ adj.building.level - 1].add( adj.position) else: self.data["adjacent"]["empty"].add( adj.position) def Refresh(self): self.game.update_turn() return not self.game.me == None def Send(self): self.game.send_cmd(self.cmdList) def Defend(self): base = None if len(self.data["own"]["bases"][0]) > 0: base = self.GetCell(list(self.data["own"]["bases"][0])[0]) if len(self.data["own"]["bases"][1]) > 0: base = self.GetCell(list(self.data["own"]["bases"][1])[0]) if len(self.data["own"]["bases"][2]) > 0: base = self.GetCell(list(self.data["own"]["bases"][2])[0]) if base: self.tech = base.building.level if self.CanUpgrade(base): self.Upgrade(base) def Expand(self): if self.me.gold <= 500: self.BuildEnergy() targets = [self.GetCell(t) for t in self.data["adjacent"]["empty"]] targets.sort(key=lambda cell: (cell.natural_energy, -cell.attack_cost), reverse=True) for target in targets: if target.attack_cost <= self.me.energy: self.Attack(target) def Bread(self): self.BuildGold() targets = [self.GetCell(t) for t in self.data["adjacent"]["empty"]] targets.sort(key=lambda cell: (cell.natural_gold, -cell.attack_cost), reverse=True) for target in targets: if target.attack_cost <= self.me.energy: self.Attack(target) def BuildEnergy(self): energyTargets = [self.GetCell(e) for e in self.data["own"]["empty"]] energyTargets.sort(key=lambda cell: (cell.natural_energy), reverse=True) for energyTarget in energyTargets: if self.CanBuild(BLD_ENERGY_WELL): self.Build(energyTarget, BLD_ENERGY_WELL) def BuildGold(self): goldTargets = [self.GetCell(e) for e in self.data["own"]["empty"]] goldTargets.sort(key=lambda cell: (cell.natural_gold), reverse=True) for goldTarget in goldTargets: if self.CanBuild(BLD_GOLD_MINE): self.Build(goldTarget, BLD_GOLD_MINE) def UpgradeEnergy(self, level): energyTargets = [ self.GetCell(e) for e in self.data["own"]["energy"][level - 1] ] energyTargets.sort(key=lambda cell: (cell.natural_energy), reverse=True) for energyTarget in energyTargets: if self.CanUpgrade(energyTarget): self.Upgrade(energyTarget) def UpgradeGold(self, level): goldTargets = [ self.GetCell(e) for e in self.data["own"]["gold"][level - 1] ] goldTargets.sort(key=lambda cell: (cell.natural_energy), reverse=True) for goldTarget in goldTargets: if self.CanUpgrade(goldTarget): self.Upgrade(goldTarget) def Stark(self): data = "" while not data == "endgame": data = input() if data == "hold": self.hold = True print("Holding Game State.") print("") elif data == "attack": self.hold = False print("Attack Mode Activated.") print("") elif data == "defend": if len(self.data["edges"]) > 0: self.defenseEnergy = int( int(self.me.energy_source / 2) / len(self.data["edges"])) else: self.defenseEnergy = 1 print("Defense Mode Activated.") print("") elif data == "recharge": self.rechargeNow = True self.energyChance = 1000 print("Recharge Mode Activated.") print("") elif data == "normal": self.rechargeNow = False self.energyChance = 2 print("Recharge Mode Deactivated.") print("") else: data = data.split() if data[0] == "d": print("Set defense energy to: " + data[1]) self.defenseEnergy = int(data[1]) elif data[0] == "a": print("Set attack energy to: " + data[1]) self.attackEnergy = int(data[1]) elif data[0] == "r": print("Set attack energy to: " + data[1]) self.energyChance = int(data[1]) def Armor(self): for edge in self.data["edges"]: edge = self.GetCell(edge) if self.me.energy >= 1: self.Attack(edge, self.defenseEnergy) def Loot(self): for i in (2, 1, 0): if len(self.data["adjacent"]["enemy"]["gold"][i]) > 0: goldTargets = [ self.GetCell(b) for b in self.data["adjacent"]["enemy"]["gold"][i] ] goldTargets.sort(key=lambda cell: (cell.attack_cost)) for goldTarget in goldTargets: if goldTarget.attack_cost <= self.me.energy: self.Attack(goldTarget) def Recharge(self): for i in (2, 1, 0): if len(self.data["adjacent"]["enemy"]["energy"][i]) > 0: goldTargets = [ self.GetCell(b) for b in self.data["adjacent"]["enemy"]["energy"][i] ] goldTargets.sort(key=lambda cell: (cell.attack_cost)) for goldTarget in goldTargets: if goldTarget.attack_cost <= self.me.energy: self.Attack(goldTarget) def Dominate(self): targets = [self.GetCell(t) for t in self.data["adjacent"]["empty"]] targets.sort(key=lambda cell: (cell.attack_cost)) for target in targets: if target.attack_cost <= self.me.energy: self.Attack(target) targets = [self.GetCell(t) for t in self.data["adjacent"]["all"]] targets.sort(key=lambda cell: (cell.attack_cost)) for target in targets: if target.attack_cost <= self.me.energy: self.Attack(target) def Snap(self): for i in (2, 1, 0): if len(self.data["adjacent"]["enemy"]["bases"][i]) > 0: bases = [ self.GetCell(b) for b in self.data["adjacent"]["enemy"]["bases"][i] ] for base in bases: snapCost = self.CanSnap(base) if not snapCost == -1: self.Attack(base, snapCost) def AllSpark(self): if not self.hold: if random.choice(range(self.energyChance)) == 0: self.UpgradeGold(1) self.UpgradeGold(2) self.BuildGold() else: self.UpgradeEnergy(1) self.UpgradeEnergy(2) self.BuildEnergy() else: if self.rechargeNow: self.UpgradeEnergy(1) self.UpgradeEnergy(2) self.BuildEnergy() self.Snap() self.Armor() if not self.hold: order = random.choice((0, 1, 2)) if order == 0: self.Dominate() if random.choice((0, 1)) == 0: self.Recharge() self.Loot() else: self.Loot() self.Recharge() elif order == 1: self.Recharge() self.Dominate() self.Loot() elif order == 2: self.Loot() self.Dominate() self.Recharge() def GameLoop(self): #print( str( len( self.data[ "edges" ] ) ) ) #print( str( len( self.data[ "adjacent" ][ "empty" ] ) ) ) self.Defend() if self.tech == 1: self.Expand() elif self.tech == 2 and not self.rechargeNow: self.Bread() else: self.AllSpark()