Exemplo n.º 1
0
    def __init__(self) -> None:
        """Create a new SceneManager and setup the static instance variable."""
        if (SceneManager.instance is None):
            SceneManager.instance = self

        # Tell pygame to center the window
        os.environ['SDL_VIDEO_CENTERED'] = '1'
        pygame.font.init()

        self._screen_size = (0, 0)
        self._is_fullscreen = True
        self._clock = pygame.time.Clock()
        self._scenes = [MainMenuScene, SettingsScene, GameScene]
        self._running = True

        self._setup_screen()

        # Always visible components
        self._root = Panel(self._screen.get_rect(),
                           style=Style(background_color=(255, 0, 0),
                                       border_width=0))

        self._fps_counter = Label(text="Calculating",
                                  rect=pygame.Rect(0, 25, 75, 20),
                                  style=Style(background_color=(255, 0, 0),
                                              border_width=0,
                                              primary_color=(255, 255, 255)),
                                  parent=self._root)
        self._rest_fps_counter_position()

        # Start the game
        self.change_scene(0)
        self._run_game_loop()
Exemplo n.º 2
0
    def set_parent(self, parent: Optional[Component]) -> None:
        """Set the component's parent. The default style is used if <parent>
        is None.
        """
        Panel.set_parent(self, parent)

        if (self._parent is None):
            return

        self.set_rect(self._parent.get_rect())
        size = self.get_rect().size

        title_rect = Rect(0, 0, 500, 70)
        title_rect.center = (size[0] / 2, size[1] / 2 - 200)

        self.clear_children()

        self.options_panel = VerticalPanel(rect=Rect(size[0] / 4, size[1] / 2,
                                                     size[0] / 2, size[1] / 4),
                                           expand_height=False,
                                           parent=self)

        self.title_label = Label(text="BATTLE SHIP!",
                                 rect=title_rect,
                                 style=Style(background_color=None,
                                             border_width=0,
                                             font=pygame.font.Font(
                                                 'freesansbold.ttf', 64),
                                             primary_color=(255, 255, 255)),
                                 parent=self)

        button_style = Style(primary_color=(255, 255, 255),
                             background_color=(128, 0, 0),
                             border_width=1,
                             border_color=(0, 0, 0),
                             font=pygame.font.Font('freesansbold.ttf', 32))

        self.cont_button = Button(rect=Rect(0, 0, 400, 40),
                                  on_click=self._cont_clicked,
                                  text="Continue",
                                  style=button_style,
                                  parent=self.options_panel)

        self.main_menu_button = Button(rect=Rect(0, 0, 400, 40),
                                       on_click=self._main_menu_clicked,
                                       text="Main menu",
                                       style=button_style,
                                       parent=self.options_panel)

        self.quit_button = Button(rect=Rect(0, 0, 400, 40),
                                  on_click=self._quit_clicked,
                                  text="Quit",
                                  style=button_style,
                                  parent=self.options_panel)
Exemplo n.º 3
0
    def read_ancestry_files(self, only_optimal_Ks=False):
        dataframes = []

        datasets = Dataset.all_datasets()
        Ks = self.available_Ks()
        panels = Panel.all_panels() + Panel.all_control_panels()

        for dataset, K, panel in product(datasets, Ks, panels):

            if only_optimal_Ks and self.optimal_Ks()[dataset.label] != K:
                continue

            # Results are sorted in directories named like DATASET_PANEL
            tag = "{}_{}".format(dataset.label, panel.label)
            basedir = join(ADMIXTURE_DIR, tag)

            if not isdir(basedir):
                continue

            # Read the .Q file for ratios of ancestry per sample
            fname = "{}.{}.Q".format(tag, K)
            ancestries_df = pd.read_csv(join(basedir, fname), sep="\s+",
                                        names=list(range(K)))

            # Read the .fam file for the sample IDs (they're in the same order)
            fname = "{}.fam".format(tag)
            samples = pd.read_csv(join(basedir, fname), sep="\s+", index_col=0,
                                  usecols=[0], names=["sample"])
            ancestries_df.index = samples.index

            # Add population data to the sample IDs
            samples_df = ThousandGenomes().all_samples()
            ancestries_df = samples_df.join(ancestries_df).dropna()

            continents_present = len(ancestries_df["superpopulation"].unique())
            if continents_present >= 3:
                self.infer_ancestral_components_from_samples_origin(ancestries_df)

            self.infer_ancestral_components_from_reference_pop(ancestries_df)

            # Arrange the hierarchical index
            ancestries_df.reset_index(inplace=True)
            ancestries_df["dataset"] = dataset.label
            ancestries_df["K"] = K
            ancestries_df["panel"] = panel.label
            ancestries_df.set_index(["dataset", "K", "panel"], inplace=True)

            dataframes.append(ancestries_df)

        return pd.concat(dataframes)
