def event_loop(screen: pygame.Surface, tree: TMTree) -> None: """Respond to events (mouse clicks, key presses) and update the display. Note that the event loop is an *infinite loop*: it continually waits for the next event, determines the event's type, and then updates the state of the visualisation or the tree itself, updating the display if necessary. This loop ends only when the user closes the window. """ selected_node = None while True: # Wait for an event event = pygame.event.poll() if event.type == pygame.QUIT: return # get the hover position and the corresponding node hover_node = tree.get_tree_at_position(pygame.mouse.get_pos()) if event.type == pygame.MOUSEBUTTONUP: selected_node = \ _handle_click(event.button, event.pos, tree, selected_node) elif event.type == pygame.KEYUP and selected_node is not None: if event.key == pygame.K_UP: selected_node.change_size(0.01) tree.update_data_sizes() tree.update_rectangles((0, 0, WIDTH, HEIGHT - FONT_HEIGHT)) elif event.key == pygame.K_DOWN: selected_node.change_size(-0.01) tree.update_data_sizes() tree.update_rectangles((0, 0, WIDTH, HEIGHT - FONT_HEIGHT)) elif event.key == pygame.K_m: selected_node.move(hover_node) tree.update_data_sizes() tree.update_rectangles((0, 0, WIDTH, HEIGHT - FONT_HEIGHT)) elif event.key == pygame.K_e: selected_node.expand() elif event.key == pygame.K_a: selected_node.expand_all() elif event.key == pygame.K_c: selected_node.collapse() elif event.key == pygame.K_x: selected_node.collapse_all() # Update display render_display(screen, tree, selected_node, hover_node)
def _handle_click(button: int, pos: Tuple[int, int], tree: TMTree, old_selected_leaf: Optional[TMTree]) -> Optional[TMTree]: """Return the new selection after handling the mouse event. We need to use old_selected_leaf to handle the case when the selected leaf is left-clicked again. """ if button == 1: selected_leaf = tree.get_tree_at_position(pos) if selected_leaf is None: return old_selected_leaf elif selected_leaf is old_selected_leaf: return None else: return selected_leaf # right click or any other click does nothing else: return old_selected_leaf
def _handle_click(button: int, pos: Tuple[int, int], tree: TMTree, old_selected_leaf: Optional[TMTree]) -> Optional[TMTree]: """Return the new selection after handling the mouse event. We need to use old_selected_leaf to handle the case when the selected leaf is left-clicked again. """ # TODO: Delete the line below after completing Task 3 # left mouse click if button == 1: for subtree in tree._subtrees: print(subtree.rect) selected_leaf = tree.get_tree_at_position(pos) if selected_leaf is None: return old_selected_leaf elif selected_leaf is old_selected_leaf: return None else: return selected_leaf # right click or any other click does nothing else: return old_selected_leaf