def __init__(self, port): self.host = 'localhost' self.webUi = WebUi() self.port_ui = port self.webUi.addEvent("cellClicked", self.wasClicked) self.webUi.addEvent("getBoardScores", self.getBoardScores) self.webUi.addEvent("connectServer", self.connectServer) self.agent_behavior_step = 0 self.new_agent_locations = [[0, 0], [0, 0]] self.new_agent_diff = [[0, 0], [0, 0]] self.remove_tile_locations = [] self.board = Board() self.playng_thread = None self.solving_engine = NewSolver() # connections self.team = "A" # "A" or "B" self.client_socket = None self.bsize = 1024 self.receive_thread = None self.input_thread = None self.was_recieved = False self.rcv_msg = ''
def __init__(self): self.host = 'localhost' self.agent_behavior_step = 0 self.new_agent_locations = [[0, 0], [0, 0]] self.remove_tile_locations = [] self.board = Board() self.playng_thread = None # connections self.team = "A" # "A" or "B" self.client_socket = None self.bsize = 1024 self.receive_thread = None self.input_thread = None self.was_recieved = False self.rcv_msg = ''
class Client(object): def __init__(self): self.host = 'localhost' self.agent_behavior_step = 0 self.new_agent_locations = [[0, 0], [0, 0]] self.remove_tile_locations = [] self.board = Board() self.playng_thread = None # connections self.team = "A" # "A" or "B" self.client_socket = None self.bsize = 1024 self.receive_thread = None self.input_thread = None self.was_recieved = False self.rcv_msg = '' def isAroundCell(self, cell1, cell2): return math.sqrt((cell1[0]-cell2[0])**2+(cell1[1]-cell2[1])**2) <= math.sqrt(2) def moveAgent(self): if self.team == "A": pass elif self.team == "B": pass def remomveTile(self): if self.team == "A": pass elif self.team == "B": pass def getBoardScores(self): return self.board.getBoardScores() # connections method def connectServer(self, port, team): self.team = team addr = (self.host, port) self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.client_socket.connect(addr) self.receive_thread = Thread(target=self.recieve) self.receive_thread.start() self.send(self.team) def recieve(self): while True: try: msg = self.client_socket.recv(self.bsize).decode("utf8") rcv_dict = json.loads(msg) order = rcv_dict['order'] if order == 'board_scores': self.board.initBoardSize(*rcv_dict['size']) self.board.setFirstAgentCell(rcv_dict['agents'][0]) self.board.initBoardScores(rcv_dict['scores']) self.board.printBoardScore() elif order == 'next_turn': self.board.setCurrentAgentLocations(rcv_dict['agents'][0], "A") self.board.setCurrentAgentLocations(rcv_dict['agents'][1], "B") self.board.team_a = copy.deepcopy(rcv_dict['tiles_a']) self.board.team_b = copy.deepcopy(rcv_dict['tiles_b']) if self.team == "A": self.board.printTiles_A() self.board.printTiles_B() except OSError: break def send(self, msg): # event is passed by binders. self.client_socket.send(bytes(msg, "utf8")) time.sleep(1e-3) if msg == "{quit}": self.client_socket.close()
class Client(object): def __init__(self, port): self.host = 'localhost' self.webUi = WebUi() self.port_ui = port self.webUi.addEvent("cellClicked", self.wasClicked) self.webUi.addEvent("getBoardScores", self.getBoardScores) self.webUi.addEvent("connectServer", self.connectServer) self.agent_behavior_step = 0 self.new_agent_locations = [[0, 0], [0, 0]] self.remove_tile_locations = [] self.board = Board() self.playng_thread = None # connections self.team = "A" # "A" or "B" self.client_socket = None self.bsize = 1024 self.receive_thread = None self.input_thread = None self.was_recieved = False self.rcv_msg = '' def isAroundCell(self, cell1, cell2): return math.sqrt((cell1[0] - cell2[0])**2 + (cell1[1] - cell2[1])**2) <= math.sqrt(2) def wasClicked(self, board_row, board_column, is_remove_mode): if self.team == "A": i = 0 tile_color = "a-tile" agent_color = "a{}-present".format(self.agent_behavior_step) my_tiles = copy.deepcopy(self.board.team_a) opponent_tiles = copy.deepcopy(self.board.team_b) elif self.team == "B": i = 1 tile_color = "b-tile" agent_color = "b{}-present".format(self.agent_behavior_step) my_tiles = copy.deepcopy(self.board.team_b) opponent_tiles = copy.deepcopy(self.board.team_a) agent = self.board.getCurrentAgentLocations()[i][ self.agent_behavior_step] if self.isAroundCell([board_row, board_column], agent): if self.agent_behavior_step >= 1: if is_remove_mode: if opponent_tiles[board_row][board_column] == 1 or my_tiles[ board_row][board_column] == 1: self.new_agent_locations[self.agent_behavior_step] = [ agent[0], agent[1] ] self.remove_tile_locations.append( [board_row, board_column]) self.webUi.editCellAttrs(board_row, board_column, agent_color, True) # self.delCellAttrs(board_row, board_column) else: print("選択したセルは除去できません") return else: if opponent_tiles[board_row][board_column] == 1: print("選択したセルに移動するためには除去を行う必要があります") return else: self.webUi.editCellAttrs(agent[0], agent[1], tile_color, True) self.webUi.editCellAttrs(board_row, board_column, agent_color, True) self.new_agent_locations[self.agent_behavior_step] = [ board_row, board_column ] self.agent_behavior_step = 0 print(self.new_agent_locations) json_data = json.dumps({ "order": "client_update", "from": self.team, "agent_location": self.new_agent_locations, "remove_tiles": self.remove_tile_locations }) self.send(json_data) self.new_agent_locations = [[0, 0], [0, 0]] self.remove_tile_locations = [] else: if is_remove_mode: if opponent_tiles[board_row][board_column] == 1 or my_tiles[ board_row][board_column] == 1: self.new_agent_locations[self.agent_behavior_step] = [ agent[0], agent[1] ] self.remove_tile_locations.append( [board_row, board_column]) # self.delCellAttrs(board_row, board_column) else: print("選択したセルは除去できません") return else: if opponent_tiles[board_row][board_column] == 1: print("選択したセルに移動するためには除去を行う必要があります") return else: self.webUi.editCellAttrs(agent[0], agent[1], tile_color, True) self.webUi.editCellAttrs(board_row, board_column, agent_color, True) self.new_agent_locations[self.agent_behavior_step] = [ board_row, board_column ] self.agent_behavior_step += 1 else: print("八近傍以外のセルには移動できません") def moveAgent(self): if self.team == "A": pass elif self.team == "B": pass def remomveTile(self): if self.team == "A": pass elif self.team == "B": pass def showWeb(self): self.webUi.showWindow(self.port_ui) def setUIBoard(self): self.webUi.showBoard(self.board.board_scores, self.board.first_agent_cells_a, self.board.first_agent_cells_b) def getBoardScores(self): return self.board.getBoardScores() # connections method def connectServer(self, port, team): self.team = team addr = (self.host, port) self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.client_socket.connect(addr) self.receive_thread = Thread(target=self.recieve) self.receive_thread.start() self.send(self.team) def recieve(self): while True: try: msg = self.client_socket.recv(self.bsize).decode("utf8") rcv_dict = json.loads(msg) order = rcv_dict['order'] if order == 'board_scores': self.board.initBoardSize(*rcv_dict['size']) self.board.setFirstAgentCell(rcv_dict['agents'][0]) self.board.initBoardScores(rcv_dict['scores']) self.setUIBoard() elif order == 'next_turn': self.board.setCurrentAgentLocations( rcv_dict['agents'][0], "A") self.board.setCurrentAgentLocations( rcv_dict['agents'][1], "B") self.board.team_a = copy.deepcopy(rcv_dict['tiles_a']) self.board.team_b = copy.deepcopy(rcv_dict['tiles_b']) if self.team == "A": self.board.printTiles_A() self.board.printTiles_B() print(self.board.getCurrentAgentLocations()) self.webUi.updateCellAttrs( self.board.team_a, self.board.team_b, self.board.getCurrentAgentLocations()) elif order == 'reject_turn': self.board.setCurrentAgentLocations( rcv_dict['agents'][0], "A") self.board.setCurrentAgentLocations( rcv_dict['agents'][1], "B") self.board.team_a = copy.deepcopy(rcv_dict['tiles_a']) self.board.team_b = copy.deepcopy(rcv_dict['tiles_b']) if self.team == "A": self.board.printTiles_A() self.board.printTiles_B() print(self.board.getCurrentAgentLocations()) self.webUi.updateCellAttrs( self.board.team_a, self.board.team_b, self.board.getCurrentAgentLocations()) except OSError: break def send(self, msg): # event is passed by binders. self.client_socket.send(bytes(msg, "utf8")) time.sleep(1e-3) if msg == "{quit}": self.client_socket.close()
class Client(object): def __init__(self, port): self.host = 'localhost' self.webUi = WebUi() self.port_ui = port self.webUi.addEvent("cellClicked", self.wasClicked) self.webUi.addEvent("getBoardScores", self.getBoardScores) self.webUi.addEvent("connectServer", self.connectServer) self.agent_behavior_step = 0 self.new_agent_locations = [[0, 0], [0, 0]] self.new_agent_diff = [[0, 0], [0, 0]] self.remove_tile_locations = [] self.board = Board() self.playng_thread = None self.solving_engine = NewSolver() # connections self.team = "A" # "A" or "B" self.client_socket = None self.bsize = 1024 self.receive_thread = None self.input_thread = None self.was_recieved = False self.rcv_msg = '' def isAroundCell(self, cell1, cell2): return math.sqrt((cell1[0]-cell2[0])**2+(cell1[1]-cell2[1])**2) <= math.sqrt(2) def wasClicked(self, board_row, board_column): if self.team == "A": i = 0 tile_color = "a-tile" agent_color = "a{}-present".format(self.agent_behavior_step) opponent_color = "b-tile" my_tiles = copy.deepcopy(self.board.team_a) opponent_tiles = copy.deepcopy(self.board.team_b) elif self.team == "B": i = 1 tile_color = "b-tile" agent_color = "b{}-present".format(self.agent_behavior_step) opponent_color = "a-tile" my_tiles = copy.deepcopy(self.board.team_b) opponent_tiles = copy.deepcopy(self.board.team_a) agent = self.board.getCurrentAgentLocations()[i][self.agent_behavior_step] if self.isAroundCell([board_row, board_column], agent): diff = [board_row-agent[0], board_column-agent[1]] if self.agent_behavior_step >= 1: if opponent_tiles[board_row][board_column] == 1: if opponent_tiles[board_row][board_column] == 1: self.new_agent_locations[self.agent_behavior_step] = [agent[0], agent[1]] self.remove_tile_locations.append([board_row, board_column]) self.webUi.editCellAttrs(board_row, board_column, opponent_color, False) else: self.webUi.editCellAttrs(agent[0], agent[1], tile_color, True) self.webUi.editCellAttrs(board_row, board_column, agent_color, True) self.new_agent_locations[self.agent_behavior_step] = [board_row, board_column] self.agent_behavior_step = 0 print("黒:", self.chooseTramp(diff)) print("") json_data = json.dumps({ "order": "client_update", "from": self.team, "agent_location": self.new_agent_locations, "remove_tiles": self.remove_tile_locations }) self.send(json_data) self.new_agent_locations = [[0, 0], [0, 0]] self.remove_tile_locations = [] else: if opponent_tiles[board_row][board_column] == 1: if opponent_tiles[board_row][board_column] == 1: self.new_agent_locations[self.agent_behavior_step] = [agent[0], agent[1]] self.remove_tile_locations.append([board_row, board_column]) self.webUi.editCellAttrs(board_row, board_column, opponent_color, False) else: self.webUi.editCellAttrs(agent[0], agent[1], tile_color, True) self.webUi.editCellAttrs(board_row, board_column, agent_color, True) self.new_agent_locations[self.agent_behavior_step] = [board_row, board_column] self.agent_behavior_step += 1 print("赤:", self.chooseTramp(diff)) else: print("八近傍以外のセルには移動できません") def chooseTramp(self, diff): if diff == [-1, 0]: return 1 elif diff == [-1, 1]: return 2 elif diff == [0, 1]: return 3 elif diff == [1, 1]: return 4 elif diff == [1, 0]: return 5 elif diff == [1, -1]: return 6 elif diff == [0, -1]: return 7 elif diff == [-1, -1]: return 8 def moveAgent(self): if self.team == "A": pass elif self.team == "B": pass def remomveTile(self): if self.team == "A": pass elif self.team == "B": pass def showWeb(self): self.webUi.showWindow(self.port_ui) def setUIBoard(self): self.webUi.showBoard(self.board.board_scores, self.board.first_agent_cells_a, self.board.first_agent_cells_b) def getBoardScores(self): return self.board.getBoardScores() # connections method def connectServer(self, port, team): self.team = team addr = (self.host, port) self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.client_socket.connect(addr) self.receive_thread = Thread(target=self.recieve) self.receive_thread.start() self.send(self.team) # これよりソルバー self.solving_engine.set_team(self.team) def recieve(self): while True: try: msg = self.client_socket.recv(self.bsize).decode("utf8") rcv_dict = json.loads(msg) order = rcv_dict['order'] if order == 'board_scores': self.board.initBoardSize(*rcv_dict['size']) self.board.setFirstAgentCell(rcv_dict['agents'][0]) self.board.initBoardScores(rcv_dict['scores']) self.setUIBoard() # これよりソルバー if self.team == 'A': agent_pos = self.board.current_agent_cells_a elif self.team == 'B': agent_pos = self.board.current_agent_cells_b self.solving_engine.update_board(self.board) self.solving_engine.calcScoreAverage() self.solving_engine.gen_state_list() agent0_next = self.solving_engine.search_around(*agent_pos[0]) self.wasClicked(*agent0_next) agent1_next = self.solving_engine.search_around(*agent_pos[1]) self.wasClicked(*agent1_next) time.sleep(1.0) elif order == 'next_turn': self.board.setCurrentAgentLocations(rcv_dict['agents'][0], "A") self.board.setCurrentAgentLocations(rcv_dict['agents'][1], "B") self.board.team_a = copy.deepcopy(rcv_dict['tiles_a']) self.board.team_b = copy.deepcopy(rcv_dict['tiles_b']) self.webUi.updateCellAttrs(self.board.team_a, self.board.team_b, self.board.getCurrentAgentLocations()) # ソルバー if self.team == 'A': agent_pos = self.board.current_agent_cells_a elif self.team == 'B': agent_pos = self.board.current_agent_cells_b self.solving_engine.update_board(self.board) self.solving_engine.gen_state_list() agent0_next = self.solving_engine.search_around(*agent_pos[0]) self.wasClicked(*agent0_next) agent1_next = self.solving_engine.search_around(*agent_pos[1]) self.wasClicked(*agent1_next) time.sleep(1.0) elif order == 'reject_turn': self.board.setCurrentAgentLocations(rcv_dict['agents'][0], "A") self.board.setCurrentAgentLocations(rcv_dict['agents'][1], "B") self.board.team_a = copy.deepcopy(rcv_dict['tiles_a']) self.board.team_b = copy.deepcopy(rcv_dict['tiles_b']) self.webUi.updateCellAttrs(self.board.team_a, self.board.team_b, self.board.getCurrentAgentLocations()) except OSError: break def send(self, msg): # event is passed by binders. self.client_socket.send(bytes(msg, "utf8")) time.sleep(1e-3) if msg == "{quit}": self.client_socket.close()
def __init__(self): self.board = Board() self.state = [] self.threshold = 0 self.team = 'A'
class NewSolver(object): def __init__(self): self.board = Board() self.state = [] self.threshold = 0 self.team = 'A' def calcScoreAverage(self): num_of_cells = 0 for row in self.board.getBoardScores(): for cell in row: if cell >= 0: self.threshold += cell num_of_cells += 1 self.threshold /= num_of_cells def set_team(self, team): self.team = team def update_board(self, input_board): self.board = input_board def gen_state_list(self): if self.team == 'A': my_board = copy.deepcopy(self.board.team_a) enemy_board = copy.deepcopy(self.board.team_b) elif self.team == 'B': my_board = copy.deepcopy(self.board.team_b) enemy_board = copy.deepcopy(self.board.team_a) self.state = [[0] * self.board.getBoardSize()[1] for i in range(self.board.getBoardSize()[0])] for x in range(self.board.getBoardSize()[0]): for y in range(self.board.getBoardSize()[1]): if my_board[x][y]: self.state[x][y] = 0 else: if self.board.getBoardScores()[x][y] >= self.threshold: if enemy_board[x][y]: self.state[x][y] = 3 else: self.state[x][y] = 2 elif self.board.getBoardScores()[x][y] >= 0: if enemy_board[x][y]: self.state[x][y] = -1 else: self.state[x][y] = 1 else: self.state[x][y] = -2 def search_around(self, row, column): destination = ((0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1)) que = [] board_size = self.board.getBoardSize() for a in destination: if (0 <= row + a[0] < board_size()[0]) and (0 <= column + a[1] < board_size()[1]): state_cache1 = copy.deepcopy(self.state) first_step = self.state[row + a[0]][column + a[1]] state_cache1[row + a[0]][column + a[1]] = 0 for b in destination: if (0 <= row + a[0] + b[0] < board_size()[0]) and ( 0 <= column + a[1] + b[1] < board_size()[1]): state_cache2 = copy.deepcopy(state_cache1) second_step = state_cache1[row + a[0] + b[0]][column + a[1] + b[1]] state_cache2[row + a[0] + b[0]][column + a[1] + b[1]] = 0 for c in destination: if (0 <= (row + a[0] + b[0] + c[0]) < board_size[0] ) and (0 <= (column + a[1] + b[1] + c[1]) < board_size[1]): third_step = state_cache2[row + a[0] + b[0] + c[0]][column + a[1] + b[1] + c[1]] que.append((first_step + second_step + third_step, self.board.getBoardScores()[row+a[0]][column+a[1]] \ + self.board.getBoardScores()[row+a[0]+b[0]][column+a[1]+b[1]] \ + self.board.getBoardScores()[row+a[0]+b[0]+c[0]][column+a[1]+b[1]+c[1]], (a, b, c) )) practice = [0, 0] #[forのiを代入, 評価値を代入] practices = [] for i, element in enumerate(que): if element[0] > practice[1]: practice = [i, element[0]] practices = [] practices.append(practice) elif element[0] == practice[1]: practice = [i, element[0]] practices.append(practice) best_practices = [(0, (0, 0))] for a in practices: if que[a[0]][1] > best_practices[0][0]: best_practices = [] best_practices.append([que[a[0]][1], que[a[0]][2][0]]) elif que[a[0]][1] == best_practices[0][0]: best_practices.append([que[a[0]][1], que[a[0]][2][0]]) num_run = random.randrange(len(best_practices)) return [ row + best_practices[num_run][1][0], column + best_practices[num_run][1][1] ]
def __init__(self): self.board = Board() self.state = [] #stateの値は-3が囲むことのできない平均値未満の領域、-2が平均値以上の領域、-1が平均値以下で点数の計算が行われていない領域、0以上は点数計算が終わり、lake_scoreに点数が代入し終わった領域。 self.lake_score = list()
class Solver(object): def __init__(self): self.board = Board() self.state = [] #stateの値は-3が囲むことのできない平均値未満の領域、-2が平均値以上の領域、-1が平均値以下で点数の計算が行われていない領域、0以上は点数計算が終わり、lake_scoreに点数が代入し終わった領域。 self.lake_score = list() def calcScoreAverage(self): return sum(map(sum, self.board.board_scores)) / ( (self.board.row + 1) * (self.board.column + 1)) def state_init(self): self.state = [[0] * self.board.getBoardSize()[1] for i in range(self.board.getBoardSize()[0])] print(len(self.state), len(self.state)) for x in range(self.board.getBoardSize()[0]): for y in range(self.board.getBoardSize()[1]): if self.board.getBoardScores()[x][y] < self.calcScoreAverage(): self.state[x][y] = -1 else: self.state[x][y] = -2 def find_lakes(self, x, y, num): self.state[x][y] = num self.lake_score_buffer = 0 self.utl = ((1, 0), (-1, 0), (0, 1), (0, -1)) for diff in self.utl: if (0 <= x + diff[0] < self.board.getBoardSize()[0] and 0 <= y + diff[1] < self.board.getBoardSize()[1] ) and self.state[x + diff[0]][y + diff[1]] == -1: self.lake_score_buffer += self.find_lakes( x + diff[0], y + diff[1], num) return abs(self.board.getBoardScores()[x][y]) + self.lake_score_buffer def set_state(self): self.state_init() for i in (0, self.board.getBoardSize()[0] - 1): for j in range(self.board.getBoardSize()[1]): if self.state[i][j] == -1: self.find_lakes(i, j, -3) for i in range(self.board.getBoardSize()[0]): for j in (0, self.board.getBoardSize()[1] - 1): if self.state[i][j] == -1: self.find_lakes(i, j, -3) count = 0 for i in range(self.board.getBoardSize()[0]): for j in range(self.board.getBoardSize()[1]): if self.state[i][j] == -1: self.lake_score.append(self.find_lakes(i, j, count)) count += 1 def set_board(self, in_board): self.board = in_board def get_state(self): return self.state def print_state(self): for row in self.state: for cell in row: print(format(cell, '3d'), end="") print("") def print_state_and_score(self, direction=0): if direction == 0: for row in self.state: for cell in row: if cell < 0: print(format(0, '3d'), end="") else: print(format(self.lake_score[cell], '3d'), end="") print("") print("") print("") elif direction == 1: for y in range(self.board.getBoardSize()[1]): for x in range(self.board.getBoardSize()[0]): if self.state[x][y] < 0: print(format(0, '3d'), end="") else: print(format(self.lake_score[self.state[x][y]], '3d'), end="") print("") print("") print("") elif direction == 2: for x in range(self.board.getBoardSize()[1])[::-1]: for y in range(self.board.getBoardSize()[0]): if self.state[x][y] < 0: print(format(0, '3d'), end="") else: print(format(self.lake_score[self.state[x][y]], '3d'), end="") print("") print("") print("") elif direction == 3: for y in range(self.board.getBoardSize()[1]): for x in range(self.board.getBoardSize()[0])[::-1]: if self.state[x][y] < 0: print(format(0, '3d'), end="") else: print(format(self.lake_score[self.state[x][y]], '3d'), end="") print("") print("") print("")
print(agents_a) board.genScores(symmetry) board.setFirstAgentCell(agents_a) board.printBoardScore() # board.printTiles_A() # board.printTiles_B() def printBoardScore_sq(level): for row_socres in board.board_scores: for score in row_socres: if score > level: print("██", end="") else: print(" ", end="") print("") board = Board() genScores(10, 10, 0, [[1, 1], [9 - 1, 9 - 1]]) level = sum(map(sum, board.getBoardScores())) / 100 print(level) print("") printBoardScore_sq(level) print("") print("") print("") print("") print("") printBoardScore_sq(level - 2)