def generate(self): """Main function to create map""" # First creates a grid of hexes without terrain for row in range(self.length): # Every other row has one fewer hex if row % 2 == 0: width = self.width else: width = self.width - 1 for col in range(width): new_hex = Hex(self.len, ".") # Keep track of hexes that have been made self.hexes.append(new_hex) self.len += 1 # Determining the necessary connections for each new hex # Connections other than Mid-Left, Top-Left, and Top-Right are # redundant. # Tuples are formatted (SIDE, NUM) where NUM is the number of # hexes to count backwards to be accurate # Check if it's on the top row if row == 0: # The top left corner initiates no connections if col == 0: tup = (("", 0),) # The others only have one else: tup = (("ML", 2),) else: # The leftmost hex in each column connects to one or two if col == 0: if row % 2 == 0: tup = (("TR", self.width),) else: tup = (("TL", self.width + 1), ("TR", self.width)) # The last hex in every other row doesn't have a TR # connection elif col == width - 1 and row % 2 == 0: tup = (("ML", 2), ("TL", self.width + 1)) else: tup = (("ML", 2), ("TL", self.width + 1), ("TR", self.width)) # Loop through each side needed and make connections for side, num in tup: try: new_hex.connect(side, self.hexes[self.len - num]) # In case I missed any edge cases, skipping over them except IndexError: pass # Generate each feature in order of precedence self.generate_forests() self.generate_rivers() roads = self.generate_roads() self.generate_buildings(roads)
def prog_file(self, fname, complete_func=None): """Program the specified file into the micro. Args: fname -- the filename to be programmed. complete_func -- completer function called to indicate percentage of completion. Raises: OSError, IOError -- if hex file open/read/write fails. OSError, IOError -- if read write from serial device failed. IspTimeoutError -- if no response for command from micro. IspChecksumError -- if checksum error occured during communication. IspProgError -- if flash programming failed. """ hex_file = file(fname) lines = hex_file.readlines() last = float(len(lines) - 1) if complete_func: complete_func(0) for i, line in enumerate(lines): line = line.strip() try: self._send_cmd(line) except IspProgError, e: h = Hex(line) raise IspProgError("programming %d bytes at 0x%04x failed, flash likely to be worn out" % (h.datalen(), h.addr())) if complete_func: complete_func(i / last)
def prog_file(self, fname, complete_func=None): """Program the specified file into the micro. Args: fname -- the filename to be programmed. complete_func -- completer function called to indicate percentage of completion. Raises: OSError, IOError -- if hex file open/read/write fails. OSError, IOError -- if read write from serial device failed. IspTimeoutError -- if no response for command from micro. IspChecksumError -- if checksum error occured during communication. IspProgError -- if flash programming failed. """ hex_file = file(fname) lines = hex_file.readlines() last = float(len(lines) - 1) if complete_func: complete_func(0) for i, line in enumerate(lines): line = line.strip() try: self._send_cmd(line) except IspProgError, e: h = Hex(line) raise IspProgError( "programming %d bytes at 0x%04x failed, flash likely to be worn out" % (h.datalen(), h.addr())) if complete_func: complete_func(i / last)
def __init__(self, frame_rate, hostname="localhost", port=4444): self.frame_rate = frame_rate self.last_update = datetime.datetime.now() self.next_update = self._get_next_update() self.server = (hostname, port) self.sock = None self.hex_model = Hex( ) # This hex model of pixels is unique to the Simulator self.connect()
def __init__(self, IP_address=None, verbose=True): self.series_id = -1 self.size = 6 self.game = Hex(6) self.model = ANET(0.9, (10, 15, 20), 'linear', 'sgd', self.size) self.model.load_model(200) BasicClientActorAbs.__init__(self, IP_address, verbose=verbose)
class GameObject: def __init__(self, image): self.image = pygame.image.load(image).convert_alpha() self.pos = Hex(0, 0) self.surface = pygame.display.get_surface() self.font = pygame.font.SysFont("droidsans", 15) self.font.set_bold(True) @property def height(self): return self.image.get_rect().height @property def width(self): return self.image.get_rect().width @property def size(self): return (self.width, self.height) def draw(self): x, y = self.pos.pixel_center() pygame.display.get_surface().blit(self.image, ( x + self.width/2, y )) def draw_text(self, text): label = self.font.render(text, 1, (255, 255, 255)) x, y = self.pos.pixel_center() center = x + label.get_rect().width/2 bottom = y + self.height - label.get_height() self.surface.blit(label, (center, bottom)) def tick(self, curr_ticks): self.draw() def _set_pos(self, x, y): self.pos = Hex(x, y) def can_move_to(self, pos): return not pos.is_edge() def can_move(self, d): return self.can_move_to(self.pos + d) def move(self, d): return self.move_to(self.pos + d) def move_to(self, pos): if self.can_move_to(pos): self.pos = pos
class SimulatorModel(object): def __init__(self, frame_rate, hostname="localhost", port=4444): self.frame_rate = frame_rate self.last_update = datetime.datetime.now() self.next_update = self._get_next_update() self.server = (hostname, port) self.sock = None self.hex_model = Hex( ) # This hex model of pixels is unique to the Simulator self.connect() def connect(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect(self.server) def _get_next_update(self): return self.last_update + datetime.timedelta(seconds=1.0 / self.frame_rate) def _needs_update(self): """Does the Simulator need updating?""" return datetime.datetime.now() > self.next_update def set(self, coord, color): """Set the coord's next_frame to color""" self.hex_model.set_cell(coord, color) def go(self): """If the frame is up, push all changed pixels to the simulator""" if self._needs_update(): self._send_pixels() self.hex_model.push_next_to_current_frame() self.last_update = datetime.datetime.now() self.next_update = self._get_next_update() def _send_pixels(self): """Send all of the changed pixels to the visualizer""" for pixel in self.hex_model.all_onscreen_pixels(): if pixel.has_changed(): # h, x, y = pixel.get_coord() # r, g, b = color_func.hsv_to_rgb(pixel.next_frame) # rgb_int = color_func.color_to_int(r, g, b) # ToDo: change this to rgb h, x, y = pixel.get_coord() hue, sat, val = pixel.next_frame hsv_int = color_func.color_to_int(hue, sat, val) msg = "{},{},{},{}".format(h, x + 5, y + 5, hsv_int) msg += "\n" # print(msg) self.sock.sendto(msg.encode(), self.server)
def _create_hex(self, start_x, start_y, size, row, column): hex_points = self._calculate_hex_points(start_x, start_y, size) hex_id = self.hex_grid.create_polygon(hex_points[0][0], hex_points[0][1], hex_points[1][0], hex_points[1][1], hex_points[2][0], hex_points[2][1], hex_points[3][0], hex_points[3][1], hex_points[4][0], hex_points[4][1], hex_points[5][0], hex_points[5][1], fill="white", outline="black", activedash=True, width=2) self._hex_coord_dict[hex_id] = hex_points adjacent_hexes = self._calculate_adjacency(row, column) ring_number = self.find_ring_number((row, column)) # structure = "None" # if hex_id == 31: # structure = "Refinery" self._hexes.append( Hex(self.hex_grid, self._master, self, hex_id, self._hex_menu_callback, row, column, adjacent_hexes, ring_number, self._parent.get_selected_squad)) self.hex_grid.tag_bind(hex_id, "<Button-3>", self._hexes[-1].hex_right_click) return hex_points[2]
def get_line(start, k): tiles = [] coord = Hex.hex_neighbor(start, k) if Board.is_on_board(coord): tiles.append(coord) Board.get_line_step(coord, k, tiles) return tiles
def has_neighbor(game, coord, current_rot): Board.update_blocked(game) coord_neighs = [] for k in range(6): if k != current_rot: coord_neighs.append(Hex.hex_neighbor(coord, k)) par_rot = (current_rot + 3) % 6 neigh_coord = Hex.hex_neighbor(coord, current_rot) for k in range(6): if k != par_rot: coord_neighs.append(Hex.hex_neighbor(neigh_coord, k)) # print(coord_neighs) for cn in coord_neighs: if cn in Board.blocked: return True return False
def set_board(self, board): self.board = board for row in range(0, len(board.grid)): for col in range(0, len(board.grid[0])): if col == 0: self.grid.append([]) self.grid[row].append(Hex((200, 175))) self.grid[row][col].set_hex(self.board.get_hex(row, col))
def _friendly_shoot(self): # wybor losowego statku spotted = random.choice(self.enemy_ships) self.ship_to_destroy = spotted; #wybor losowego pola assert isinstance(spotted,statek.Statek) pole = random.choice(spotted.get_pola()) assert isinstance(pole,statek.PoleStatku) wspPole = pole.get_key() hexPole = Hex(wspPole[0],wspPole[1]) sasiedzi = hexPole.get_neighbours() # spudluj w sasiada lub traf w pole if random.randint(0,100) > 50: self._shoot(random.choice(sasiedzi)) else: self._shoot(wspPole) self._mood = "angry"
def update_blocked(game): for pt in game.placed_tiles: (q, r, k) = pt[0] coord = (q, r) if Board.is_on_board(coord): Board.blocked.add(coord) neigh = Hex.hex_neighbor(coord, k) if Board.is_on_board(neigh): Board.blocked.add(neigh)
def is_free_pair_overlay(coord, k, overlay_blocked): if coord in overlay_blocked: return False if not Board.is_on_board(coord): return False neighbor = Hex.hex_neighbor(coord, k) # print("testing neighbor ", neighbor) if neighbor in overlay_blocked: return False if not Board.is_on_board(neighbor): return False return True
def draw_pair(coords, cols): # Draw under-layer (q, r, k) = coords (c1, c2) = cols Board.draw_empty_tile(q, r, k) # Draw coloured shapes primary_points = Shapes.plot_primary(Board.board_size, Board.size, q, r, c1) Board.draw_shape(c1, primary_points) (nq, nr) = Hex.hex_neighbor((q, r), k) secondary_points = Shapes.plot_primary(Board.board_size, Board.size, nq, nr, c2) Board.draw_shape(c2, secondary_points)
def set_up_channels(num_channels, max_show_time): """Get ready for two channels Each channel has its own ShowRunner, hex_model, and Pixels""" one_channel = (num_channels == 1) # Boolean channels = [ HexServer(hex_model=Hex(), channel=channel, one_channel=one_channel, max_show_time=max_show_time) for channel in range(num_channels) ] return channels
def handle_get_action(self, state): """ Here you will use the neural net that you trained using MCTS to select a move for your actor on the current board. Remember to use the correct player_number for YOUR actor! The default action is to select a random empty cell on the board. This should be modified. :param state: The current board in the form (1 or 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), where 1 or 2 indicates the number of the current player. If you are player 2 in the current series, for example, then you will see a 2 here throughout the entire series, whereas player 1 will see a 1. :return: Your actor's selected action as a tuple (row, column) """ # This is an example player who picks random moves. REMOVE THIS WHEN YOU ADD YOUR OWN CODE !! next_move = tuple( self.pick_random_free_cell(state, size=int(math.sqrt(len(state) - 1)))) state_manager = Hex(6) state_string = state_manager.convert_state(state) state_manager = Hex(6, state_string) move = state_manager.convert_to_move( self.player.get_action(state_string)) next_move = move ############################# # # # YOUR CODE HERE # # next_move = ??? ############################## return next_move
def is_free_pair(coord, k, free=False): # print("testing coord ", coord) if coord in Board.blocked: return False if not free and not Board.is_on_board(coord): return False neighbor = Hex.hex_neighbor(coord, k) # print("testing neighbor ", neighbor) if neighbor in Board.blocked: return False if not free and not Board.is_on_board(neighbor): return False return True
def construct_hexes(nodes, nodes_per_hexes): hexes = [] for node_indices in nodes_per_hexes: nodes_in_hex = [] for node_index in node_indices: nodes_in_hex.append(nodes[node_index]) # all of the Nodes making up the Hex are now assembling. make the Hex new_hex = Hex(nodes_in_hex) hexes.append(new_hex) # let nodes know which hexes they are vertices of for node in nodes_in_hex: node.add_hex(new_hex) return hexes
def is_legal(coords): (q, r, k) = coords tile = (q, r) if Board.is_on_board((q, r)): neighbor = Hex.hex_neighbor((q, r), k) # Check if clicked on 2-player board => distance 6 if Board.is_on_board(neighbor): # exit if square is non-empty if tile in Board.blocked: return False elif neighbor in Board.blocked: return False else: distances_tile = [Hex.hex_distance(tile, pt[0][0:2]) for pt in Board.placed_tiles] distances_other = [Hex.hex_distance(tile, Board.get_other_coord(pt)) for pt in Board.placed_tiles] neighbor_tile = [Hex.hex_distance(neighbor, pt[0][0:2]) for pt in Board.placed_tiles] neighbor_other = [Hex.hex_distance(neighbor, Board.get_other_coord(pt)) for pt in Board.placed_tiles] distances = distances_tile + distances_other + neighbor_tile + neighbor_other if min(distances) > 1: return False else: return True
def __init__(self, num_pixels, brightness): """ numpixels: the number of NeoPixels brightness: 0.0 to 1.0 pixel_order: The order of the pixel colors - RGB or GRB. Some NeoPixels have red and green reversed! For RGBW NeoPixels, simply change the ORDER to RGBW or GRBW. """ super(HexLights, self).__init__() self.num_pixels = num_pixels self.pixels = neopixel.NeoPixel(self.PIXEL_PIN, self.num_pixels, brightness=brightness, auto_write=False, pixel_order=neopixel.GRB) red = {"R": 255, "G": 0, "B": 0} blue = {"R": 0, "G": 0, "B": 255} self.color_palette = [red, blue, red, blue, red, blue] self.single_hexes = [] self.num_hexes = int(num_pixels / Hex.NUM_PIXELS) for hex_index in range(self.num_hexes): self.single_hexes.append(Hex(hex_index, self)) #Threading vars self.mutex = QtCore.QMutex() self.stop_received = False self.stopped = False #Pattern vars self.breathe_in = False self.patterns = { "Breathe": self.breathe, "Single cell snake": self.single_cell_snake, "Fedded sanke": self.single_cell_snake_with_fade, "Dubble Trubble": self.dubble_trubble, "Single Cell Rainbow": self.single_cell_rainbow, "Calibration": self.calibrate, "DNA": self.DNA } self.current_pattern = "Breathe" self.sleep_time = 0.1 self.is_dubble_trubble_forward = True self.dna_forwards = [] #Calibration self.is_calibrating = False self.calibration_index = 0
def count_available_pairs(): count = 0 overlay_blocked = set(Board.blocked) for k in range(0, 3): for r in range(-6, 7): for q in range(-6, 7): if Board.is_free_pair_overlay((q, r), k, overlay_blocked): Board.overlays.append((q, r, k)) overlay_blocked.add((q, r)) overlay_blocked.add(Hex.hex_neighbor((q, r), k)) count += 1 # Prevent drawing the overlays Board.overlays = [] # print(f'Available pairs: {count} ({Board.count_available()})') return count
def hex_round(self): x = int(round(self.x)) y = int(round(self.y)) z = int(round(self.z)) x_diff = abs(x - self.x) y_diff = abs(y - self.y) z_diff = abs(z - self.z) if x_diff > y_diff and x_diff > z_diff: x = -y - z elif y_diff > z_diff: y = -x - z else: z = -x - y return Hex(x, y)
def _create_hex(self, start_x, start_y, size): hex_points = self._calculate_hex_points(start_x, start_y, size) hex_id = self.hex_grid.create_polygon(hex_points[0][0], hex_points[0][1], hex_points[1][0], hex_points[1][1], hex_points[2][0], hex_points[2][1], hex_points[3][0], hex_points[3][1], hex_points[4][0], hex_points[4][1], hex_points[5][0], hex_points[5][1], outline="white", activedash=True) self._hex_ids.append(hex_id) self._hexes.append( Hex(self.hex_grid, self._master, self, hex_id, self._hex_menu_callback)) return hex_points[2]
def is_on_board(coord): if Hex.hex_distance((0, 0), coord) > 6: return False else: return True
import prettytensor as pt import tensorflow as tf import numpy as np import random import json import sys import os from itertools import cycle from hex import Hex topp = len(sys.argv) > 1 n = 3 hex = Hex(n) BATCH_SIZE = 100 x = tf.placeholder(tf.float64, shape=(None, n**2 + 1), name="x") y = tf.placeholder(tf.float64, shape=(None, n**2), name="y") def tprint(msg): def inner(activation): return tf.Print(activation, [activation], msg) return inner y_ = (
def draw_hexagon(center, s, fill_color, hex_screen=None): if not hex_screen: hex_screen = Board.screen pg.draw.polygon(hex_screen, fill_color, [Hex.hex_corner(center, s, p) for p in range(6)]) pg.draw.polygon(hex_screen, Board.colors[0], [Hex.hex_corner(center, s, p) for p in range(6)], Board.line_width)
def draw_ring(center, n, fill_color): for p in Hex.hex_ring(center, n): Board.draw_hexagon_axial(p[0], p[1], fill_color)
def get_mouse_axial(): pos = pg.mouse.get_pos() q = (2. / 3 * (pos[0] - Board.width / 2)) / Board.size r = (-1. / 3 * (pos[0] - Board.width / 2) + sqrt(3) / 3 * (pos[1] - Board.height / 2)) / Board.size return Hex.hex_round((q, r))
def get_distance(h, s=(0, 0)): return Hex.hex_distance(s, h)
def _set_pos(self, x, y): self.pos = Hex(x, y)
def get_other_coord(tile): return Hex.hex_neighbor(tile[0][0:2], tile[0][2])
import pygame import math from pygame.locals import Color import constants black = Color('black') white = Color('white') from utils import random_position from objects import Container, Avatar, Minion from hex import Hex from actions import Action pygame.init() surface = pygame.display.set_mode(( int((constants.MAP_WIDTH - 2/3) * Hex.pixel_width() * 3/4), int((constants.MAP_HEIGHT - 0.5) * Hex.pixel_height()) )) objects = [] minions = [] rocks = Container(float("inf"), True, False) rocks._set_pos(*random_position()) objects.append(rocks) bucket = Container(0, False, True) bucket._set_pos(*random_position()) objects.append(bucket) avatar = Avatar(minions, objects)
def is_touching(a, b): return Hex.hex_distance(a, b) == 1
def get_line_step(coord, k, tiles): coord = Hex.hex_neighbor(coord, k) if Board.is_on_board(coord): tiles.append(coord) Board.get_line_step(coord, k, tiles)
def __init__(self, image): self.image = pygame.image.load(image).convert_alpha() self.pos = Hex(0, 0) self.surface = pygame.display.get_surface() self.font = pygame.font.SysFont("droidsans", 15) self.font.set_bold(True)