def printPossibleMoves(g: Game, c: Coord): moves = g.getPossibleMoves(c) b = g.board print(Style.BRIGHT, end="") print(Fore.RED + " Black " + Fore.RESET) print(" 0 1 2 3 4 5 6 7") print(" " + "▄" * 18) for y in range(len(b)): print(f"{y} █", end="") for x in range(len(b[y])): print(Back.LIGHTBLACK_EX if (x + y) % 2 == 1 else Back.BLACK, end="") if (Coord(x, y) in moves): print(Back.LIGHTMAGENTA_EX, end="") elif (Coord(x, y) == c): print(Back.LIGHTCYAN_EX, end="") if (b[y][x].team == 1): print(Fore.RED, end="") elif (b[y][x].team == 0): print(Fore.BLUE, end="") print(chooseSprite(b[y][x]), end=" ") print(Back.RESET + Fore.RESET, end="") print("█") print(" " + "▀" * 18) print(Fore.BLUE + " White " + Fore.RESET) print(Style.RESET_ALL, end="")
def test_gamemanager(level2): gm = GameManager() player_names = [] for i in range(3): player_names.append("bruh " + str(i)) gm.register_player_names(player_names) assert len(gm.players) == 3 assert gm.players[0].name == "bruh 0" assert gm.players[1].name == "bruh 1" assert gm.players[2].name == "bruh 2" gm.start_game(level2) assert gm.gamestate.current_level assert len(gm.players) == 3 assert len(gm.gamestate.players) == 3 assert gm.players[0].name == "bruh 0" assert gm.players[1].name == "bruh 1" assert gm.players[2].name == "bruh 2" new_player_locs = [gm.players[0].pos, gm.players[1].pos, gm.players[2].pos] new_player_locs[2] = Coord(7, 18) gm.request_player_move(gm.players[2].name, Coord(7, 3)) assert gm.players[2].pos == Coord(7, 3) item = Item(KEY, Coord(8, 17)) gm.apply_player_item_interaction(gm.gamestate.players[2], Coord(8, 17)) print(str(gm.gamestate.players[2])) assert item in gm.gamestate.players[2].inventory
def get_reachable_tiles(self, coord): try: tiles = [] is_horizontal = self.check_orientation() # If halls should be 1 tile wide any traversable coord in a horizontal hall must have the same y value as a door. The range of traversable tiles spans the x boundary while y does not change if is_horizontal == True: col_values = set() for room in self.rooms: for door in room.doors: col_values.add(door.col) for ii in range(self.origin.row, self.origin.row + self.dimensions.row + 1): if coord.col in col_values: new_coord = Coord(ii, coord.col) tiles.append(new_coord) elif is_horizontal == False: row_values = set() for room in self.rooms: for door in room.doors: row_values.add(door.row) for jj in range(self.origin.col, self.origin.col + self.dimensions.col + 1): if coord.row in row_values: new_coord = Coord(coord.row, jj) tiles.append(new_coord) return tiles except Exception as err: print(err) return None
def post(self): headers = request.headers game_id = headers["game"] if (game_id not in manager.games.keys()): return {"error": "game not in game manager"} g = manager.getGame(game_id) if (headers["action"] == "move"): fromC = Coord(headers["x1"], headers["y1"]) toC = Coord(headers["x2"], headers["y2"]) try: g.makeMove(fromC, toC) db.child("Games").child(game_id).set( toJson(manager.games[game_id])) return {"done": True} except Exception as e: return { "error": "error at moving, message included.", "message": str(e) } if (headers["action"] == "getMoves"): fromC = Coord(headers["x1"], headers["y1"]) try: valids = g.getValidMoves(fromC) except Exception as e: return {"error": str(e)} print([str(c) for c in valids]) out = {"coords": []} # ind = 0 for c in valids: out["coords"].append({"x": c.x, "y": c.y}) # ind+=1 return out g.debugPrint()
def printValidMoves(g: Game, c: Coord): moves = g.getValidMoves(c) b = g.board print(Style.BRIGHT, end="") if g.turn == 1: print(Fore.RED + " > Black <", g.getScore(), Fore.RESET) else: print(Fore.RED + " Black ", g.getScore(), Fore.RESET) print(" a b c d e f g h") print(" " + "▄" * 18) for y in range(len(b)): print(f"{8-y} █", end="") for x in range(len(b[y])): print(Back.LIGHTBLACK_EX if (x + y) % 2 == 1 else Back.BLACK, end="") if (Coord(x, y) in moves): print(Back.LIGHTMAGENTA_EX, end="") elif (Coord(x, y) == c): print(Back.LIGHTCYAN_EX, end="") if (b[y][x].team == 1): print(Fore.RED, end="") elif (b[y][x].team == 0): print(Fore.BLUE, end="") print(chooseSprite(b[y][x]), end=" ") print(Back.RESET + Fore.RESET, end="") print("█") print(" " + "▀" * 18) if g.turn == 0: print(Fore.BLUE + " > White <", g.getScore(), Fore.RESET) else: print(Fore.BLUE + " White ", g.getScore(), Fore.RESET) print(Style.RESET_ALL, end="")
def get_introns(self): """Returns a list of coordinates that represent the introns for this transcript""" introns = [] for i in range(len(self.exons) - 1): ex1 = self.exons[i] ex2 = self.exons[i + 1] if self.strand == -1: intron = Coord(self.chrom, ex2.end + 1, ex1.start - 1, strand=self.strand) else: intron = Coord(self.chrom, ex1.end + 1, ex2.start - 1, strand=self.strand) intron.exon_5p = ex1 intron.exon_3p = ex2 introns.append(intron) if self.intron_scores is not None: intron.score = self.intron_scores[i] if self.known_intron_flags is not None: if self.known_intron_flags[i] == "1": intron.is_known = True else: intron.is_known = False return introns
def generate_pacman_and_cherries(self): free_cells = [ pos for pos, cell in self.grid.cells.items() if pos.x != self.grid.width // 2 and cell.is_floor() ] self.random.shuffle(free_cells) left_cells = [ pos for pos in free_cells if pos.x < self.grid.width // 2 ] i = 0 while i < self.pacman_per_player: left_cell = Coord(left_cells[i].x, left_cells[i].y) right_cell = Coord(self.grid.width - 1 - left_cell.x, left_cell.y) left_player = self.random.randint(0, 1) right_player = (left_player + 1) % 2 self.players[left_player][i] = left_cell self.players[right_player][i] = right_cell i += 1 for j in range(self.cherries // 2): left_cell = Coord(left_cells[i + j].x, left_cells[i + j].y) right_cell = Coord(self.grid.width - 1 - left_cell.x, left_cell.y) self.grid.get(left_cell).has_cherry = True self.grid.get(right_cell).has_cherry = True players = set() for player in self.players: for pos in player: players.add(pos) for pos, cell in self.grid.cells.items(): if cell.is_floor() and not cell.has_cherry and pos not in players: cell.has_pellet = True
def maxSlices(pizza): matrix = pizza.grid print "matrix:" print matrix # Output Data Type slices = [] iMax = pizza.R jMax = pizza.C i = 0 while (i < (iMax - 1)): j = 0 while (j < (jMax - 1)): startVal = matrix[i][j] endVal = matrix[i][j + 1] if (isValidSlice(startVal, endVal)): startCoord = Coord(i, j) endCoord = Coord(i, j + 1) currSlice = Slice(startCoord, endCoord) slices.append(currSlice) j += 2 else: j += 1 i += 1 # print matrix for currSlice in slices: currSlice.printSlice() visitSlices(matrix, slices)
def test_coord(): c1 = Coord(0, 0) c2 = Coord(0, 1) c3 = Coord(0, 0) assert c1 != c2 assert c2 != c3 assert c1 == c3
def next_best_point(st, bot=None): minX = bot.region["minX"] maxX = bot.region["maxX"] minZ = bot.region["minZ"] maxZ = bot.region["maxZ"] # print(bot.region) for y, x, z in np.transpose( np.where( np.transpose(st.matrix._ndarray, (1, 0, 2)) == state.Voxel.MODEL)): if minX <= x < maxX and minZ <= z < maxZ: coord = Coord(int(x), int(y), int(z)) if st.matrix.would_be_grounded(coord): # print(coord) return coord for y, x, z in np.transpose( np.where( np.transpose(st.matrix._ndarray, (1, 0, 2)) == state.Voxel.MODEL)): if minX - (maxX - minX) / 2 <= x < maxX + (maxX - minX) / 2 and minZ - ( maxZ - minZ) / 2 <= z < maxZ + (maxZ - minZ) / 2: coord = Coord(int(x), int(y), int(z)) if st.matrix.would_be_grounded(coord): # print(coord) return coord return None
def parse_room_obj(room_input): try: room_json = json.loads(room_input) except TypeError: room_json = room_input origin = None bounds = None layout = None point = None try: # [Room, Point] format if room_json[0][TYPE] != ROOM: print('Invalid Args: Type is not room') return None input_json = room_json[0] point = room_json[1] except (KeyError, IndexError): input_json = room_json origin = input_json[ORIGIN] bounds = input_json[BOUNDS] layout = input_json[LAYOUT] origin_coord = to_coord(origin) dimensions = Coord(bounds[ROWS], bounds[COLS]) tiles = [] doors = [] for ii in range(0, bounds[ROWS]): for jj in range(0, bounds[COLS]): # ii = x jj = y if layout[ii][jj] != 0: tiles.append(Coord(origin[0] + ii, origin[1] + jj)) if layout[ii][jj] == 2: doors.append(Coord(origin[0] + ii, origin[1] + jj)) return {COORD: to_coord(point) if point else None, ROOM: Room(origin_coord, dimensions, tiles, doors)}
def part2(program): screen = {} score = None last_ball_x = 0 last_paddle_x = 0 def paddle_ai(): return (last_ball_x > last_paddle_x) - (last_ball_x < last_paddle_x) computer = Computer(program, mem_override={0: 2}, input=paddle_ai) computer.input_func = paddle_ai while not computer.halted: try: x = computer.run() y = computer.run() pos = Coord(x, y) if pos == Coord(-1, 0): score = computer.run() else: screen[pos] = computer.run() if screen[pos] == 3: last_paddle_x = pos.x if screen[pos] == 4: last_ball_x = pos.x except Halted: pass return score
def aStar(mapCells, srcX, srcY, dstX, dstY): openSet = [] closedSet = [] startNode = Node(mapCells, srcX, srcY, dstX, dstY, None) openSet.append(startNode) while len(openSet) != 0: curCandidate = getLowestScoreNode(openSet) if curCandidate.x == dstX and curCandidate.y == dstY: #then success! path = [] curNode = curCandidate while not (curNode.x == srcX and curNode.y == srcY): coord = Coord(curNode.x, curNode.y) path.append(coord) curNode = curNode.prev # we also add this last one coord = Coord(curNode.x, curNode.y) path.append(coord) path.reverse() return path openSet.remove(curCandidate) closedSet.append(curCandidate) # add this node's neighbors to the open list addNeighbors(curCandidate, openSet, closedSet, mapCells, dstX, dstY) print "oh no!"
def test_invalid_level_dimensions(capsys, level1): invalid_dimensions = Room(Coord(6, 1), Coord(6, 6), tiles, doors) level1.rooms.append(invalid_dimensions) valid_level = check_level(level1) capture = capsys.readouterr() assert capture.out == 'Invalid Level: Overlapping Room(s) or Hallway(s)\n' assert valid_level == False
def get_cardinal_coords(cur_pos): up = Coord(cur_pos.row - 1, cur_pos.col) down = Coord(cur_pos.row + 1, cur_pos.col) left = Coord(cur_pos.row, cur_pos.col - 1) right = Coord(cur_pos.row, cur_pos.col + 1) directions = [up, down, left, right] return directions
def _find_coord(self, s): _p = s.split() for x in _p: r = re_coord1.search(x) if r: p = r.group(0).replace("-", " ").replace(":", " ").replace( ",", "").replace(".", "").split() return (s.replace(r.group(0), "").strip(), Coord(p[0].replace("x", "X").replace("y", "Y"), p[1], p[2])) for x in _p: r = re_coord2.search(x) if r: p = r.group(0).replace("-", " ").replace(":", " ").replace( ",", "").replace(".", "").split() return (s.replace(r.group(0), "").strip(), Coord(p[0].replace("x", "X").replace("y", "Y"), p[1], int(p[1]) + 1)) for x in _p: r = re_coord3.search(x) if r: c = r.group(0).replace("x", "X").replace("y", "Y") return (s.replace(r.group(0), "").strip(), Coord(c, 0, chrom_lengths[self.assembly][c])) return (s, None)
def handle_keys(self): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == KEYDOWN: pass elif event.type == KEYUP: pass elif event.type == MOUSEBUTTONDOWN: print(self.plan_map) print('BUTTON:', event.button) x, y = event.pos if event.button == 1: if self.first_vertex: self.plan_map.firstV.x = x self.plan_map.firstV.y = y self.first_vertex = not self.first_vertex elif self.nearest_edge is None: self.plan_map.split_edge(self.plan_map.lastE, Coord(x, y)) else: self.plan_map.split_edge(self.nearest_edge, Coord(x, y)) elif event.button == 3: nearest_edge = self.plan_map.nearest_edge(Coord(x, y)) print('Nearest edge:', nearest_edge)
def create(cls, arr, height=None, width=None, chart_id=None, index=None, pixels=None, orientation=0, mirror=(False, False)): obj = cls() obj.arr = np.array(arr, dtype=Chart.DATA_TYPE, copy=True) obj.chart_id = chart_id if height == None: obj.height = obj.arr.shape[0] else: obj.height = height if width == None: obj.width = obj.arr.shape[1] else: obj.width = width if index != None: obj.index = Coord(index) obj.low = Coord(index[0], index[1]) obj.high = Coord(index[0] + height, index[1] + width) if pixels == None: obj.pixels = obj._count_pixels() else: obj.pixels = pixels if orientation < 0 or orientation > 3: raise Exception('Invalid orientation in Chart.create') obj.orientation = orientation return obj
def get_next_move(self, coordstring): #I am Player One. Only return one coordinate if(coordstring[0:1]=='D'): move = random.choice(list(self.__moves)) self.__moves.discard(move) print move, "jjj" return str(move.get_msg_repr()) #I am Player two, this is my first move. if(coordstring[0:1]=='L'): self.__moves.discard(Coord(coordstring[1:3],coordstring[3:5])) self.__moves.discard(Coord(coordstring[5:7],coordstring[7:9])) #Regular Case else: self.__moves.discard(Coord(coordstring[0:2],coordstring[2:4])) self.__moves.discard(Coord(coordstring[4:6],coordstring[6:8])) move1 = random.choice(list(self.__moves)) self.__moves.discard(move1) move2 = random.choice(list(self.__moves)) self.__moves.discard(move2) returnvalue = str(move1.get_msg_repr()+move2.get_msg_repr()) return returnvalue
def test_reachable_tiles_multiple(room1): coord = Coord(8, 7) tiles = room1.get_reachable_tiles(coord) assert len(tiles) == 3 assert Coord(8, 6) in tiles assert Coord(8, 8) in tiles assert Coord(9, 7) in tiles
def gen_ref(self, tx, wall_type, wall_pos): distance = 0 if wall_type == "top" or wall_type == "bottom": distance = wall_pos - tx.y return Coord(tx.x, tx.y + 2 * distance), wall_type else: distance = wall_pos - tx.x return Coord(tx.x + 2 * distance, tx.y), wall_type
def test_invalid_level_shared_coords(capsys, room1, level1): hall = Hallway([Coord(5, 15), Coord(10, 20)], [room1, room2]) level1.hallways[0] = hall valid_level = check_level(level1) capture = capsys.readouterr() # assert capture.out == 'Invalid Level: Hallway or Room sharing coordinates\n' # TODO: Fix hallway to be valid assert valid_level == False
def generate_straight_moves(piece: BasePiece, all_pieces: Iterable[BasePiece], repeat: bool = True): return generate_offset_moves( piece, all_pieces, (Coord(1, 0), Coord(-1, 0), Coord(0, 1), Coord(0, -1)), repeat, )
def generate_diagonal_moves(piece: BasePiece, all_pieces: Iterable[BasePiece], repeat: bool = True): return generate_offset_moves( piece, all_pieces, (Coord(1, -1), Coord(-1, 1), Coord(1, 1), Coord(-1, -1)), repeat, )
def __init__(self, x, y, vx, vy, car_type='normal', attack_type=None): self.id = next(self.id_generator) self.position = Coord(x, y) self.speed = Coord(vx, vy) self.type = car_type self.generate_xpath() self.generate_ypath() self.attack_type = attack_type self.network = None
def shortest_path_algo(st): bot = st.bots[0] bot.smove(UP) minX, maxX, minY, maxY, minZ, maxZ = st.matrix.bounds print(st.matrix.bounds) minarea, maxbots = 6 * 6, 20 width, depth = maxX - minX, maxZ - minZ mostarea = width * depth / maxbots rsize = ceil(sqrt(max(mostarea, minarea))) xbots, zbots = max(floor(width / rsize), 1), max(floor(depth / rsize), 1) nbots = xbots * zbots print("nbots: {}".format(nbots)) regions = [] for x in range(xbots): rX = min([maxX, minX + (x + 1) * rsize]) if maxX - rX < rsize: rX = maxX for z in range(zbots): rZ = min([maxZ, minZ + (z + 1) * rsize]) if maxZ - rZ < rsize: rZ = maxZ region = { "minX": int(minX + x * rsize), "maxX": int(rX), "minZ": int(minZ + z * rsize), "maxZ": int(rZ) } print(region) regions.append(region) # print(convex_hull(st)) # print(st.matrix.bounds) st.step_all() for i in range(1, nbots): # print(st.bots[0].seeds) sorted(st.bots, key=lambda bot: -len(bot.seeds))[0].fission(FORWARD, 0) st.step_all() b = st.bots[i] b.region = regions[nbots - i - 1] path = shortest_path(st, b, Coord(b.region["minX"], 1, b.region["minZ"])) if path: compress(st, b, path) st.step_all() b = st.bots[0] b.region = regions[nbots - 1] path = shortest_path(st, b, Coord(b.region["minX"], 1, b.region["minZ"])) if path: compress(st, b, path) st.step_all() solve(st) print("finished solve") st.step_all()
def add_target(self, random=True, set_location=Coord(0, 0)): if random == True: self.target_coords.append( Coord(randint(0, self.x - 1), randint(0, self.y - 1))) self.num_targets += 1 self.total_targets += 1 else: self.target_coords.append(set_location) self.num_targets += 1 self.total_targets += 1 self.target_set = True
def test_basic_matrix(self): m = Matrix(problem=1) c = Coord(8, 9, 10) self.assertTrue(m[c].is_void()) m[c].set_full() self.assertTrue(m[c].is_full()) self.assertFalse(m[c].is_grounded()) m.yplane(9)[8, 10].set_grounded() self.assertTrue(m[c].is_grounded()) self.assertTrue(m[Coord(13, 5, 8)].is_model())
def copy(cls, chart): obj = cls() obj.arr = np.array(chart.arr, dtype=Chart.DATA_TYPE, copy=True) obj.chart_id = chart.chart_id obj.height = chart.height obj.width = chart.width obj.index = Coord(chart.index) obj.low = Coord(chart.low) obj.high = Coord(chart.high) obj.pixels = chart.pixels obj.orientation = chart.orientation return obj
def dig_mofo(st, bot, pt): print("dig dig dig") print(bot.pos) bot.actions = [] print(pt) path = None if path is None: start = Coord(st.R - 1, pt.y, pt.z) path = shortest_path(st, bot, start) dir = RIGHT n = st.R - pt.x - 2 if path is None: start = Coord(pt.x, pt.y, 0) path = shortest_path(st, bot, start) dir = FORWARD n = pt.z - 1 if path is None: start = Coord(pt.x, pt.y, st.R - 1) path = shortest_path(st, bot, start) dir = BACK n = st.R - pt.z - 2 if path is None: start = Coord(0, pt.y, pt.z) path = shortest_path(st, bot, start) dir = LEFT n = pt.x - 1 if path is not None: # print("got path") print(path) compress(st, bot, path) else: print("couldn't find path to pt: " + str(start)) for i in range(n): bot.smove(dir) start += dir bot.void(dir) bot.fill(dir) for i in range(n): bot.smove(dir.mul(-1)) start += dir.mul(-1) if st.matrix[start + dir].is_model(): bot.fill(dir) print("finished digging")