def __init__(self): pygame.sprite.Sprite.__init__(self) self.burstAnimator = Animator.__init__(self) self.flowAnimator = Animator.__init__(self) self.spawn = True self.run_burst = False self.hitted_rects = []
def __init__(self, pos: list, images): super().__init__() Animator.__init__(self) self.images = images self.default_speed = 1600 self.speed = self.default_speed if isinstance(self.images, list): self.rect = self.images[0].get_rect(center=pos) else: self.rect = self.images.get_rect(center=pos) self.hitted_rects = [self.rect.copy()]
def __init__(self, filename, position, default_velocity=[PLAYER_DEF_V, 0.0], velocity=[0.0, 0.0], acceleration=[0.0, GRAVITY]): Creature.__init__(self, filename, position, default_velocity, velocity, acceleration, max_y=800) self.flapping = False self.flap_amount = FLAP_AMOUNT self.jump_amount = JUMP_AMOUNT self.shots = 10 self._points = 0 walking_image_names = ["%s.png" % i for i in range(1, 3)] walking_images = [] for i in walking_image_names: walking_images += [ mediahandler.load_image( i, os.path.join("images", "player_walking"), -1, False) ] flapping_image_names = ["%s.png" % i for i in range(1, 5)] flapping_images = [] for i in flapping_image_names: flapping_images += [ mediahandler.load_image( i, os.path.join("images", "player_flapping"), -1, False) ] normal_image = mediahandler.load_image( "1.png", os.path.join("images", "player_normal"), -1, False) self.image = normal_image walking_animator = Animator(walking_images) flapping_animator = Animator(flapping_images) self.stances = { "walking": walking_animator, "flapping": flapping_animator, "normal": Animator([normal_image]) } self.anim_time = 0 self.anim_threshold = 75 self.lives = 3 self.next_life = NEW_LIFE
def get_game_variables(constants): inventory_component = Inventory(26) body_component = get_human_body() player = Entity(int(constants['screen_width'] / 2), int(constants['screen_height'] / 2), '@', tcod.white, "Player", blocks=True, render_order=RenderOrder.ACTOR, ai=Player, inventory=inventory_component, body=body_component) entities = [player] animator = Animator([]) turn_count = 0 game_map = GameMap(constants['map_width'], constants['map_height']) game_map.make_map(player, entities, constants) message_log = MessageLog(constants['message_x'], constants['message_width'], constants['message_height']) game_state = GameStates.PLAYER_TURN return player, entities, animator, turn_count, game_map, message_log, game_state
def __init__(self, images, rect, name, speed): super().__init__() self.burstAnimator = Animator() self.flowAnimator = Animator() self.image = images[name]['default'] self.burst_list = images[name]['burst'] self.icon = images[name]['icon'] self.speed = speed self.spawn = False x, y = rect.centerx, int(rect.top + self.icon.get_height() // 2) # хитбокс создается на основе картинки без эффектов self.icon_rect = self.icon.get_rect(center=(x, y)) self.rect = self.image.get_rect(center=(x, y)) self.hitted_rects = [self.rect.copy()] self.run_burst = False
class Shell(pygame.sprite.Sprite, Animator): # общий класс для пуль всех типов def __init__(self, images, rect, name, speed): super().__init__() self.burstAnimator = Animator() self.flowAnimator = Animator() self.image = images[name]['default'] self.burst_list = images[name]['burst'] self.icon = images[name]['icon'] self.speed = speed self.spawn = False x, y = rect.centerx, int(rect.top + self.icon.get_height() // 2) # хитбокс создается на основе картинки без эффектов self.icon_rect = self.icon.get_rect(center=(x, y)) self.rect = self.image.get_rect(center=(x, y)) self.hitted_rects = [self.rect.copy()] self.run_burst = False def draw(self, display): if self.run_burst: display.blit(self.burst_list[self.burstAnimator.getIteral], self.rect) else: display.blit(self.image, self.rect) def update(self, now): self.rect.y -= self.speed if self.run_burst: self.burstAnimator.updateAnimation(now, len(self.burst_list), 40, self.kill) # 40 self.speed = 0 self.rect = self.burst_list[self.burstAnimator.getIteral].get_rect( center=(self.rect.center)) else: self.burstAnimator.change_time(now) self.icon_rect.center = self.rect.center self.hitted_rects[0] = self.icon_rect
def play_game(con, player, entities, animator: Animator, turn_count: int, game_map: GameMap, message_log, game_state, panel, constants): target_x, target_y = player.x, player.y targeting_item = None target_entity = None while True: fov_algorithm = 2 fov_light_walls = True fov_radius = 20 fov_recompute = True fov_map = initialize_fov(game_map) if fov_recompute: recompute_fov(fov_map, player.x, player.y, fov_radius, fov_light_walls, fov_algorithm) render_all(con, panel, entities, animator, player, game_map, fov_map, fov_recompute, message_log, constants['screen_width'], constants['screen_height'], constants['bar_width'], constants['panel_height'], constants['panel_y'], game_state, target_x, target_y, target_entity, turn_count) tcod.console_flush() clear_all(con, entities) player_turn_results = [] animator.advance_frame() # Handle Game State if game_state == GameStates.ENEMY_TURN: turn_count += 1 # Generate path map with all static tiles (ignore entities for now) path_map = generate_path_map(game_map, entities=None, player=player) for entity in entities: if entity.ai and entity.ai != Player: recompute_walkable(fov_map, game_map, entities, entity) entity_turn_results = entity.ai.take_turn( player, fov_map, game_map, entities, path_map) for entity_turn_result in entity_turn_results: message = entity_turn_result.get('message') dead_entity = entity_turn_result.get('dead') if message: message_log.add_message(message) if dead_entity: if dead_entity == player: message, game_state = kill_player(player) else: message = kill_entity(dead_entity) message_log.add_message(message) if game_state == GameStates.PLAYER_DEAD: break if game_state == GameStates.PLAYER_DEAD: break else: game_state = GameStates.PLAYER_TURN # Handle Events for event in tcod.event.wait(): if event.type == "QUIT": save_game(player, entities, animator, turn_count, game_map, message_log, game_state) raise SystemExit() if event.type == "KEYDOWN": action: [Action, None] = handle_keys(event.sym, game_state) if action is None: continue action_type: ActionType = action.action_type if action_type == ActionType.EXECUTE: if game_state == GameStates.TARGETING: item_use_results = player.body.use_selected_appendage( entities=entities, fov_map=fov_map, game_map=game_map, target_x=target_x, target_y=target_y) player_turn_results.extend(item_use_results) game_state = GameStates.ENEMY_TURN elif game_state == GameStates.LOOKING: look_results = [] looked_at_entities = get_entities_at_location( entities, target_x, target_y) if tcod.map_is_in_fov(fov_map, target_x, target_y): if looked_at_entities: for entity in looked_at_entities: look_results.extend( entity.get_description()) target_entity = entity else: if game_map.tiles[target_x][target_y].blocked: look_results.append({ 'message': Message("You stare at the wall.") }) else: look_results.append({ 'message': Message("You stare into empty space.") }) else: look_results.append({ 'message': Message("You can't see that far.") }) game_state = GameStates.PLAYER_TURN player_turn_results.extend(look_results) if action_type == ActionType.MOVEMENT: dx: int = action.kwargs.get("dx", 0) dy: int = action.kwargs.get("dy", 0) # Player Movement if game_state == GameStates.PLAYER_TURN: destination_x = player.x + dx destination_y = player.y + dy tile_results = game_map.tiles[destination_x][ destination_y].overlap_entity(player) player_turn_results.extend(tile_results) if not game_map.is_blocked(destination_x, destination_y): target_appendage = get_blocking_entities_at_location( entities, destination_x, destination_y) if target_appendage: if target_appendage.body: player_fighter = player.body.selected_appendage.fighter if player_fighter: target_entity = target_appendage game_state = GameStates.TARGET_APPENDAGE else: player_turn_results.append({ 'message': Message( "You cannot attack with your {0}." .format( player.body. selected_appendage.name), tcod.yellow) }) elif target_appendage.structure: structure_interact_results = target_appendage.structure.interact( player) player_turn_results.extend( structure_interact_results) else: player.move(dx, dy) else: player_turn_results.append({ 'message': Message("You slam yourself into the wall!", tcod.orange) }) if game_state != GameStates.TARGET_APPENDAGE: game_state = GameStates.ENEMY_TURN # Targeting elif game_state in (GameStates.TARGETING, GameStates.LOOKING): new_x = target_x + dx new_y = target_y + dy if player.distance(new_x, new_y) < targeting_radius: target_x = new_x target_y = new_y elif action_type == ActionType.GRAB: for entity in entities: if entity.item and entity.x == player.x and entity.y == player.y: pickup_result = player.body.grab_entity(entity) player_turn_results.extend(pickup_result) break else: player_turn_results.append({ 'message': Message('You grab at the air', tcod.yellow) }) game_state = GameStates.ENEMY_TURN elif action_type == ActionType.LOOK: game_state = GameStates.LOOKING target_x, target_y = player.x, player.y targeting_radius = 100 elif action_type == ActionType.WAIT: player_turn_results.append({ 'message': Message('You stare blankly into space', tcod.yellow) }) game_state = GameStates.ENEMY_TURN elif action_type == ActionType.CHOOSE_OPTION: option_index = action.kwargs.get("option_index", None) if game_state == GameStates.SWAP_APPENDAGE: if option_index < len(player.body.appendages): item = player.body.appendages[option_index] swap_results = player.body.select_appendage(item) player_turn_results.extend(swap_results) game_state = GameStates.PLAYER_TURN elif game_state == GameStates.TARGET_APPENDAGE: if option_index < len(target_entity.body.appendages): target_appendage = target_entity.body.appendages[ option_index] attack_results = player.body.selected_appendage.fighter.attack_appendage( target_appendage) player_turn_results.extend(attack_results) game_state = GameStates.ENEMY_TURN elif action_type == ActionType.INTERACT: for entity in entities: if entity.structure and entity.x == player.x and entity.y == player.y: interact_results = entity.structure.interact( player) player_turn_results.extend(interact_results) break else: if game_state == GameStates.PLAYER_TURN: activate_item_results = player.body.use_selected_appendage( fov_map=fov_map, game_map=game_map, entities=entities) if activate_item_results: player_turn_results.extend( activate_item_results) game_state = GameStates.ENEMY_TURN elif action_type == ActionType.DROP_INVENTORY_ITEM: grabber = player.body.selected_appendage.grabber if grabber: player_turn_results.extend(grabber.drop()) # game_state = GameStates.DROP_INVENTORY elif action_type == ActionType.SWAP_APPENDAGE: game_state = GameStates.SWAP_APPENDAGE elif action_type == ActionType.ESCAPE: if game_state == GameStates.TARGETING: game_state = GameStates.PLAYER_TURN elif game_state == GameStates.PLAYER_TURN: save_game(player, entities, animator, turn_count, game_map, message_log, game_state) main() elif action_type == ActionType.RESTART: main() # Process player turn results for player_turn_result in player_turn_results: message = player_turn_result.get('message') dead_entity = player_turn_result.get('dead') item_added = player_turn_result.get('item_added') item_consumed = player_turn_result.get('consumed') item_dropped = player_turn_result.get('item_dropped') targeting = player_turn_result.get('targeting') next_floor = player_turn_result.get('next_floor') if message: message_log.add_message(message) if dead_entity: if dead_entity == player: message, game_state = kill_player(player) else: message_log.add_message(kill_entity(dead_entity)) if item_added: entities.remove(item_added) game_state = GameStates.ENEMY_TURN if item_dropped: entities.append(item_dropped) game_state = GameStates.ENEMY_TURN if targeting: game_state = GameStates.TARGETING targeting_item = targeting targeting_radius = targeting.item.targeting_radius target_x = player.x target_y = player.y message_log.add_message( Message("You begin aiming the {0}.".format( targeting.name))) # TODO: Replace occurrences of add_message with player_turn_result approach # player_turn_results.append({'message': Message("You begin aiming the {0}.".format(targeting.name))}) if next_floor: entities = game_map.next_floor(player, constants) fov_map = initialize_fov(game_map) tcod.console_clear(con)
sorted_dists = sorted(dists, key=lambda t: t[1]) idx_k, dist_k = sorted_dists[k - 1] data_k = data[idx_k] plt.plot(data_k, 0, 'oC3') plt.plot([x, x], [0, estimate[i * 5]], '--C3') plt.plot(x, estimate[i * 5], '.C3') hyperbole_xs = [ x_val for x_val in xs if (x <= data_k and x_val <= data_k) or (x > data_k and x_val > data_k) ] hyperbole_ys = [ k / (2 * len(data) * abs(x_val - data_k)) for x_val in hyperbole_xs ] plt.plot(hyperbole_xs, hyperbole_ys, '--C3', alpha=0.5) yrange = max(estimate) - min(estimate) off = yrange * 0.1 plt.plot([data_k, data_k], [0, max(estimate) + off], '--C3', alpha=0.5) plt.ylim(0 - off, max(estimate) + off) plt.xlim(-0.5, 8.5) a = Animator(name='KNNEstimator', setup_handle=setup) a.setFrameCallback(frame_handle=frame, max_frame=160) a.run(clear=False, precompile=False)
plt.plot(data, [0] * len(data), 'xk') plt.axhline(0, color='k', linewidth=0.5) # calculate current interval x = i / 10 x1, x2 = x - h / 2, x + h / 2 # calculate relative width for visualization axis_to_data = plt.gca().transAxes + plt.gca().transData.inverted() bottom = axis_to_data.transform((0, 0))[1] top = -bottom # plot visualization lines plt.plot([x, x], [0, hist[i * 10]], '--C3') plt.plot([x1, x1], [bottom, top], 'C3', linewidth=0.5) plt.plot([x2, x2], [bottom, top], 'C3', linewidth=0.5) plt.plot([x1, x2], [0, 0], 'C3', linewidth=0.5) plt.fill_between([x1, x2], bottom, top, color='C3', alpha=0.3) plt.plot(x, hist[i * 10], '.C3') # highlight data in interval highlight_data = [d for d in data if x1 < d <= x2] plt.plot(highlight_data, [0] * len(highlight_data), 'oC3') plt.xlim(-0.5, 8.5) a = Animator(name='NaiveEstimator', setup_handle=setup) a.setFrameCallback(frame_handle=frame, max_frame=80) a.run(clear=False, precompile=True)
matplotlib.colors.to_rgba('r', alpha=0), matplotlib.colors.to_rgba('k', alpha=1) ]) plt.imshow(np.isclose(img, 1.0, atol=0.02), extent=(0, 10, 0, 10), cmap=colormap, origin='lower') plt.plot(*zip(*points), 'xb', markersize=8) plt.ylim(0, 10) plt.xlim(0, 10) plt.draw() def click(xdata, ydata, dblclick, button, **kwargs): global points if dblclick: points.append((xdata, ydata)) elif button == 3: if not points: return point_dists = [(p, dist(p, (xdata, ydata))) for p in points] point_dists.sort(key=lambda item: item[1]) points.remove(point_dists[0][0]) a = Animator(name='LOFAnimation', setup_handle=setup) a.setFrameCallback(frame_handle=frame, max_frame=3) a.setClickCallback(click) a.run(clear=True, precompile=False)
def __init__(self, x, y, display_size): super().__init__() self.burstAnimator = Animator() self.flowAnimator = Animator() self.Health = HeartsGroup(display_size) self.Stamina = Mana(display_size) self.x, self.y = x, y self.display_size = display_size path = os.getcwd() self.skins = { 'purple': { 'left_move': [ pygame.image.load(path + r'\img\spaceship\purpleship\left' + str(i) + '.png') for i in range(1, 3) ], 'right_move': [ pygame.image.load(path + r'\img\spaceship\purpleship\right' + str(i) + '.png') for i in range(1, 3) ], 'default': [ pygame.image.load(path + r'\img\spaceship\purpleship\space' + str(i) + '.png') for i in range(1, 3) ], 'color': 'purple' }, 'red': { 'left_move': [ pygame.image.load(path + r'\img\spaceship\redship\left' + str(i) + '.png') for i in range(1, 3) ], 'right_move': [ pygame.image.load(path + r'\img\spaceship\redship\right' + str(i) + '.png') for i in range(1, 3) ], 'default': [ pygame.image.load(path + r'\img\spaceship\redship\space' + str(i) + '.png') for i in range(1, 3) ], 'color': 'red' }, 'dark': { 'left_move': [ pygame.image.load(path + r'\img\spaceship\dark\left' + str(i) + '.png') for i in range(1, 3) ], 'right_move': [ pygame.image.load(path + r'\img\spaceship\dark\right' + str(i) + '.png') for i in range(1, 3) ], 'default': [ pygame.image.load(path + r'\img\spaceship\dark\space' + str(i) + '.png') for i in range(1, 3) ], 'color': 'dark' } } self.images = self.skins['purple'] self.acting_images = self.images['default'] self.rect = pygame.Rect(self.x, self.y, self.images['default'][0].get_width(), self.images['default'][0].get_height()) self.speed = {'accel': 1, 'finite': 8} self.DEFAULTXP = 10 self.XP = self.DEFAULTXP self.hitted_rects = [ pygame.Rect(self.rect.centerx - 10, self.rect.top + 15, 20, self.rect.bottom - self.rect.top - 25), pygame.Rect(self.rect.left + 10, self.rect.top + 65, self.rect.right - self.rect.left - 22, 45) ] self.last_strike = 0 self.last_skinChanging = 0
class Player(pygame.sprite.Sprite, HeartsGroup, Mana): def __init__(self, x, y, display_size): super().__init__() self.burstAnimator = Animator() self.flowAnimator = Animator() self.Health = HeartsGroup(display_size) self.Stamina = Mana(display_size) self.x, self.y = x, y self.display_size = display_size path = os.getcwd() self.skins = { 'purple': { 'left_move': [ pygame.image.load(path + r'\img\spaceship\purpleship\left' + str(i) + '.png') for i in range(1, 3) ], 'right_move': [ pygame.image.load(path + r'\img\spaceship\purpleship\right' + str(i) + '.png') for i in range(1, 3) ], 'default': [ pygame.image.load(path + r'\img\spaceship\purpleship\space' + str(i) + '.png') for i in range(1, 3) ], 'color': 'purple' }, 'red': { 'left_move': [ pygame.image.load(path + r'\img\spaceship\redship\left' + str(i) + '.png') for i in range(1, 3) ], 'right_move': [ pygame.image.load(path + r'\img\spaceship\redship\right' + str(i) + '.png') for i in range(1, 3) ], 'default': [ pygame.image.load(path + r'\img\spaceship\redship\space' + str(i) + '.png') for i in range(1, 3) ], 'color': 'red' }, 'dark': { 'left_move': [ pygame.image.load(path + r'\img\spaceship\dark\left' + str(i) + '.png') for i in range(1, 3) ], 'right_move': [ pygame.image.load(path + r'\img\spaceship\dark\right' + str(i) + '.png') for i in range(1, 3) ], 'default': [ pygame.image.load(path + r'\img\spaceship\dark\space' + str(i) + '.png') for i in range(1, 3) ], 'color': 'dark' } } self.images = self.skins['purple'] self.acting_images = self.images['default'] self.rect = pygame.Rect(self.x, self.y, self.images['default'][0].get_width(), self.images['default'][0].get_height()) self.speed = {'accel': 1, 'finite': 8} self.DEFAULTXP = 10 self.XP = self.DEFAULTXP self.hitted_rects = [ pygame.Rect(self.rect.centerx - 10, self.rect.top + 15, 20, self.rect.bottom - self.rect.top - 25), pygame.Rect(self.rect.left + 10, self.rect.top + 65, self.rect.right - self.rect.left - 22, 45) ] self.last_strike = 0 self.last_skinChanging = 0 def update(self, now, tick=80): self.hitted_rects = [ pygame.Rect( self.rect.centerx - self.rect.width * .2 // 2, self.rect.top, self.rect.width * 0.2, self.rect.bottom - self.rect.top - self.rect.height * 0.1), pygame.Rect(self.rect.left, self.rect.top + self.rect.height * 0.36, self.rect.right - self.rect.left, self.rect.height * 0.25) ] self.flowAnimator.updateAnimation(now, len(self.acting_images), tick, self.flowAnimator.IteralToNull) def draw(self, display): display.blit(self.acting_images[self.flowAnimator.getIteral], (self.rect.x, self.rect.y)) def Strike(self, now, object, image, func): if object: if now - self.last_strike > object.cooldawn: if self.Stamina.toSpend(object.stm): func(object(image, self.rect), ('all', 'player')) self.last_strike = now def hit(self, damage): self.XP -= damage self.Health.hit(self.XP, damage) return self.XP def heal(self, amount): if self.XP == self.DEFAULTXP: pass elif self.XP + amount <= self.DEFAULTXP: self.XP += amount self.Health.heal(self.XP, amount) else: # аааааа дублирование кода amount = (self.XP + amount) - self.DEFAULTXP self.XP += amount super().heal(self.XP, amount) def changeSkinPack(self, now): if now - self.last_skinChanging > 250: a = list(self.skins.keys()) index = a.index(self.images['color']) if index + 1 < len(a): pack_name = a[index + 1] else: pack_name = a[0] self.images = self.skins[pack_name] self.rect = pygame.Rect(self.rect.x, self.rect.y, self.images['default'][0].get_width(), self.images['default'][0].get_height()) self.last_skinChanging = now