def move(self, direction: int): status = self.program.enter_input(direction)[0][0] delta = { 1: Coords(0, 1), 2: Coords(0, -1), 3: Coords(-1, 0), 4: Coords(1, 0), }[direction] signs = { 1: '^', 2: 'v', 3: '<', 4: '>', } if status == 0: self.map[self.pos + delta] = '\u2588' elif status == 1: self.mark(delta, signs[direction]) self.pos += delta else: self.mark(delta, signs[direction]) self.pos += delta self.map[self.pos] = 'O' self.min_x = min(self.pos.x, self.min_x) self.max_x = max(self.pos.x, self.max_x) self.min_y = min(self.pos.y, self.min_y) self.max_y = max(self.pos.y, self.max_y) return status
def __init__(self, program: StatefulIntcode): self.program = program self.pos = Coords(0, 0) self.map = {Coords(0, 0): 'S'} self.min_x = 0 self.max_x = 0 self.min_y = 0 self.max_y = 0 self.mode = 'map' self.counter = 0 self.max = 0
def _set_ally_fountain_loc(self): if ColorLib.match_color_screen( self.img, (GameCoords.bottom_left_base.x, GameCoords.bottom_left_base.y), GameCoords.bottom_left_base.colors[0], 15, -15): self._my_fountain_coords = GameCoords.bottom_fountain self._my_team_side = 'bot' self._general_enemy_dir_coords = Coords(x=870, y=180) else: self._my_fountain_coords = GameCoords.top_fountain self._my_team_side = 'top' self._general_enemy_dir_coords = Coords(x=380, y=470)
def __init__(self, x: int, y: int) -> None: self.coords = Coords(x=x, y=y) self.total_stars = 0 self.planets_dict: Dict[Coords, Planet] = {} """This value refers to planets that are allied to the ship in question, and not nescaraly to the player """ self.friendly_planets = 0 """This value refers to planets that are neutral to the ship in question, and not nescaraly to the player """ self.neutral_planets = 0 """This value refers to planets that are hostile to the ship in question, and not nescaraly to the player """ self.unfriendly_planets = 0 self.barren_planets = 0 self.objectives = 0 """This value refers to ships that are hostile to the ship in question, and not nescaraly to the player """ self.hostile_ships = 0 """This value refers to ships that are allied to the ship in question, and not nescaraly to the player """ self.allied_ships = 0 self.derelicts = 0 self.planet_count_needs_updating = True self.ship_count_needs_updating = True
def spawnForPlayer(cls, baseData, x, y, stack=-1): if baseData is None or baseData is DUMMY_ITEM: return cls(DUMMY_ITEM, Coords(x, y), E_NONE, 0, False, 1, identified=True) if stack == -1: stack = 1 if baseData.typeOfItem == 'STAFF': stack = rollAttack(2, 1 + baseData.minLevel) return cls(baseData, Coords(x, y), E_NONE, 0, True, 1, identified=True)
def __init__(self, gd: GameData, x: int, y: int): #self.astroObjects = [Sector.__buildSlice(gd.subsec_size_x) for s in gd.subsec_size_range_y] self.safe_spots = list( SubSector.__gen_safe_spot_list(gd.subsec_size_range_x, gd.subsec_size_range_y)) self.coords = Coords(x=x, y=y) #self.x = x #self.y = y #print(stars) self.game_data = gd self.stars_dict: Dict[Coords, Star] = {} self.total_stars = 0 #self.planets = [] self.planets_dict: Dict[Coords, Planet] = {} self.friendly_planets = 0 self.neutral_planets = 0 self.unfriendly_planets = 0 self.barren_planets = 0 self.planets_friendly_to_player = 0 self.planets_neutral_to_player = 0 self.planets_hostile_to_player = 0 self.planets_friendly_to_enemy = 0 self.planets_neutral_to_enemy = 0 self.planets_hostile_to_enemy = 0 self.player_present = False
def __ballEffect(self, gl, user, targetCo, runEffect): eList = gl.getEntitiesInLineOfFire(user, targetCo, maxRange=self.maxRange) #eList = gl.getEntitiesBetweenPoints(user.co, targetCo, maxEntities=10000, maxRange=self.maxRange) ip = (user.co - targetCo).normalize() impactPoint = Coords(round(ip[0] * self.maxRange), round(ip[1] * self.maxRange)) if len(eList) > 0: for e in eList: dist = user.co.distance(e.co) if rollAttack(2, 6) - dist > 0: #to hit roll impactPoint = e.co break if self.radius > 0: # entitiesInBlastArea = list(filter(lambda x: not gl.checkForObstructionBetweenPoints(x.co, impactPoint, maxRange=self.radius) and x.co != impactPoint, gl.allEntities)) entitiesInBlastArea = list( (e for e in gl.allEntities if e.co != impactPoint and not gl.checkForObstructionBetweenPoints( e.co, impactPoint, maxRange=self.radius))) map(lambda x: runEffect(x, x.co.distance(impactPoint)), entitiesInBlastArea) else: # entitiesInBlastArea = list(filter(lambda x: not gl.checkForObstructionBetweenPoints(x.co, impactPoint, maxRange=self.radius) and x.co != impactPoint, gl.allEntities)) entitiesInBlastArea = list( (e for e in gl.allEntities if e.co != impactPoint and not gl.checkForObstructionBetweenPoints( e.co, impactPoint, maxRange=self.radius))) map(lambda x: runEffect(x, x.co.distance(impactPoint)), entitiesInBlastArea)
def regerateLevel(self, depth): ls = self.getLevelSize(depth) w = ls + randint(-depth - 1, depth + 1) * 1 h = ls + randint(-depth - 1, depth + 1) * 1 self.size = ls self.grid = self.genLevel(depth, depth) self.widthHeight = Coords(w, h) self.depth = depth self.visibilityGrid = list(self.genVisibilityGrid(ls)) self.rooms, self.junctions = self.generateDungeonRooms( w, h, 0.06, 0.025) self.assignTerrain(w, h) self.stairs = self.placeStairs() self.itemsOnFloor = [] self.avalibleSpecies = getFilteredSpecies(depth) self.itemsAvalibleForDepth = getListOfItemsSuitbleForDepth(depth) self.itemsByTypeAvalibleForDepth = { k: getSuitbleItemsByType(self.itemsAvalibleForDepth, k) for k in ALL_IMPORTANT_ITEM_TYPES } self.player = None
def get_game_map(intcode): out, done = intcode.run() if done: print("GAME OVER (WTF?)") game_map = dict() for i in range(0, len(out), 3): game_map[Coords(out[i], out[i + 1])] = out[i + 2] return game_map, done
def placeStairs(self): stairs = [] startRoom = self.rooms[0] endRoom = self.rooms[-1] x, y = startRoom.randomPointWithinRoom stairs.append(Coords(x, y)) self.grid[y][x] = choice([ ALL_TILE_DICT['TERRAIN_DOWN_STAIR'], ALL_TILE_DICT['TERRAIN_STAIR'] ]) x, y = endRoom.randomPointWithinRoom stairs.append(Coords(x, y)) self.grid[y][x] = choice([ ALL_TILE_DICT['TERRAIN_UP_STAIR'], ALL_TILE_DICT['TERRAIN_STAIR'] ]) for r in self.rooms[1:-1]: if randFloat() < 1.0 / 3.0: x, y = r.randomPointWithinRoom self.grid[y][x] = choice([ ALL_TILE_DICT['TERRAIN_STAIR'], ALL_TILE_DICT['TERRAIN_UP_STAIR'], ALL_TILE_DICT['TERRAIN_DOWN_STAIR'] ]) stairs.append(Coords(x, y)) for r in self.rooms: if randFloat() < 0.2: x, y = r.randomPointWithinRoom if self.grid[y][x] not in { ALL_TILE_DICT['TERRAIN_STAIR'], ALL_TILE_DICT['TERRAIN_UP_STAIR'], ALL_TILE_DICT['TERRAIN_DOWN_STAIR'] }: self.grid[y][x] = choice([ ALL_TILE_DICT['TERRAIN_STAIR'], ALL_TILE_DICT['TERRAIN_UP_STAIR'], ALL_TILE_DICT['TERRAIN_DOWN_STAIR'] ]) stairs.append(Coords(x, y)) return stairs
def draw(self, render=True): delta, done = get_game_map(self.intcode) self.active = not done self.game_map.update(delta) ball = list(filter(lambda it: it[1] == 4, self.game_map.items()))[0][0] paddle = list(filter(lambda it: it[1] == 3, self.game_map.items()))[0][0] self.autoplay = np.sign(ball.x - paddle.x) score = self.game_map.get(Coords(-1, 0), 0) if render: system('clear') print("Score:", score) print() for y in range(30): for x in range(50): tile = self.game_map.get(Coords(x, y), 0) print(theme[tile], end='') print()
def spawnItem(cls, baseData, x, y, depth, identified=False, stack=-1): if baseData is None or baseData is DUMMY_ITEM: return cls(DUMMY_ITEM, Coords(x, y), E_NONE, 0, False, 1, identified=True) ego = E_NONE egos = list( filter(lambda e: e.minLevel + baseData.minLevel < depth, baseData.egosAllowed)) if len(egos) == 1: ego = egos[0] elif len(egos) > 1: ego = choices( egos, [depth - (e.minLevel + baseData.minLevel) for e in egos])[0] egoPower = depth - (ego.minLevel + baseData.minLevel) if egoPower < 1: egoPower = 0 else: minPower = -egoPower // 4 egoPower = randrange(minPower, egoPower) if egoPower == 0: ego = E_NONE if stack == -1: stack = 1 if baseData.typeOfItem == 'STAFF': stack = ego.extraCharges + baseData.magicEffect.max_charges return cls(baseData, Coords(x, y), ego, egoPower, False, stack, identified)
def print(self): for y in range(self.max_y): for x in range(self.max_x): coords = Coords(x, y) if self.pos == coords: print('@', end='') elif coords in self.trace: print('.', end='') else: print(self.world_map.get(coords, ' '), end='') print()
def print_map(self): for y in reversed(range(self.min_y - 2, self.max_y + 2)): for x in range(self.min_x - 2, self.max_x + 2): coords = Coords(x, y) if coords in self.map.keys(): print(self.map[coords], end='') elif coords == self.pos: print('D', end='') else: print(' ', end='') print()
def lookLOS(vDict): """A very simple and somewhat inefficiant LOS function. for defermining if a grid tile can be marked as 'seen'. May have bugs.""" gameLevel = vDict['gameLevel'] top = max(gameLevel.player.co.y - gameLevel.player.getSightRadius, 0) bottom = min(gameLevel.player.co.y + gameLevel.player.getSightRadius, gameLevel.widthHeight.y) left = max(gameLevel.player.co.x - gameLevel.player.getSightRadius, 0) right = min(gameLevel.player.co.x + gameLevel.player.getSightRadius, gameLevel.widthHeight.x) for x in range(left + 1, right - 1): betterLOS(gameLevel, gameLevel.player, Coords(x, top)) betterLOS(gameLevel, gameLevel.player, Coords(x, bottom)) for y in range(top + 1, bottom - 1): betterLOS(gameLevel, gameLevel.player, Coords(left, y)) betterLOS(gameLevel, gameLevel.player, Coords(right, y))
def __init__(self): self.length = 0.0 self.lines = [] self.current_pos = 0.0 self.current_point = Point(0, 0, 0) self.current_line_index = 0 self.tools = {} # dictionary, tool id to Tool object self.current_tool = 1 self.rapid = True self.mm_per_sec = 50.0 self.running = False self.coords = Coords(0, 0, 0, 0, 0, 0) self.in_cut_to_position = False
def regenerate(self, baseData, x, y, depth, identified=False, stack=-1): if baseData is None or baseData is DUMMY_ITEM: self.baseData = DUMMY_ITEM self.co = Coords(x, y) self.identified = identified self.egoPower = 0 self.ego = E_NONE self.__stack = 0 else: self.__baseData = baseData ego = E_NONE egos = list( filter(lambda e: e.minLevel + baseData.minLevel < depth, baseData.egosAllowed)) if len(egos) == 1: ego = egos[0] elif len(egos) > 1: ego = choices( egos, [depth - (e.minLevel + baseData.minLevel) for e in egos])[0] egoPower = depth - (ego.minLevel + baseData.minLevel) if egoPower < 1: egoPower = 0 else: minPower = -egoPower // 4 egoPower = randrange(minPower, egoPower) if egoPower == 0: ego = E_NONE if stack == -1: stack = 1 if baseData.typeOfItem == 'STAFF': stack = ego.extraCharges + baseData.magicEffect.max_charges else: self.ego = ego self.egoPower = egoPower self.identified = identified self.seen = False self.stack = stack self.identify_item()
def create_tuple(): old_x, old_y = new_coords_x, new_coords_y old_c = None for r in range(CONFIG_OBJECT.max_distance): c:Coords = Coords(round(old_x), round(old_y)) if not no_dups or (not old_c or c != old_c): yield c old_c = c old_x += new_coords_x old_y += new_coords_y
def analyse_scaffold(out): scaffold = dict() x = 0 y = 0 for i in out: if is_line_break(i): y += 1 x = 0 elif i != ord('.'): scaffold[Coords(x, y)] = i x += 1 else: x += 1 return scaffold
def resized(self,size=1.,tol=1.e-5): """Return a copy of the Geometry scaled to the given size. size can be a single value or a list of three values for the three coordinate directions. If it is a single value, all directions are scaled to the same size. Directions for which the geometry has a size smaller than tol times the maximum size are not rescaled. """ from numpy import resize s = self.sizes() size = Coords(resize(size,(3,))) ignore = s<tol*s.max() s[ignore] = size[ignore] return self.scale(size/s)
def quaterLOS(vDict): gameLevel = vDict['gameLevel'] playerPos = gameLevel.player.co top = max(gameLevel.player.co.y - gameLevel.player.getSightRadius, 0) bottom = min(gameLevel.player.co.y + gameLevel.player.getSightRadius, gameLevel.widthHeight.y) left = max(gameLevel.player.co.x - gameLevel.player.getSightRadius, 0) right = min(gameLevel.player.co.x + gameLevel.player.getSightRadius, gameLevel.widthHeight.x) hitBlockWhileScanningPrevousLine = False # scan top quarter t = 1 for t in range(playerPos.y, top, -1): if not hitBlockWhileScanningPrevousLine: hitBlock = False for l_2_r in range(playerPos.x - t, playerPos.x + t): if not gameLevel.grid[t][l_2_r].seeThru: hitBlock = True gameLevel.visibilityGrid[t][l_2_r] = True t += -1 if hitBlock: hitBlockWhileScanningPrevousLine = True else: for l_2_r in range(-t, t): # this is a tuple, not a Coords object nX, nY = (Coords(l_2_r, t) - playerPos).normalize(round_to=True) if not gameLevel.grid[t][l_2_r].seeThru: pass elif not gameLevel.visibilityGrid[t + nY][l_2_r + nX]: pass else: gameLevel.visibilityGrid[t][l_2_r] = True
def Reset(self): global toolpath toolpath = self # get the box of all the solids box = wx.GetApp().program.stocks.GetBox() if box.valid: c = box.Center() width = box.Width() height = box.Height() depth = box.Depth() + 10 minz = box.MinZ() - 10 if width < 100: width = 100 if height < 100: height = 100 box.InsertBox( geom.Box3D(c.x - width / 2, c.y - height / 2, minz, c.x + width / 2, c.y + height / 2, minz + depth)) else: box.InsertBox(geom.Box3D(-100, -100, -50, 100, 100, 50)) self.coords = Coords(box.MinX(), box.MinY(), box.MinZ(), box.MaxX(), box.MaxY(), box.MaxZ()) self.coorfs.add_block(0, 0, -10, 100, 100, 10) # add each stock stocks = wx.GetApp().program.stocks.GetChildren() for stock in stocks: stock_box = stock.GetBox() sim.set_current_color(stock.GetColor().ref()) c = box.Center() self.coords.add_block(c.x, c.y, box.MinZ(), box.Width(), box.Height(), box.Depth()) tools = wx.GetApp().program.tools.GetChildren() for tool in tools: self.tools[tool.tool_number] = GetSimToolDefinition(tool) machine_module = __import__('nc.' + wx.GetApp().program.machine.reader, fromlist=['dummy']) parser = machine_module.Parser(self) parser.Parse(wx.GetApp().program.GetOutputFileName()) self.rewind() self.timer = wx.Timer(wx.GetApp().frame, wx.ID_ANY) self.timer.Start(33) wx.GetApp().frame.Bind(wx.EVT_TIMER, OnTimer)
def select_ship_planet_star(game_data:GameData, event: "tcod.event.MouseButtonDown") -> Union[Planet, Star, Starship, bool]: """Attempts to select the ship, planet, or star that the player is clicking on. Otherwise, it returns a boolean value depending on weither the cursor was positioned over a system grid square. Args: game_data (GameData): The GameData object. event (tcod.event.MouseButtonDown): The event containing the location of the click. Returns: Union[Planet, Star, Starship, bool]: If the mouse cursor is over a ship, planet, or star, that object will be returned. If not, then True will be returned. If the mouse cursor was not over a grid square, False will be returned. """ x,y = CONFIG_OBJECT.subsector_display_x, CONFIG_OBJECT.subsector_display_y width, height = CONFIG_OBJECT.subsector_width, CONFIG_OBJECT.subsector_height x_range = range(x+1, x+2+width*2, 2) y_range = range(y+1, y+1+height*2, 2) if event.tile.x in x_range and event.tile.y in y_range: x_ajusted = (event.tile.x - (x + 1)) // 2 y_ajusted = (event.tile.y - (y + 1)) // 2 subsector = game_data.player.get_sub_sector co = Coords(x_ajusted, y_ajusted) try: planet = subsector.planets_dict[co] return planet except KeyError: try: star = subsector.stars_dict[co] return star except KeyError: for ship in game_data.ships_in_same_sub_sector_as_player: if ( ship.local_coords.x == x_ajusted and ship.local_coords.y == y_ajusted and ship.ship_status.is_visible ): return ship return True else: return False
def __init__(self, depth=0, valueOfItemsToSpawn=50): ls = self.getLevelSize(depth) w = ls + randint(-depth - 1, depth + 1) * 5 h = ls + randint(-depth - 1, depth + 1) * 5 self.size = ls self.grid = self.genLevel(w, h) self.widthHeight = Coords(w, h) self.depth = depth self.visibilityGrid = list(self.genVisibilityGrid(w, h)) self.rooms, self.junctions = self.generateDungeonRooms( w, h, 0.06, 0.025) self.assignTerrain(w, h) self.stairs = self.placeStairs() self.itemsOnFloor = [] self.avalibleSpecies = getFilteredSpecies(depth) self.itemsAvalibleForDepth = getListOfItemsSuitbleForDepth(depth) self.itemsByTypeAvalibleForDepth = { k: getSuitbleItemsByType(self.itemsAvalibleForDepth, k) for k in ALL_IMPORTANT_ITEM_TYPES } self.player = None self.allEntities = [] self.spawnInhabitants(depth) self.open_spaces = set() for r in self.rooms: for y in r.topToBottomRange: for x in r.leftToRightRange: self.open_spaces.add(tuple([x, y])) for h in self.junctions: hw = h.generateList self.open_spaces = self.open_spaces | set(hw) self.number_of_open_spaces = len(self.open_spaces)
def getRADec(name): '''get a Coords object for the given object''' script = r'''format object "%COO(:s;A | D)" query id {0}'''.format(name) result = script_request(script) if ':error:' in result[0]: return None ra, dec = result[0].split('|') ra = RA_coord.fromStr(ra.strip()) match = getRADec._min_re.match(dec.strip()) if match: #we need to take care of the special case when we get fractional minutes instead of seconds d = int(match.group(1)) mins = Decimal(match.group(2)) m = int(mins) s = (mins - m) * 60 dec = Dec_coord(d, m, s) else: dec = Dec_coord.fromStr(dec.strip()) return Coords(ra, dec)
def getLocationsWithinRadius(self, radius, condition, locationX, locationY=None): if isinstance(locationX, Coords): location: Coords = locationX else: location: Coords = Coords(locationX, locationY) locList = [] for y in range(max(0, location.y - radius), min(self.widthHeight.y, location.y + radius)): for x in range(max(0, location.x - radius), min(self.widthHeight.x, location.x + radius)): if location.distance(x, y) <= radius: if condition(x, y): locList.append(tuple([x, y])) return locList
def vtkIntersectWithSegment(surf, lines, tol=0.0): """ Computes the intersection of surf with lines. Returns a list of the intersection points lists and of the element number of surf where the point lies. The position in the list is equal to the line number. If there is no intersection with the correspondent lists are empty Parameters: surf : can be Formex, Mesh or TriSurface lines : a mesh of segments """ from vtk import vtkOBBTree surf = convert2VPD(surf, clean=False) loc = vtkOBBTree() loc.SetDataSet(vm) loc.SetTolerance(tol) loc.BuildLocator() loc.Update() cellids = [ [], ] * lines.nelems() pts = [ [], ] * lines.nelems() for i in range(lines.nelems()): ptstmp = vtkPoints() cellidstmp = vtkIdList() loc.IntersectWithLine(lines.coords[lines.elems][i][1], lines.coords[lines.elems][i][0], ptstmp, cellidstmp) if cellidstmp.GetNumberOfIds(): cellids[i] = [ cellidstmp.GetId(j) for j in range(cellidstmp.GetNumberOfIds()) ] pts[i] = Coords(v2n(ptstmp.GetData()).squeeze()) loc.FreeSearchStructure() del loc return pts, cellids
def createElementType(name, doc, ndim, vertices, edges=('', []), faces=('', []), **kargs): name = name.capitalize() if name in _registered_element_types: raise ValueError, "Element type %s already exists" % name #print "\n CREATING ELEMENT TYPE %s\n" % name D = dict( __doc__='_' + doc, # block autodoc for generated classed ndim=ndim, vertices=Coords(vertices), edges=_sanitize(edges), faces=_sanitize(faces), ) for a in ['drawedges', 'drawedges2', 'drawfaces', 'drawfaces2']: if a in kargs: D[a] = [_sanitize(e) for e in kargs[a]] del kargs[a] # other args are added as-is D.update(kargs) #print "Final class dict:",D ## # add the element to the collection ## if self._name in Element.collection: ## raise ValueError,"Can not create duplicate element names" ## Element.collection[self._name] = self C = type(name, (ElementType, ), D) _registered_element_types[name] = C return C
def main(): pygame.init() width = 800 height = 600 screen = pygame.display.set_mode([width,height]) screen_center = Vec2d(width/2, height/2) coords = Coords(screen_center.copy(), 1, True) zoom = 100 coords.zoom_at_coords(Vec2d(0,0), zoom) # Used to manage how fast the screen updates clock = pygame.time.Clock() # Create initial objects to demonstrate objects = [] points = (Vec2d(0,0), Vec2d(1,0), Vec2d(1,0.5), Vec2d(0.5,0.5), Vec2d(0.5,1), Vec2d(0,1), )
def get_lookup_table( *, direction_x:float, direction_y:float, normalise_direction:bool=True, no_dups:bool=True ): new_coords_x, new_coords_y = Coords( x=direction_x, y=direction_y ).normalize() if normalise_direction else (direction_x, direction_y) def create_tuple(): old_x, old_y = new_coords_x, new_coords_y old_c = None for r in range(CONFIG_OBJECT.max_distance): c:Coords = Coords(round(old_x), round(old_y)) if not no_dups or (not old_c or c != old_c): yield c old_c = c old_x += new_coords_x old_y += new_coords_y return tuple(create_tuple())