def restart(self): self.color = 1 self.gamealive = True self.board = HexBoard(RADIUS, (SIZE, SIZE)) self.board.padding = PAD self.draw_board() pg.display.update() if len(sys.argv) == 2: self.filename = sys.argv[1] else: self.filename = 'map' + str(random.randrange(9999)) while self.gamealive: deltaTime = self.clock.tick(FPS) for event in pg.event.get(): if event.type == QUIT: pg.quit() sys.exit() elif event.type == MOUSEBUTTONDOWN: cpoint = self.board.centerPoint((3, 3)) for loc in self.board.alllocs: if vect.dist(self.board.centerPoint(loc), event.pos) < RADIUS: self.board.map[loc] = self.color elif event.type == KEYDOWN: if event.key == K_s: np.save('assets/maps/' + self.filename, self.board.map) print "Map Saved as", self.filename elif event.key == K_1: self.color = 0 elif event.key == K_2: self.color = 1 self.draw_board() pg.display.update()
class MapEditor: def __init__(self): pg.init() self.screen = pg.display.set_mode((WIDTH,HEIGHT)) pg.display.set_caption('BotSurvival!') self.screen.fill(colors.white) pg.display.update() self.clock = pg.time.Clock() self.restart() def restart(self): self.color = 1 self.gamealive = True self.board = HexBoard(RADIUS,(SIZE,SIZE)) self.board.padding = PAD self.draw_board() pg.display.update() if len(sys.argv) == 2: self.filename = sys.argv[1] else: self.filename = 'map'+str(random.randrange(9999)) while self.gamealive: deltaTime = self.clock.tick(FPS) for event in pg.event.get(): if event.type == QUIT: pg.quit() sys.exit() elif event.type == MOUSEBUTTONDOWN: cpoint = self.board.centerPoint((3,3)) for loc in self.board.alllocs: if vect.dist(self.board.centerPoint(loc),event.pos) < RADIUS: self.board.map[loc] = self.color elif event.type == KEYDOWN: if event.key == K_s: np.save('assets/maps/'+self.filename,self.board.map) print "Map Saved as",self.filename elif event.key == K_1: self.color = 0 elif event.key == K_2: self.color = 1 self.draw_board() pg.display.update() def draw_board(self): color = colors.gray5 for loc in self.board.alllocs: if self.board.loc_type(loc) == 'walk': color = colors.gray6 elif self.board.loc_type(loc) == 'obstacle': color = colors.black cpoint = self.board.centerPoint(loc) hexa = drawing.hexagon(cpoint,RADIUS) pg.draw.polygon(self.screen,color,hexa) pg.draw.lines(self.screen,colors.black,True,hexa,1)
def swapp(self): curBoard = copy(self.startState) self.startState = HexBoard(self.height, self.width) self.move = MCTS(self)[0] i, j = self.move if curBoard.board[i][j] != 0: self.swap = True self.startState = curBoard
class HexKI(): def __init__(self, m, n, mode, strat, board): self.height = m self.width = n self.mode = mode self.strategy = strat self.startState = board self.swap = False self.move = None def calculateMove(self): if self.strategy == 'MCTS': if self.startState.zug == 1: self.swapp() print(self.move) return self.swap else: self.move = MCTS(self)[0] print(self.move) return True elif self.strategy == 'random': self.move = random.choice(getLegalMoves(self.startState)) return True elif self.strategy == 'unsymmetric': self.legalmoves = getLegalMoves(self.startState) if self.startState.zug >= 1: self.unsymmetricMove() if self.move != None: i, j = self.move if self.startState.board[i][j] != 0: self.move = random.choice(self.legalmoves) return True else: self.move = random.choice(self.legalmoves) return False else: self.move = random.choice(self.legalmoves) return True self.move = random.choice(self.legalmoves) return False def swapp(self): curBoard = copy(self.startState) self.startState = HexBoard(self.height, self.width) self.move = MCTS(self)[0] i, j = self.move if curBoard.board[i][j] != 0: self.swap = True self.startState = curBoard def nextMove(self): return self.move def receiveMove(self, move): self.startState.receiveMove(move) def unsymmetricMove(self): self.move = unsymmetric(self.height, self.width, self.startState.lastmove)
def __init__(self, colour): """ This method is called once at the beginning of the game to initialise your player. You should use this opportunity to set up your own internal representation of the game state, and any other information about the game state you would like to maintain for the duration of the game. The parameter colour will be a string representing the player your program will play as (Red, Green or Blue). The value will be one of the strings "red", "green", or "blue" correspondingly. """ self.board = HexBoard() self.player = colour
class randomJim: def __init__(self, colour): """ This method is called once at the beginning of the game to initialise your player. You should use this opportunity to set up your own internal representation of the game state, and any other information about the game state you would like to maintain for the duration of the game. The parameter colour will be a string representing the player your program will play as (Red, Green or Blue). The value will be one of the strings "red", "green", or "blue" correspondingly. """ self.board = HexBoard() self.player = colour def action(self): """ This method is called at the beginning of each of your turns to request a choice of action from your program. Based on the current state of the game, your player should select and return an allowed action to play on this turn. If there are no allowed actions, your player must return a pass instead. The action (or pass) must be represented based on the above instructions for representing actions. """ choices = list(self.board.adj_state_actions(self.player)) action = random.choice(choices)[1] return action def update(self, colour, action): """ This method is called at the end of every turn (including your player’s turns) to inform your player about the most recent action. You should use this opportunity to maintain your internal representation of the game state and any other information about the game you are storing. The parameter colour will be a string representing the player whose turn it is (Red, Green or Blue). The value will be one of the strings "red", "green", or "blue" correspondingly. The parameter action is a representation of the most recent action (or pass) conforming to the above in- structions for representing actions. You may assume that action will always correspond to an allowed action (or pass) for the player colour (your method does not need to validate the action/pass against the game rules). """ self.board.update(colour, action)
def copy(Board): m = len(Board.board[0]) a, b = Board.zug, Board.no_filled newBoard = HexBoard(m, m) newBoard.board = deepcopy(Board.board) newBoard.starter = Board.starter newBoard.win = Board.win newBoard.zug = a newBoard.lastmove = Board.lastmove newBoard.no_filled = b newBoard.swap = Board.swap return newBoard
def restart(self): self.color = 1 self.gamealive = True self.board = HexBoard(RADIUS,(SIZE,SIZE)) self.board.padding = PAD self.draw_board() pg.display.update() if len(sys.argv) == 2: self.filename = sys.argv[1] else: self.filename = 'map'+str(random.randrange(9999)) while self.gamealive: deltaTime = self.clock.tick(FPS) for event in pg.event.get(): if event.type == QUIT: pg.quit() sys.exit() elif event.type == MOUSEBUTTONDOWN: cpoint = self.board.centerPoint((3,3)) for loc in self.board.alllocs: if vect.dist(self.board.centerPoint(loc),event.pos) < RADIUS: self.board.map[loc] = self.color elif event.type == KEYDOWN: if event.key == K_s: np.save('assets/maps/'+self.filename,self.board.map) print "Map Saved as",self.filename elif event.key == K_1: self.color = 0 elif event.key == K_2: self.color = 1 self.draw_board() pg.display.update()
def run_match(self, blue, red): b = self.players[blue](self.size, HexBoard.BLUE, self.seed) r = self.players[red](self.size, HexBoard.RED, self.seed) if self.names[blue] is None: self.names[blue] = b.name() if self.names[red] is None: self.names[red] = r.name() board = HexBoard(self.size) blue_turn = True while not board.is_game_over(): if blue_turn: b.make_move(board) else: r.make_move(board) blue_turn = not blue_turn return not blue_turn, blue, red
def restart(self): self.turn = 1 self.gamealive = True self.board = HexBoard(settings.radius,(settings.map_size,settings.map_size)) self.board.padding = settings.padding self.view = View(self.board.size,settings.view_height,settings.view_width) self.draw_board() self.bots = [] size = self.board.size[0]-1 for i in range(150): x = int(floor(max(0,min(size,gauss(size/2,10))))) y = int(floor(max(0,min(size,gauss(size/2,10))))) self.bots.append((x,y)) pg.display.update() while self.gamealive: deltaTime = self.clock.tick(settings.fps) pg.display.set_caption('BotSurvival! '+str(round(1.0/deltaTime*1000))) self.dirty_rects = [] for event in pg.event.get(): if event.type == QUIT: close() elif event.type == MOUSEBUTTONDOWN: self.run_turn() self.turn += 1 elif event.type == KEYDOWN: if event.key == K_r: self.restart() self.gamealive = False elif event.key == K_ESCAPE: close() elif event.key == K_RIGHT: self.view.move((0,2)) elif event.key == K_LEFT: self.view.move((0,-2)) elif event.key == K_DOWN: self.view.move((2,0)) elif event.key == K_UP: self.view.move((-2,0)) self.draw_board() self.draw_bots() pg.display.update() self.restart() close()
def main(): # find a board configuration from input board_config = parseboardinput() # initialise board board = HexBoard(board_config) # used for debug purposes if PRINT_HEURISTICS: board.print_board_heuristics() # run search algorithm dest_node = A_star_search(board) if dest_node == None: print("# can't do it sorry :(") return # prints every board state along the path (run with "| more -16" to animate with spacebar) if PRINT_BOARD_PATH: board.print_path(dest_node) # prints the required output dest_node.print_instructions() # Billy insisting on doing a weird output for some reason print(f"# yeehaw {dest_node.cost} moves")
def __init__(self, n): self.root = tk.Tk() self.root.title('Hex') self.n = n self.data = pd.DataFrame() self.current_player = 1 self.current_player_color = 'blue' self.current_move = 1 self.player_1_selection = tk.StringVar() self.player_1_selection.set('Human Player') self.player_2_selection = tk.StringVar() self.player_2_selection.set('Human Player') self.board = HexBoard(n) self.window = HexGui(n, self) self.root.mainloop()
class MapEditor: def __init__(self): pg.init() self.screen = pg.display.set_mode((WIDTH, HEIGHT)) pg.display.set_caption('BotSurvival!') self.screen.fill(colors.white) pg.display.update() self.clock = pg.time.Clock() self.restart() def restart(self): self.color = 1 self.gamealive = True self.board = HexBoard(RADIUS, (SIZE, SIZE)) self.board.padding = PAD self.draw_board() pg.display.update() if len(sys.argv) == 2: self.filename = sys.argv[1] else: self.filename = 'map' + str(random.randrange(9999)) while self.gamealive: deltaTime = self.clock.tick(FPS) for event in pg.event.get(): if event.type == QUIT: pg.quit() sys.exit() elif event.type == MOUSEBUTTONDOWN: cpoint = self.board.centerPoint((3, 3)) for loc in self.board.alllocs: if vect.dist(self.board.centerPoint(loc), event.pos) < RADIUS: self.board.map[loc] = self.color elif event.type == KEYDOWN: if event.key == K_s: np.save('assets/maps/' + self.filename, self.board.map) print "Map Saved as", self.filename elif event.key == K_1: self.color = 0 elif event.key == K_2: self.color = 1 self.draw_board() pg.display.update() def draw_board(self): color = colors.gray5 for loc in self.board.alllocs: if self.board.loc_type(loc) == 'walk': color = colors.gray6 elif self.board.loc_type(loc) == 'obstacle': color = colors.black cpoint = self.board.centerPoint(loc) hexa = drawing.hexagon(cpoint, RADIUS) pg.draw.polygon(self.screen, color, hexa) pg.draw.lines(self.screen, colors.black, True, hexa, 1)
class Game: def __init__(self): pg.init() self.screen = pg.display.set_mode((settings.scr_width,settings.scr_height),settings.fullscreen) pg.display.set_caption('BotSurvival!') self.screen.fill(settings.back_color) pg.display.update() self.clock = pg.time.Clock() self.restart() def restart(self): self.turn = 1 self.gamealive = True self.board = HexBoard(settings.radius,(settings.map_size,settings.map_size)) self.board.padding = settings.padding self.view = View(self.board.size,settings.view_height,settings.view_width) self.draw_board() self.bots = [] size = self.board.size[0]-1 for i in range(150): x = int(floor(max(0,min(size,gauss(size/2,10))))) y = int(floor(max(0,min(size,gauss(size/2,10))))) self.bots.append((x,y)) pg.display.update() while self.gamealive: deltaTime = self.clock.tick(settings.fps) pg.display.set_caption('BotSurvival! '+str(round(1.0/deltaTime*1000))) self.dirty_rects = [] for event in pg.event.get(): if event.type == QUIT: close() elif event.type == MOUSEBUTTONDOWN: self.run_turn() self.turn += 1 elif event.type == KEYDOWN: if event.key == K_r: self.restart() self.gamealive = False elif event.key == K_ESCAPE: close() elif event.key == K_RIGHT: self.view.move((0,2)) elif event.key == K_LEFT: self.view.move((0,-2)) elif event.key == K_DOWN: self.view.move((2,0)) elif event.key == K_UP: self.view.move((-2,0)) self.draw_board() self.draw_bots() pg.display.update() self.restart() close() def run_turn(self): print self.turn nl = [] self.erase_bots() for loc in self.bots: try: nl.append(choice(self.board.locs_around(loc,['water','mountain']))) except IndexError as err: print err self.bots = nl self.draw_bots() if self.turn >= settings.max_turns: self.gamealive = False def draw_board(self): color = colors.gray5 size = self.view.getSize() loc_list = ((x,y) for x in xrange(size[0]) for y in xrange(size[1])) for vloc in loc_list: #print self.board.map[loc] bloc = self.view.getBoardLoc(vloc) color = self.get_color(bloc) self.draw_tile(vloc,color) def draw_tile(self,loc,color,radius=settings.radius,contorno=True): cpoint = self.board.centerPoint(loc) hexa = drawing.hexagon(cpoint,radius) pg.draw.polygon(self.screen,color,hexa) if contorno: pg.draw.lines(self.screen,colors.black,True,hexa,1) def draw_bots(self): for loc in self.bots: vloc = self.view.getViewLoc(loc) if vect.isInsideRect(vloc,self.view.getSize()): self.draw_tile(vloc,colors.cyan5,settings.radius*0.6,False) def erase_bots(self): for loc in self.bots: vloc = self.view.getViewLoc(loc) if vect.isInsideRect(vloc,self.view.getSize()): color = self.get_color(loc) self.draw_tile(vloc,color) def get_color(self,loc): loctype = self.board.loc_type(loc) if loctype== 'walk': if loc[1] % 2 == 0: return colors.green7 else: return settings.walk_color elif loctype == 'obstacle': return settings.obst_color elif loctype == 'water': return colors.blue8 elif loctype == 'hills': return colors.brown8 elif loctype == 'plains': return colors.green4 elif loctype == 'mountain': return colors.brown4 else: raise ValueError('not color for that loc: '+str(loc)+loctype)
from hexgame import HexGame from hexplayer import HexPlayerHuman, HexPlayerDijkstra from hexboard import HexBoard from hexcolour import HexColour if __name__ == '__main__': # test functionality board = HexBoard(3) board.set_colour([(0, 1), (1, 1), (2, 1)], HexColour.RED) board.dijkstra(HexColour.RED, True) board.dijkstra(HexColour.BLUE, True) board = HexBoard(5) board.set_colour([(0, 3), (2, 2), (4, 1)], HexColour.RED) board.dijkstra(HexColour.RED, True) # play a game game = HexGame(5, HexPlayerDijkstra(4), HexPlayerHuman()) game.play()
nargs='?', default="player") parser.add_argument("SEED", type=int, nargs='?', default=None) args = parser.parse_args() try: c_blue = importlib.import_module("players." + args.PLAYER_BLUE).export c_red = importlib.import_module("players." + args.PLAYER_RED).export p_blue = c_blue(args.BOARD_SIZE, HexBoard.BLUE, args.SEED) p_red = c_red(args.BOARD_SIZE, HexBoard.RED, args.SEED) except ModuleNotFoundError: print("Invalid player name") exit(-1) print(p_blue.name() + " VS " + p_red.name()) board = HexBoard(args.BOARD_SIZE) is_blue_turn = True while not board.is_game_over(): if is_blue_turn: assert (board.current_player() == HexBoard.BLUE) print("BLUE turn:") board.print() p_blue.make_move(board) else: assert (board.current_player() == HexBoard.RED) print("RED turn:") board.print() p_red.make_move(board) is_blue_turn = not is_blue_turn board.print()
class Dizzy: def __init__(self, colour): """ This method is called once at the beginning of the game to initialise your player. You should use this opportunity to set up your own internal representation of the game state, and any other information about the game state you would like to maintain for the duration of the game. The parameter colour will be a string representing the player your program will play as (Red, Green or Blue). The value will be one of the strings "red", "green", or "blue" correspondingly. """ self.board = HexBoard() self.player = colour def action(self): """ This method is called at the beginning of each of your turns to request a choice of action from your program. Based on the current state of the game, your player should select and return an allowed action to play on this turn. If there are no allowed actions, your player must return a pass instead. The action (or pass) must be represented based on the above instructions for representing actions. """ if not set.union( *map(itemgetter(1), self.board.state.iter_opponents_pieces(self.player))): # Dizzy is the only player left on the board # don't waste any time finding a good move, just f****n go for state, action in self.board.adj_state_exit_actions( self.player): return action for state, action in self.board.adj_state_actions(self.player): if state.players_stats[self.player][ TOTAL_DIST] < self.board.state.players_stats[ self.player][TOTAL_DIST]: return action action = miniMax(self.board, self.player) return action def update(self, colour, action): """ This method is called at the end of every turn (including your player’s turns) to inform your player about the most recent action. You should use this opportunity to maintain your internal representation of the game state and any other information about the game you are storing. The parameter colour will be a string representing the player whose turn it is (Red, Green or Blue). The value will be one of the strings "red", "green", or "blue" correspondingly. The parameter action is a representation of the most recent action (or pass) conforming to the above in- structions for representing actions. You may assume that action will always correspond to an allowed action (or pass) for the player colour (your method does not need to validate the action/pass against the game rules). """ self.board.update(colour, action)
class HexGame: def __init__(self, size, player1, player2): self.board = HexBoard(size) self.player1 = player1 self.player2 = player2 self.win = "" self.lose = "" def step(self, renders=('board', 'win')): if 'board' in renders: self.board.render(1000) if self.player1 and self.board.turn() == HexColour.RED: move = self.player1.get_move(self.board, HexColour.RED, renders) if self.player2 and self.board.turn() == HexColour.BLUE: move = self.player2.get_move(self.board, HexColour.BLUE, renders) self.board.do_move(move) def play(self, renders=('board', 'win')): while not self.board.is_game_over(): self.step(renders) if 'board' in renders: self.board.render(1000) if self.board.check_win(HexColour.RED): self.win = [self.player1, 1] self.lose = [self.player2, 2] if 'win' in renders: print('Red Wins!') return HexColour.RED if self.board.check_win(HexColour.BLUE): self.win = [self.player2, 2] self.lose = [self.player1, 1] if 'win' in renders: print('Blue Wins!') return HexColour.BLUE
class Game: def __init__(self, n): self.root = tk.Tk() self.root.title('Hex') self.n = n self.data = pd.DataFrame() self.current_player = 1 self.current_player_color = 'blue' self.current_move = 1 self.player_1_selection = tk.StringVar() self.player_1_selection.set('Human Player') self.player_2_selection = tk.StringVar() self.player_2_selection.set('Human Player') self.board = HexBoard(n) self.window = HexGui(n, self) self.root.mainloop() # Handles the case when Player 1 is changes def player_1_changed(self, event): print( "Player 1:", self.player_1_selection.get()) # prints value based on choice var mode = self.player_1_selection.get() if mode == "Human Player": self.ki_1 = None elif mode == "Monte Carlo AI": self.ki_1 = MonteCarloAI(self.n, self.board.board, 1, self.current_move) elif mode == "Game Tree AI": self.ki_1 = GameTreeAI(self.n, self.board.board, 1, self.current_move) elif mode == "Neural Net AI": #pass self.ki_1 = AnnAI(self.n, self.board.board, 1, self.current_move) if self.current_player == 1 and mode != "Human Player": move = self.ki_1.calculate_next_move() self.make_move(move) # Handles the case when player 2 is changed def player_2_changed(self, event): print( "Player 2:", self.player_2_selection.get()) # prints value based on choice var mode = self.player_2_selection.get() if mode == "Human Player": self.ki_2 = None elif mode == "Monte Carlo AI": self.ki_2 = MonteCarloAI(self.n, self.board.board, 2, self.current_move) elif mode == "Game Tree AI": self.ki_2 = GameTreeAI(self.n, self.board.board, 2, self.current_move) elif mode == "Neural Net AI": #pass self.ki_2 = AnnAI(self.n, self.board.board, 1, self.current_move) if self.current_player == 2 and mode != "Human Player": move = self.ki_2.calculate_next_move() self.make_move(move) # Handles updating the game and board with a move def make_move(self, move): self.current_move += 1 self.window.update_move(move) # HexBoard.update_move checks if a winning paths exists and returns a bool game_finished = self.board.update_move(move) self.data = save_move(self.data, self.board.board, move, self.current_player) if game_finished: self.window.game_over() ######self.data.to_csv("training_data/data_X.csv") return else: self.update_next_player() # Updates AIs with the move if self.player_1_selection.get() != "Human Player": self.ki_1.receive_move(move) if self.player_2_selection.get() != "Human Player": self.ki_2.receive_move(move) # If next player is an AI, let them calculate the next Move if self.current_player == 1 and self.player_1_selection.get( ) != "Human Player": next_move = self.ki_1.calculate_next_move() self.make_move(next_move) if self.current_player == 2 and self.player_2_selection.get( ) != "Human Player": next_move = self.ki_2.calculate_next_move() self.make_move(next_move) # Changes the player after a move has been made def update_next_player(self): if self.current_player == 1: self.current_player = 2 self.current_player_color = 'red' else: self.current_player = 1 self.current_player_color = 'blue' self.board.set_current_player(self.current_player) # Destroys the root and starts new game def restart(self, n): self.root.destroy() Game(n)
def __init__(self, size, player1, player2): self.board = HexBoard(size) self.player1 = player1 self.player2 = player2 self.win = "" self.lose = ""
from hexboard import HexBoard parser = argparse.ArgumentParser(description="Hex interactive player") parser.add_argument("BOARD_SIZE", type=int) parser.add_argument("-r", help="play as red", action="store_true") parser.add_argument("PLAYER", type=str, nargs='?', default="player") parser.add_argument("SEED", type=int, nargs='?', default=0) args = parser.parse_args() opp_color = HexBoard.RED play_color = HexBoard.BLUE if args.r: opp_color = HexBoard.BLUE play_color = HexBoard.RED board = HexBoard(args.BOARD_SIZE) board.print() opponent_class = importlib.import_module("players." + args.PLAYER).export opponent = opponent_class(args.BOARD_SIZE, opp_color, args.SEED) print("Playing vs: " + opponent.name()) is_player_turn = not args.r while not board.is_game_over(): if is_player_turn: try: text_in = input("move?> ") x, y = text_in.split(',') x = int(x) y = ord(y) - ord('a') if x >= 0 and x < board.size and y >= 0 and y < board.size and board.is_empty(
from hexgame import HexGame from hexplayer import HexPlayerHuman, HexPlayerEnhanced from hexboard import HexBoard if __name__ == '__main__': # test functionality board = HexBoard(2) for child, _ in board.children(): print(child.board, hash(child)) game = HexGame(2, HexPlayerEnhanced(10, True), None) game.step(['tree']) game = HexGame(2, HexPlayerEnhanced(10, False), None) game.step(['tree']) # play a game game = HexGame(5, HexPlayerEnhanced(10, True), HexPlayerHuman()) game.play()