Exemplo n.º 1
0
    def add_visited(self):
        """Adds an X in the square."""

        top_left = (self.rect.x, self.rect.y)
        top_right = (self.rect.x + get_width(), self.rect.y)
        bottom_left = (self.rect.x, self.rect.y + get_height())
        bottom_right = (self.rect.x + get_width(), self.rect.y + get_height())

        pygame.draw.line(self.image, COLOR_MAP['gray'], (0, 0),
                         (get_width(), get_height()))
        pygame.draw.line(self.image, COLOR_MAP['gray'], (get_width(), 0),
                         (0, get_height()))
Exemplo n.º 2
0
    def add_coordinates(self):
        """Adds coordinates to the square."""

        if self.board.num_rows == 1:
            message = '{}'.format(self.col - self.origin[1])
        elif self.board.num_cols == 1:
            message = '{}'.format(self.row - self.origin[0])
        else:
            message = '({},{})'.format(self.row - self.origin[0],
                                       self.col - self.origin[1])

        font = pygame.font.Font(None, min(get_width(), get_height()) // 3)
        text = font.render(message, True, COLOR_MAP['black'],
                           COLOR_MAP['white'])
        text_rect = text.get_rect(center=(get_width() // 2, get_height() // 2))
        self.image.blit(text, text_rect)
Exemplo n.º 3
0
    def __init__(self,
                 board,
                 row,
                 col,
                 num_colors,
                 init_color=0,
                 cycle_size=None,
                 color_map=None,
                 visited=False,
                 coordinates=False):
        """Initializes the Square.

        Arguments:
            board(Board): The Board the Square will be a part of.
            row(int): The number of the row where this Square is located.
            col(int): The number of the column where this Square is located.
            num_colors(int): The number of possible colors this Square can take on.
                Max is the number of colors in COLORS in constants.py.
            init_color(int): The initial color of this Square.
            cycle_size(int): The number of colors to cycle at the end of the list
                of colors. Must be less than or equal to num_colors.
                (None to cycle through all the colors.)
            color_map(dict): A map from each color to the next color in the sequence.
                If None, the default color_map will be initialized in
                the method initialize_color_map.
            visited(bool): True to add an X to indicate which squares have been visited.
            coordinates(bool): True to add coordinates to squares.
        """

        super(Square, self).__init__()

        self.board = board
        self.row = row
        self.col = col
        self.num_colors = num_colors
        self.color = init_color
        self.cycle_size = cycle_size
        self.visited = visited
        self.coordinates = coordinates
        self.origin = (self.board.flea_rows[0], self.board.flea_cols[0])

        # Initialize color map
        self.color_map = color_map if color_map is not None else self.initialize_color_map(
        )

        # Initialize square image
        self.image = pygame.Surface((get_width(), get_height()))
        self.image.fill(COLORS[self.color])
        self.rect = self.image.get_rect()
        self.rect.x = column_to_pixel(self.col)
        self.rect.y = row_to_pixel(self.row)

        if self.coordinates:
            self.add_coordinates()
Exemplo n.º 4
0
def column_to_pixel(col_num):
    """Converts a column number to a pixel number.

    Arguments:
        col_num(int): The number of the column.

    Returns:
        The pixel corresponding to the column.
    """

    return col_num * get_width() + MARGIN_SIDE // 2
Exemplo n.º 5
0
    def set_image(self):
        """Sets the image of the Flea and orients it correctly."""

        self.image = pygame.image.load('images/{}'.format(self.image_name))
        self.image = pygame.transform.scale(self.image,
                                            (get_width(), get_height()))

        # Rotate if necessary
        if self.direction == 'right':
            self.image = pygame.transform.rotate(self.image, 270)
        elif self.direction == 'down':
            self.image = pygame.transform.rotate(self.image, 180)
        elif self.direction == 'left':
            self.image = pygame.transform.rotate(self.image, 90)
Exemplo n.º 6
0
    def __init__(self, screen, board, font_type=None, font_size=50):
        """Initializes the Text.

        Arguments:
            screen(Surface): A pygame Surface representing the screen display.
            board(Board): The Board containing the squares and fleas.
            font_type(Font): The pygame font type to use.
            font_size(int): The font size to use.
        """
        self.screen = screen
        self.board = board
        self.font_type = font_type
        self.font_size = font_size

        self.screen_width = self.board.num_cols * get_width() + MARGIN_SIDE
        self.font = pygame.font.Font(self.font_type, self.font_size)

        self.top_area = pygame.Surface((self.screen_width, MARGIN_TOP))
        self.top_area.fill(COLOR_MAP['black'])
Exemplo n.º 7
0
def run_simulation(num_rows,
                   num_cols,
                   flea_class,
                   num_fleas,
                   flea_rows,
                   flea_cols,
                   init_directions,
                   square_colors,
                   image='flea.png',
                   visited=False,
                   coordinates=False,
                   hide_grid=False,
                   display_frequency=1,
                   print_frequency=1e5,
                   delay=0,
                   pause=False):
    """Runs a graphing fleas simulation.

    Arguments:
        num_rows(int): Number of rows in the board.
        num_cols(int): Number of columns in the board.
        flea_class(class): The class of the Fleas to create.
        num_fleas(int): The number of Fleas to create.
        flea_rows(list): The initial rows of the fleas.
            (None to start in the center vertically.
             Unspecified fleas will be placed randomly.)
        flea_cols(list): The initial columns of the fleas.
            (None to start in the center horizontally.
             Unspecified fleas will be placed randomly.)
        init_directions(list): The initial directions of the fleas.
            (Uspecified fleas will start facing up.)
        square_colors(list): Initial configuration of the colors of the squares.
            (list of list of ints representing square colors.)
            If None, all squares are initialized to color 0.
        image(str): Name of image file in images directory to use as the flea image.
        visited(bool): True to add an X to indicate which squares have been visited.
        coordinates(bool): True to add coordinates to squares.
        hide_grid(bool): True to hide the grid lines.
        display_frequency(int): How many steps between each update of the display.
            -1 to update manually upon pressing "d" key.
        print_frequency(int): How often to print the step to the terminal.
        delay(int): The number of milliseconds of delay between each step.
        pause(bool): True to start the game in a paused state.
    """

    pygame.init()

    window_size = (num_cols * get_width() + MARGIN_SIDE,
                   num_rows * get_height() + MARGIN_TOP + MARGIN_SIDE)
    screen = pygame.display.set_mode(window_size)
    pygame.display.set_caption('Graphing Fleas')

    board = Board(screen, num_rows, num_cols, flea_class, num_fleas, flea_rows,
                  flea_cols, init_directions, square_colors, image, visited,
                  coordinates, hide_grid)
    board.draw()

    text = Text(screen, board)
    text.update(format_message(0, pause))

    pygame.time.wait(500)

    # Main loop
    quit = False
    step = 0
    while True:
        advance = False

        # Check for key and mouse hits
        for event in pygame.event.get():
            # Check for quit
            if event.type == pygame.QUIT:
                quit = True

            elif event.type == pygame.KEYDOWN:
                # Check for pause
                if event.key == pygame.K_SPACE:
                    pause = not pause
                    text.update(format_message(step, pause))

                # Check for display
                elif event.key == pygame.K_d:
                    text.update(format_message(step, pause))
                    board.draw()

                # Check for advance
                elif event.key == pygame.K_RIGHT:
                    advance = True

            # Check for mouse click to set initial squares
            elif pause and event.type == pygame.MOUSEBUTTONUP:
                click_type = 'right' if event.button == 3 else 'left'
                mouse_pos = pygame.mouse.get_pos()
                clicked_squares = [
                    square for square in board.squares
                    if square.rect.collidepoint(mouse_pos)
                ]

                for square in clicked_squares:
                    if click_type == 'left':
                        square.next_color()
                    elif click_type == 'right':
                        square.previous_color()

                board.draw()

        # Break loop if quit
        if quit:
            break

        # Take step
        if not pause or advance:
            # Print step to terminal
            if step % print_frequency == 0:
                print(format_message(step, pause))

            # Update text displaying step number
            if display_frequency != -1 and step % display_frequency == 0:
                text.update(format_message(step, pause))

            # Rotate fleas
            board.rotate_fleas()

            if display_frequency != -1 and step % display_frequency == 0:
                board.draw()
                pygame.time.wait(delay)

            # Change square colors
            board.change_square_colors()

            # Move fleas
            board.move_fleas()

            if display_frequency != -1 and step % display_frequency == 0:
                board.draw()
                pygame.time.wait(delay)

            step += 1

    pygame.quit()