def toggle_torch(self): # get closest unlit torch unlit_torch = arcade.get_closest_sprite(self.player, self.unlit_lights) dist = unlit_torch[1] unlit_torch = unlit_torch[0] # if torch is within action range, turn it on if dist < ACTION_RANGE: # create new lit torch to replace unlit torch new_torch = items.Torch(unlit_torch.center_x, unlit_torch.center_y, SCALE) # get rid of unlit torch unlit_torch.kill() # add torch to list of torches self.light_list.append(new_torch) # create a new light source and assign it to the torch light = Light(new_torch.center_x, new_torch.center_y, TORCH_RADIUS, TORCH_LIGHT, 'soft') self.torches[new_torch] = light self.light_layer.add(light) else: lit_torch = arcade.get_closest_sprite(self.player, self.light_list) dist = lit_torch[1] lit_torch = lit_torch[0] # self.torches.pop(lit_torch) # if there isnt an unlit torch in range, but there is a lit torch, turn it off if dist < ACTION_RANGE: # make new unlit torch new_torch = items.UnlitTorch(lit_torch.center_x, lit_torch.center_y, SCALE) # get rid of light source light = self.torches[lit_torch] self.light_layer.remove(light) # get rid of lit torch and add unlit torch lit_torch.kill() self.unlit_lights.append(new_torch)
def on_mouse_release(self, x: float, y: float, button: int, modifiers: int): # Who's turn is it # arcade.get_sprites_at_point() returns a python list of sprites at the cursors location if self.turn: piece = arcade.get_sprites_at_point((x, y), self.black_set) else: piece = arcade.get_sprites_at_point((x, y), self.white_set) # if there is no sprite at my mouse location if len(piece) == 0: # drop the sprite if self.piece_in_hand is not None: mat = arcade.get_closest_sprite(self.piece_in_hand, self.board) self.piece_in_hand.position = mat[0].position self.turn = not self.turn self.piece_in_hand = None return # if there is a sprite at my mouse location elif len(piece) == 1: # If piece at current position is a dif color then kill it if piece[0].bw != self.piece_in_hand.bw: mat = arcade.get_closest_sprite(self.piece_in_hand, self.board) self.piece_in_hand.position = mat[0].position self.turn = not self.turn self.piece_in_hand = None piece[0].kill()
def place_selected_checker(self, bear_off_roll=None): """Adds a checker to it's destination checker pile depending on it's state: moved, missplaced, bear off """ if self.checker_state == "valid_move": destination_point, dist = arcade.get_closest_sprite( self.selected_checker, self.point_list) placed_checker, used_roll, dead_checker = destination_point.add_checker( self.selected_checker) self.used_rolls.append(used_roll) if dead_checker is not None: self.bring_sprite_to_front(dead_checker) dead_checker.position = SCREEN_WIDTH / 2 + DEAD_CHECKER_PILE_DIRECTION[ dead_checker.colorr] * ( BOARD_WIDTH / 2 + PLAYER_STAT_WIDTH / 4), CHECKER_RADIUS + 5 + 50 * len( self.dead_checker_list[dead_checker.colorr]) if len(self.dead_checker_list[dead_checker.colorr]) > 0: self.dead_checker_list[ dead_checker.colorr][-1].is_selectable = False self.dead_checker_list[dead_checker.colorr].append( dead_checker) elif self.checker_state == "missplaced": self.selected_checker.place_back_to_origin(self.dead_checker_list) elif self.checker_state == "bear_off": self.used_rolls.append(bear_off_roll) self.checker_list.remove(self.selected_checker) self.nr_of_beared_off[self.turn] += 1
def on_mouse_release(self, x, y, button, key_modifiers): """ when mouse release """ # check the button check_mouse_release_for_buttons(x, y, self.button_list) # check the foods if len(self.held_foods) == 0: return else: # snap the food into dish # find the closest dish dish, distance = arcade.get_closest_sprite(self.held_foods[0], self.dish_list) reset_position = True # if we have contact between the food and the dish if arcade.check_for_collision(self.held_foods[0], dish): self.bite_sound.play() for i, dropped_food in enumerate(self.held_foods): dropped_food.position = dish.center_x, dish.center_y # success, don't reset reset_position = False if reset_position: # if we dropped the food somewhere else, return it to the original position for food_index, food in enumerate(self.held_foods): food.position = self.held_foods_original_location[ food_index] self.held_foods = []
def on_mouse_release(self, x: float, y: float, button: int, modifiers: int): """ Called when the user presses a mouse button. """ # If we don't have any cards, who cares if len(self.held_cards) == 0: return # Find the closest pile, in case we are in contact with more than one pile, distance = arcade.get_closest_sprite(self.held_cards[0], self.pile_mat_list) reset_position = True # See if we are in contact with the closest pile if arcade.check_for_collision(self.held_cards[0], pile): # For each held card, move it to the pile we dropped on for i, dropped_card in enumerate(self.held_cards): # Move cards to proper position dropped_card.position = pile.center_x, pile.center_y # Success, don't reset position of cards reset_position = False # Release on top play pile? And only one card held? if reset_position: # Where-ever we were dropped, it wasn't valid. Reset the each card's position # to its original spot. for pile_index, card in enumerate(self.held_cards): card.position = self.held_cards_original_position[pile_index] # We are no longer holding cards self.held_cards = []
def nearby_actor(self, engine): result = [] enemy_list = [ enemy for enemy in engine.cur_level.actor_sprites if Tag.enemy in enemy.tag ] e_len = len(enemy_list) for i in range(e_len): sprite = arcade.get_closest_sprite(engine.player, enemy_list)[0] if sprite.is_visible: result.append(sprite) enemy_list.remove(sprite) return result
def on_mouse_release(self, x: float, y: float, button: int, modifiers: int): """ Called when the user presses a mouse button. """ if self.game_state == "started" and self.winner is None and self.selected_checker_destination is None: if self.selected_checker is not None and self.selected_checker_destination is None: if x > SCREEN_WIDTH - PLAYER_STAT_WIDTH and self.ready_for_bearoff( 0) or x < PLAYER_STAT_WIDTH and self.ready_for_bearoff( 1): if self.is_valid_move(self.selected_checker, None, self.rolls, self.used_rolls): self.checker_state = "bear_off" self.selected_checker_origin = x, y self.selected_checker_destination = self.get_bear_off_destination( self.turn) else: self.selected_checker.point.arrange_pile( for_what="add") self.selected_checker_destination = self.selected_checker.point.get_checker_destination( self.selected_checker) self.selected_checker_origin = x, y self.checker_state = "missplaced" else: closest_point, dist = arcade.get_closest_sprite( self.selected_checker, self.point_list) if self.is_valid_move(self.selected_checker, closest_point, self.rolls, self.used_rolls): closest_point.arrange_pile(for_what="add") self.selected_checker_origin = x, y self.selected_checker_destination = closest_point.get_checker_destination( self.selected_checker) self.checker_state = "valid_move" # wrong move -> checker must be put back else: # checker is in play if self.selected_checker.point is not None: self.selected_checker.point.arrange_pile( for_what="add") self.selected_checker_destination = self.selected_checker.point.get_checker_destination( self.selected_checker) self.selected_checker_origin = x, y self.checker_state = "missplaced" # checker is dead else: self.selected_checker_destination = self.dead_checker_origin self.selected_checker_origin = x, y self.checker_state = "missplaced"
def check_for_food(ant): res = get_closest_sprite(ant, ant.arena.food_list) if not res: return -1 food, dist = res if dist > 10 * settings.SCALE: return -1 dx = food.center_x - ant.center_x dy = food.center_y - ant.center_y if dy > abs(dx): return 0 if dx > abs(dy): return -90 if -dx > abs(dy): return 90 return -1
def process(self, *args, **kwargs): [ self.targets.append(x[1][0]) for x in self.world.get_components(Renderable, Player) ] for m, (render, monster, vel) in self.world.get_components(Renderable, Monster, Velocity): target, dist = get_closest_sprite(render, self.targets) if 1000 >= dist >= 120: self.follow_target(render, target, vel) else: vel.x = 0 vel.y = 0 for i in range(len(self.targets)): self.targets.pop()
def on_mouse_release(self, x, y, button, modifiers): """Llamada cuando el usuario deja de hacer click en un boton """ #Si no tenemos cartas no ocurre nada if len(self.held_cards) == 0: return #Encontrar la pila de cartas mas cercana, en caso de que estemos en contacto con mas de una. pila, distancia = arcade.get_closest_sprite(self.held_cards[0], self.pile_mat_list) reiniciar_pos = True lcx, lcy = self.lista_cartas._get_center() #pcx, pcy = self.piles[PLAY_PILE]._get_center() if (pila.center_y == lcy): cardpile = self.lista_cartas else: cardpile = self.piles[PLAY_PILE] #Checamos si estamos en contacto con la pila mas cercana if arcade.check_for_collision(self.held_cards[0], pila): #Por carta, moverla en la pila que soltemos for i, carta_soltada in enumerate(self.held_cards): #Mover las cartas a la posicion adecuada. carta_soltada.position = pila.center_x, pila.center_y try: cardpile.append(carta_soltada) self.lista_cartas.pop( self.lista_cartas.index(carta_soltada)) pass except: cardpile.append(carta_soltada) self.piles[PLAYER_PILE].pop( self.piles[PLAYER_PILE].index(carta_soltada)) pass #Exito no hay que reiniciar la posicion de la carta reiniciar_pos = False if reiniciar_pos: #Donde soltamos no fue una posicion valida por lo tante regresamos al lugar inicial for pile_index, carta in enumerate(self.held_cards): carta.position = self.held_card_original_position[pile_index] #Ya no estamos sosteniendo ninguna carta self.held_cards = []
def loot_chest(self): # get closest chest sprite chest = arcade.get_closest_sprite(self.player, self.chests) dist = chest[1] chest = chest[0] # if the chest is within range, loot it and display the contents if dist < ACTION_RANGE: item = chest.loot if item: # set show text to true and create new dialogue object self.show_text = True self.text = Dialogue(self.player.collect(item),'\n', item.description, delay=3) chest.loot = None return True else: # loot can only be found once self.show_text = True self.text = Dialogue(f"You already found the loot in this chest.")
def move_player(game, step): player_asset = game.player_list[0] if (step == 'l'): player_asset.center_x -= player_asset.width elif (step == 'r'): player_asset.center_x += player_asset.width elif (step == 'u'): player_asset.center_y += player_asset.height else: player_asset.center_y -= player_asset.height closest_box = arcade.get_closest_sprite(player_asset, game.box_list) if (closest_box[1] < 0.1): if (step == 'l'): closest_box[0].center_x -= closest_box[0].width elif (step == 'r'): closest_box[0].center_x += closest_box[0].width elif (step == 'u'): closest_box[0].center_y += closest_box[0].height else: closest_box[0].center_y -= closest_box[0].height
def on_mouse_press(self, x, y, button, key_modifiers): """ User moves mouse """ # If you are not holding a piece and click it tries to pick up a piece: if not self.piece_held: pieces_near_click = arcade.get_sprites_at_point((x,y), self.piece_list) piece = (pieces_near_click[0] if pieces_near_click else None) if piece and piece.player == self.active_player: self.piece_held = piece self.set_mouse_visible(False) # Piece is now the 'cursor' and the mouse is distracting self.piece_held.pickup(self.spaces, self.en_passant_turn) # If you are already holding a piece when you click: else: # Snapping held chess piece to the closest board position destination, position = arcade.get_closest_sprite(self.piece_held, self.space_list) self.set_mouse_visible(True) # If the attempted movement is not legal, this returns it to the originating location) if self.get_space(destination.space_coord()) not in self.piece_held.move_list: self.piece_held.return_to_previous_position() elif destination.occupant and destination.occupant.player == self.active_player: self.piece_held.return_to_previous_position() else: # No longer an en_passant_turn (if it ever was) self.en_passant_turn = False # The capture function manages all legal placements; it can be considered the end of a turn. capture(self, self.piece_held, destination) # 'Lets Go' of the piece to complete the click and reset the board. for space in self.piece_held.move_list: space.return_original_color() self.piece_held.move_list = [] self.piece_held.previous_position = None self.piece_held = None
def on_update(self, delta_time: float): """Здесь мы обновляем параметры и перемещаем спрайты. Этот метод вызывается автоматически с частотой 60 кадров в секунду""" if self.timer > 0: self.sprite.update() # for coin in self.coins_list: # if arcade.check_for_collision(self.sprite, coin): # self.coins_list.remove(coin) # self.score += 1 collisions = arcade.check_for_collision_with_list(self.sprite, self.coins_list) for coin in collisions: self.coins_list.remove(coin) self.score += 1 collide_distance = arcade.get_closest_sprite(self.sprite, self.big_coins_list) if collide_distance is not None: sprite, distance = collide_distance # print(distance) if distance < 150: sprite.remove_from_sprite_lists() # чтобы не перепутать списки, удаляем из всех списков
def on_mouse_release(self, x: float, y: float, button: int, modifiers: int): """ Called when the user presses a mouse button. """ if self.held_gate == None: return node, distance = arcade.get_closest_sprite(self.held_gate, self.nodes_list) reset_position = True if arcade.check_for_collision(self.held_gate, node): if (not node.gate): # update circuit in qiskit here if (self.held_gate.node): self.held_gate.node.gate = None self.held_gate.position = node.center_x, node.center_y self.held_gate.node = node node.gate = self.held_gate reset_position = False if reset_position: self.reset_gate(self.held_gate) self.held_gate = None self.circuit.update_results()
def on_mouse_release(self, x: float, y: float, button: int, modifiers: int): """ Called when the user presses a mouse button. """ # Release all buttons buttons = arcade.get_sprites_at_point((x, y), self.buttons) if len(buttons) > 0: button = buttons[-1] if button.isButtonPressed: if button.task == "Take Cards": self.takeCards(self.Attack == 1, self.Attack == 0) # this is in revers - the defender may take cards elif button.task == "Done": if self.isAllAttacksCompleted(): self.newTurn() elif button.task == "Start Over": self.setup() elif button.task == "Help": self.page = PAGE_HELP elif button.task == "Resume": self.page = PAGE_HELP HelpButtons = arcade.get_sprites_at_point((x, y), self.Help_buttons) if len(HelpButtons) > 0: button = HelpButtons[-1] if button.isButtonPressed: if button.task == "Resume": self.page = PAGE_GAME for button in self.buttons: button.buttonRelease() # If we don't have any cards, who cares if len(self.held_cards) == 0: return # Find the closest pile, in case we are in contact with more than one pile, distance = arcade.get_closest_sprite(self.held_cards[0], self.pile_mat_list) reset_position = True # See if we are in contact with the closest pile if arcade.check_for_collision(self.held_cards[0], pile): # What pile is it? pile_index = self.pile_mat_list.index(pile) # Is it the same pile we came from? if pile_index == self.get_pile_for_card(self.held_cards[0]): # If so, who cares. We'll just reset our position. pass # Is it on a middle play pile? elif self.pile_mat_list[pile_index].game: reset_position = self.checkTheMove(pile,pile_index) if reset_position: # Where-ever we were dropped, it wasn't valid. Reset the each card's position # to its original spot. for pile_index, card in enumerate(self.held_cards): card.position = self.held_cards_original_position[pile_index] # We are no longer holding cards self.held_cards = [] if not reset_position: self.newMove()
def on_update(self, delta_time): """ Movement and game logic """ # update frame count self.frames += 1 if self.frames % 60 == 0: self.time += 1 # Move the player with the physics engine self.physics_engine.update() if self.physics_engine.is_on_ladder(): if 'W' in self.keys_pressed and 'SP' not in self.keys_pressed: self.player_sprite.change_y = PLAYER_MOVEMENT_SPEED elif 'S' in self.keys_pressed and 'SP' not in self.keys_pressed: self.player_sprite.change_y = -PLAYER_MOVEMENT_SPEED elif 'SP' not in self.keys_pressed: self.player_sprite.change_y = 0 else: self.player_sprite.change_y = max( self.player_sprite.change_y - GRAVITY, 0) if len(self.moving_platforms_list): platform, distance = arcade.get_closest_sprite( self.player_sprite, self.moving_platforms_list) if (platform.center_y + TILE_WIDTH / 2 > self.player_sprite.center_y - TILE_WIDTH > platform.center_y and platform.center_x - (3 * TILE_WIDTH) / 2 < self.player_sprite.center_x < platform.center_x + (3 * TILE_WIDTH) / 2): if self.level < 4: self.jump_remaining = 1 else: self.jump_remaining = 2 if self.physics_engine.is_on_ladder() or self.physics_engine.can_jump( ): if self.level < 4: self.jump_remaining = 1 else: self.jump_remaining = 2 self.wall_list.update() for wall in self.wall_list: if wall.boundary_right and wall.right > wall.boundary_right and wall.change_x > 0: wall.change_x *= -1 if wall.boundary_left and wall.left < wall.boundary_left and wall.change_x < 0: wall.change_x *= -1 if wall.boundary_top and wall.top > wall.boundary_top and wall.change_y > 0: wall.change_y *= -1 if wall.boundary_bottom and wall.bottom < wall.boundary_bottom and wall.change_y < 0: wall.change_y *= -1 # See if we hit any coins coin_hit_list = arcade.check_for_collision_with_list( self.player_sprite, self.coin_list) self.player_sprite.update_animation(self.physics_engine.is_on_ladder()) # if on_moving_platform: # if self.player_sprite.change_x < moving_hit_list[0].change_x: # self.player_sprite.change_x += moving_hit_list[0].change_x # if self.player_sprite.change_y < moving_hit_list[0].change_y: # self.player_sprite.change_y += moving_hit_list[0].change_y # Check for collision with hazards if arcade.check_for_collision_with_list(self.player_sprite, self.hazards_list): arcade.play_sound(self.game_over_sound, volume=.4) self.setup(self.level) # Loop through each coin we hit (if any) and remove it for coin in coin_hit_list: # Remove the coin coin.remove_from_sprite_lists() # Play a sound arcade.play_sound(self.collect_coin_sound, volume=.6) # Add one to the score self.score += 1 # if self.score == 13: if not len(self.coin_list): game_view = InstructionView(self.level + 1, self.time) self.window.show_view(game_view) return # --- Manage Scrolling --- # Track if we need to change the viewport changed = False # Scroll left left_boundary = self.view_left + LEFT_VIEWPORT_MARGIN if self.player_sprite.left < left_boundary: self.view_left -= left_boundary - self.player_sprite.left changed = True # Scroll right right_boundary = self.view_left + SCREEN_WIDTH - RIGHT_VIEWPORT_MARGIN if self.player_sprite.right > right_boundary: self.view_left += self.player_sprite.right - right_boundary changed = True # Scroll up top_boundary = self.view_bottom + SCREEN_HEIGHT - TOP_VIEWPORT_MARGIN if self.player_sprite.top > top_boundary: self.view_bottom += self.player_sprite.top - top_boundary changed = True # Scroll down bottom_boundary = self.view_bottom + BOTTOM_VIEWPORT_MARGIN if self.player_sprite.bottom < bottom_boundary: self.view_bottom -= bottom_boundary - self.player_sprite.bottom changed = True if changed: # Only scroll to integers. Otherwise we end up with pixels that # don't line up on the screen self.view_bottom = int(self.view_bottom) self.view_left = int(self.view_left) # Do the scrolling arcade.set_viewport(self.view_left, SCREEN_WIDTH + self.view_left, self.view_bottom, SCREEN_HEIGHT + self.view_bottom)
def update(self, delta_time): if self.is_dead: print("CANCEELED") return """ Movement and game logic """ # Stop the player from leaving the screen if self.player_sprite.center_y > 600: self.player_sprite.change_y = 0 self.player_sprite.center_y = 599 elif self.player_sprite.center_y < 25: self.player_sprite.change_y = 0 self.player_sprite.center_y = 26 # record the player's last location to get their true speed self.player_last_x = self.player_sprite.center_x # Move the player with the physics engine self.physics_engine.update() # get player's speed and update backgrounds player_speed = self.player_sprite.center_x - self.player_last_x self.bg_list.update(player_speed, self.player_sprite.center_x) # --- Manage Scrolling --- changed = False # Scroll left left_boundary = self.view_left + LEFT_VIEWPORT_MARGIN if self.player_sprite.left < left_boundary: self.view_left -= left_boundary - self.player_sprite.left changed = True # Scroll right right_boundary = self.view_left + SCREEN_WIDTH - RIGHT_VIEWPORT_MARGIN if self.player_sprite.right > right_boundary: self.view_left += self.player_sprite.right - right_boundary changed = True if changed: # Only scroll to integers. Otherwise we end up with pixels that # don't line up on the screen self.view_bottom = int(self.view_bottom) self.view_left = int(self.view_left) # Do the scrolling arcade.set_viewport(self.view_left, SCREEN_WIDTH + self.view_left, self.view_bottom, SCREEN_HEIGHT + self.view_bottom) for wall in self.wall_list: if wall.center_x < self.player_sprite.center_x - 500: wall.center_x += 1250 # if self.won: # arcade.play_sound(self.courage_sound) # time.sleep(1) # new_view = game_won.GameWon() # self.window.show_view(new_view) # if wall.center_x < self.player_sprite.center_x - 500: # wall.center_x += 2500 # manage threads for i in range(len(self.sky_scraper_sprites)): ss: SkyScraper = self.sky_scraper_sprites[i] if not ss.thread.is_alive() and not ss.loaded: ss.load_image() current_equation = self.equations[0] closest_sprite: Sprite = arcade.get_closest_sprite( self.player_sprite, self.answer_sprites)[0] if type(closest_sprite ) == Answer and self.player_sprite.left > closest_sprite.left: answer: Answer = closest_sprite # player hit the correct answer if answer.get_number() == current_equation.answer: self.score += 1 # Reset the equation and answers self.get_new_equation() current_equation = self.equations[0] else: self.kill_bird() # move answers values = current_equation.answers for i in range(len(self.answer_sprites)): a: Answer = self.answer_sprites[i] a.center_x += 1250 value = values[i] a.set_number(value) a.is_correct = current_equation.answer == value if len(self.sky_scraper_sprites) == 3: sprite: SkyScraper = self.sky_scraper_sprites.pop(0) center = (sprite.center_x, sprite.center_y) print("reloading", [e.answers for e in self.equations]) new_sprite = SkyScraper(self.equations[1].answers, id=self.wall_counter) self.wall_counter += 1 new_sprite.center_x = center[0] new_sprite.center_y = center[1] new_sprite.move_forward(how_many=3) self.sky_scraper_sprites.append(new_sprite) # bird death detection if player_speed == 0: print("Bird hit the wall") self.kill_bird()
def on_key_press(self, key, modifiers): """ Called whenever a key is pressed. """ # Logic for assignment of keys and movement directions if not self.pick_tree_state and not self.in_tree_state: if key == arcade.key.UP: self.player_sprite.change_y = self.player_speed elif key == arcade.key.DOWN: self.player_sprite.change_y = -self.player_speed elif key == arcade.key.LEFT: self.player_sprite.change_x = -self.player_speed elif key == arcade.key.RIGHT: self.player_sprite.change_x = self.player_speed elif self.pick_tree_state: # Pick a tree if self.trees_in_range: # There is a tree within range self.picked_tree_index = ( self.picked_tree_index + 1 ) % len(self.trees_in_range) if key == arcade.key.SPACE: self.pick_tree_state = True if self.trees_in_range: self.picked_tree_index = 0 self.nearest, distance = arcade.get_closest_sprite( self.player_sprite, self.wall_list ) if distance < 100: self.wall_list.remove(self.nearest) tree_collision = True self.in_tree_state = True if key == arcade.key.KEY_1: self.picking_free_space = True pi, pj = get_sprite_ij(self.player_sprite) possible = [] for i, j in [(pi + 1, pj), (pi, pj + 1), (pi - 1, pj), (pi, pj - 1)]: if not((i, j) in self.tree_placement or (i, j) in wall_coordinates): possible.append((i, j)) for i, j in possible: free_space = arcade.Sprite( "images/chick.png", SPRITE_SCALING_PLAYER ) x, y = get_xy(i, j) free_space.center_x = x free_space.center_y = y self.available_spaces_list.append(free_space) # Allow player to use arrow keys if they are picking # a free space if self.picking_free_space and key == arcade.key.UP: self.in_tree_state = False elif self.picking_free_space and key == arcade.key.DOWN: self.in_tree_state = False elif self.picking_free_space and key == arcade.key.LEFT: self.in_tree_state = False elif self.picking_free_space and key == arcade.key.RIGHT: self.in_tree_state = False
def on_mouse_release(self, x: float, y: float, button: int, modifiers: int): """ Called when the user presses a mouse button """ enemy_colour = 'B' if self.turn == 'W' else 'W' enemy_pieces = self.black_piece_list if self.turn == 'W' else self.white_piece_list # Check if a piece was held if not self.held_piece: return acceptable_moves = self.held_piece.move_list acceptable_attacks = self.held_piece.attack_list # Find the closest tile in case of overlap tile, distance = arcade.get_closest_sprite(self.held_piece, self.tile_list) # create reset variable with default True reset_position = True if arcade.check_for_collision(self.held_piece, tile): tile_index = self.tile_list.index(tile) tile_index_y = 7 - int(tile_index // 8) tile_index_x = tile_index % 8 new_tile = self.tiles[tile_index_y][tile_index_x] old_tile = self.get_tile_for_piece(self.held_piece, self.tiles) if old_tile == (tile_index_y, tile_index_x): #TODO: build highlighting pass elif (tile_index_y, tile_index_x) not in acceptable_moves and ( tile_index_y, tile_index_x) not in acceptable_attacks: pass elif new_tile in enemy_pieces: self.move_sequence.append( (self.held_piece, self.held_piece_origin, old_tile, (tile_index_y, tile_index_x), new_tile, new_tile.position, (tile_index_y, tile_index_x), None)) if enemy_colour == 'W': if self.white_pieces_captured < 8: new_tile.position = START_X+SQUARE_WIDTH*8, \ START_Y+(SQUARE_HEIGHT*self.white_pieces_captured) else: new_tile.position = START_X+SQUARE_WIDTH*9, \ START_Y+(SQUARE_HEIGHT*(self.white_pieces_captured-8)) self.white_pieces_captured += 1 else: if self.black_pieces_captured < 8: new_tile.position = START_X+SQUARE_WIDTH*10, \ START_Y+(SQUARE_HEIGHT*self.black_pieces_captured) else: new_tile.position = START_X+SQUARE_WIDTH*11, \ START_Y+(SQUARE_HEIGHT*(self.black_pieces_captured-8)) self.black_pieces_captured += 1 self.held_piece.position = tile.center_x, \ tile.center_y self.tiles[tile_index_y][tile_index_x] = self.held_piece self.held_piece.move_counter += 1 self.turn = 'W' if self.turn == 'B' else 'B' self.tiles[old_tile[0]][old_tile[1]] = None reset_position = False elif self.held_piece.piece == 'King' and (abs(old_tile[1] - tile_index_x)) > 1: self.tiles[tile_index_y][tile_index_x] = self.held_piece self.held_piece.position = tile.center_x, \ tile.center_y if tile_index_x > old_tile[1]: castled_rook = self.tiles[tile_index_y][tile_index_x + 1] old_pos = castled_rook.position rook_old_shift = 1 rook_new_shift = -1 self.tiles[tile_index_y][tile_index_x - 1] = castled_rook self.tiles[tile_index_y][tile_index_x + 1] = None castled_rook.position = tile.center_x-SQUARE_WIDTH, \ tile.center_y else: castled_rook = self.tiles[tile_index_y][tile_index_x - 2] old_pos = castled_rook.position rook_old_shift = -2 rook_new_shift = 1 self.tiles[tile_index_y][tile_index_x + 1] = castled_rook self.tiles[tile_index_y][tile_index_x - 2] = None castled_rook.position = tile.center_x+SQUARE_WIDTH, \ tile.center_y self.move_sequence.append( (self.held_piece, self.held_piece_origin, old_tile, (tile_index_y, tile_index_x), castled_rook, old_pos, (tile_index_y, tile_index_x + rook_old_shift), (tile_index_y, tile_index_x + rook_new_shift))) self.held_piece.move_counter += 1 self.turn = 'W' if self.turn == 'B' else 'B' self.tiles[old_tile[0]][old_tile[1]] = None reset_position = False elif new_tile is None: self.tiles[tile_index_y][tile_index_x] = self.held_piece self.held_piece.position = tile.center_x, \ tile.center_y self.move_sequence.append( (self.held_piece, self.held_piece_origin, old_tile, (tile_index_y, tile_index_x))) self.turn = 'W' if self.turn == 'B' else 'B' self.tiles[old_tile[0]][old_tile[1]] = None self.held_piece.move_counter += 1 reset_position = False if self.held_piece.piece == 'Pawn' and (tile_index_y == 0 or tile_index_y == 7): new_queen = self.held_piece.promote(self) self.move_sequence.append( ('P', self.held_piece, self.held_piece_origin, new_queen, (tile_index_y, tile_index_x))) if reset_position: self.held_piece.position = self.held_piece_origin self.held_piece = None self.end_turn()
def on_mouse_release(self, x: float, y: float, button: int, modifiers: int): """ Called when the user presses a mouse button. """ # If we don't have any cards, who cares if len(self.held_cards) == 0: return # Find the closest pile, in case we are in contact with more than one pile, distance = arcade.get_closest_sprite( self.held_cards[0], self.pile_mat_list) reset_position = True # See if we are in contact with the closest pile if arcade.check_for_collision(self.held_cards[0], pile): # What pile is it? pile_index = self.pile_mat_list.index(pile) # Is it the same pile we came from? if pile_index == self.get_pile_for_card(self.held_cards[0]): # If so, who cares. We'll just reset our position. pass # Is it on a middle play pile? elif PLAY_PILE_1 <= pile_index <= PLAY_PILE_7: # Are there already cards there? if len(self.piles[pile_index]) > 0: # Move cards to proper position top_card = self.piles[pile_index][-1] for i, dropped_card in enumerate(self.held_cards): dropped_card.position = top_card.center_x, \ top_card.center_y - CARD_VERTICAL_OFFSET * (i + 1) else: # Are there no cards in the middle play pile? for i, dropped_card in enumerate(self.held_cards): # Move cards to proper position dropped_card.position = pile.center_x, \ pile.center_y - CARD_VERTICAL_OFFSET * i for card in self.held_cards: # Cards are in the right position, but we need to move # them to the right list self.move_card_to_new_pile(card, pile_index) # Success, don't reset position of cards reset_position = False # Release on top play pile? And only one card held? elif TOP_PILE_1 <= pile_index <= TOP_PILE_4 and \ len(self.held_cards) == 1: # Move position of card to pile self.held_cards[0].position = pile.position # Move card to card list for card in self.held_cards: self.move_card_to_new_pile(card, pile_index) reset_position = False if reset_position: # Where-ever we were dropped, it wasn't valid. Reset the each # card's position to its original spot. for pile_index, card in enumerate(self.held_cards): card.position = self.held_cards_original_position[pile_index] # We are no longer holding cards self.held_cards = []