Exemplo n.º 4
0
    def _generate_distances_long_format(self):
        genome = Genome.regions()
        panel_analyser = PanelAnalyser()
        frames = [panel_analyser.snp_distances_per_chromosome(panel, genome)
                  for panel in Panel.all_panels()]
        distances = pd.concat(frames).T

        return pd.melt(distances)
Exemplo n.º 5
0
    def __init__(self, root: Panel):
        """Create a new MainMenuScene, creating the gui components to
        display.
        """
        size = root.get_rect().size
        title_rect = Rect(0, 0, 500, 70)
        title_rect.center = (size[0] / 2, size[1] / 2 - 200)

        # A panel for all the options
        options_panel = VerticalPanel(rect=Rect(size[0] / 4, size[1] / 2,
                                                size[0] / 2, size[1] / 4),
                                      expand_height=False,
                                      parent=root)

        # Title label
        Label(text="BATTLE SHIP!",
              rect=title_rect,
              style=Style(background_color=None,
                          border_width=0,
                          font=pygame.font.Font('freesansbold.ttf', 64),
                          primary_color=(255, 255, 255)),
              parent=root)

        # A style for all of the menu options
        button_style = Style(primary_color=(255, 255, 255),
                             background_color=(128, 0, 0),
                             border_width=1,
                             border_color=(0, 0, 0),
                             font=pygame.font.Font('freesansbold.ttf', 32))

        # Player vs Computer button
        Button(rect=Rect(0, 0, 400, 40),
               on_click=self._pvc_clicked,
               text="Player vs Computer",
               style=button_style,
               parent=options_panel)

        # Player vs Player button
        Button(rect=Rect(0, 0, 400, 40),
               on_click=self._pvp_clicked,
               text="Player vs Player",
               style=button_style,
               parent=options_panel)

        # Settings button
        Button(rect=Rect(0, 0, 400, 40),
               on_click=self._settings_clicked,
               text="Settings",
               style=button_style,
               parent=options_panel)

        # Quit button
        Button(rect=Rect(0, 0, 400, 40),
               on_click=self._quit_clicked,
               text="Quit",
               style=button_style,
               parent=options_panel)
Exemplo n.º 6
0
class SceneManager(object):
    """A Singleton that manages all scenes and tracks the appilcation's
    running state. The static instance variable can be used to access this
    object. This class must be created atleast once. The game loop will run
    until the application closes.

    === Private Attributes ===
        _screen_size:
            The size of the screen in pixels.
        _screen:
            The surface that represents the screen.
        _clock:
            A object that records the time inbettween calls to its tick
            function.
        _fps_counter:
            A label that displays the current framerate.
        _scenes:
            A list of all available scenes.
        _running:
            Whether or not the application is currently running.
        _is_fullscreen:
            Whether or not the application is currently in fullscreen mode.
        _active_scene_index:
            The currently active scene's index.
        _active_scene:
            The currently active scene.
    """
    instance = None

    _screen_size: Tuple[int, int]
    _screen: pygame.Surface
    _clock: pygame.time.Clock
    _fps_counter: Component
    _scenes: List
    _running: bool
    _is_fullscreen: bool
    _active_scene_index: int
    _active_scene: object

    def __init__(self) -> None:
        """Create a new SceneManager and setup the static instance variable."""
        if (SceneManager.instance is None):
            SceneManager.instance = self

        # Tell pygame to center the window
        os.environ['SDL_VIDEO_CENTERED'] = '1'
        pygame.font.init()

        self._screen_size = (0, 0)
        self._is_fullscreen = True
        self._clock = pygame.time.Clock()
        self._scenes = [MainMenuScene, SettingsScene, GameScene]
        self._running = True

        self._setup_screen()

        # Always visible components
        self._root = Panel(self._screen.get_rect(),
                           style=Style(background_color=(255, 0, 0),
                                       border_width=0))

        self._fps_counter = Label(text="Calculating",
                                  rect=pygame.Rect(0, 25, 75, 20),
                                  style=Style(background_color=(255, 0, 0),
                                              border_width=0,
                                              primary_color=(255, 255, 255)),
                                  parent=self._root)
        self._rest_fps_counter_position()

        # Start the game
        self.change_scene(0)
        self._run_game_loop()

    def set_screen_size(self, size: Tuple[int, int]) -> None:
        """Set the screen size. This method re-creates the active scene."""
        em.EventManager.instance.set_invalid()
        if (self._is_fullscreen):
            self._screen_size = (0, 0)
        else:
            self._screen_size = (max(size[0], MINIMUM_SCREEN_SIZE[0]),
                                 max(size[1], MINIMUM_SCREEN_SIZE[1]))
        self._setup_screen()
        self._root.set_rect(self._screen.get_rect())
        self._rest_fps_counter_position()
        self.change_scene(self._active_scene_index)

    def _setup_screen(self) -> None:
        """Create the screen object."""
        pygame.display.init()
        pygame.display.set_caption("Battleships")
        pygame.key.set_repeat(250, 50)

        flags = pygame.RESIZABLE
        if (self._is_fullscreen):
            flags |= pygame.FULLSCREEN

        self._screen = pygame.display.set_mode(self._screen_size, flags)
        self._screen_size = self._screen.get_rect().size

    def is_fullscreen(self) -> bool:
        """Whether or not the the application is in fullscreen mode."""
        return self._is_fullscreen

    def toggle_fullscreen(self) -> None:
        """Toggles the application mode between fullscreen and windowed."""
        self._is_fullscreen = not self._is_fullscreen
        pygame.display.quit()

        if (self._is_fullscreen):
            self.set_screen_size((0, 0))
        else:
            self.set_screen_size(DEFAULT_WINDOWED_MODE_SIZE)

    def _rest_fps_counter_position(self):
        """Sets the position of the fps counter."""
        fps_rect = self._fps_counter.get_rect()
        fps_rect.right = self._screen_size[0] - 25
        self._fps_counter.set_rect(fps_rect)

    def get_screen_size(self) -> Tuple[int, int]:
        """Get the size of the screen in pixels."""
        return self._screen_size

    def get_root(self) -> Component:
        """Get the topmost component."""
        return self._root

    def change_scene(self, scene_index: int) -> None:
        """Switch the current scene to the scene at index <scene_index>."""
        self._root.clear_children()
        self._active_scene_index = scene_index
        self._active_scene = self._scenes[scene_index](self._root)
        self._root.add_child(self._fps_counter)
        em.EventManager.instance.set_invalid()

    def quit_game(self) -> None:
        """Close the application."""
        self._running = False

    def _run_game_loop(self) -> None:
        """Run the game loop until the application closes"""
        while self._running:
            # Handle Events
            em.EventManager.instance.update()

            # Update
            self._root.update(self._clock.tick())  # Framerate Limit
            if (self._clock.get_fps() != float("inf")):
                self._fps_counter.set_text(str(int(self._clock.get_fps())))
            else:
                self._fps_counter.set_text("Infinity")

            # Draw
            changed = []
            self._root.render(self._screen, changed)
            pygame.display.update(changed)

        pygame.quit()
Exemplo n.º 7
0
    def __init__(self, root: Panel):
        """Create a new GameScene, creating the gui components to
        display and starting the game.
        """
        self._pause_menu = PauseMenuPanel(Rect(0, 0, 0, 0),
                                          style=Style(
                                              background_color=None,
                                              border_width=0,
                                              force_parent_redraw=True))

        # A style for all
        button_style = Style(background_color=(0, 255, 255),
                             primary_color=(0, 0, 0),
                             border_color=(0, 0, 0),
                             border_width=1)

        size = root.get_rect().size

        rect1 = Rect(size[0] / 8, size[1] / 8, size[0] * 3 / 8,
                     size[1] * 3 / 4)
        rect2 = Rect(size[0] / 2, size[1] / 8, size[0] * 3 / 8,
                     size[1] * 3 / 4)

        # The background water for the game
        self._background_water = BackgroundWater(rect=Rect(
            0, 0, size[0], size[1]),
                                                 parent=root)

        # A style for for the pause button
        pause_style = Style(
            background_color=None,
            force_parent_redraw=True,
            border_color=(0, 0, 0),
            border_width=2,
            background_image=pygame.image.load("images/pause.jpg"))

        # Pause Button
        Button(on_click=self._pause_clicked,
               rect=Rect(20, 20, 100, 100),
               style=pause_style,
               parent=self._background_water)

        # A style for player 1 grids
        player1_grid_style = Style(background_color=None,
                                   primary_color=(255, 0, 0, 100),
                                   secondary_color=(0, 0, 0, 200),
                                   border_color=(0, 0, 0),
                                   border_width=1,
                                   force_parent_redraw=True)

        # Create player 1 grids
        self._player1_grids = self._create_player_grids(
            rect1, player1_grid_style)

        # A style for player 2 grids
        player2_grid_style = Style(background_color=None,
                                   primary_color=(0, 255, 0, 50),
                                   secondary_color=(0, 0, 0, 200),
                                   border_color=(0, 0, 0),
                                   border_width=1,
                                   force_parent_redraw=True)

        # Create player 2 grids
        self._player2_grids = self._create_player_grids(
            rect2, player2_grid_style)

        # Setup observers
        player1 = GameManager.instance.get_player1()
        player2 = GameManager.instance.get_player2()
        player1.clear_observers()
        player2.clear_observers()
        player1.add_observer(self)
        player2.add_observer(self)

        # Start the game
        current_player = GameManager.instance.get_whos_turn()
        current_player.on_turn_started()
        current_player.notify_observers()