Ejemplo n.º 1
0
 def _game_restart(self):
     """
     Send the score to the server, and ask the player to continue
     """
     # Send the score to the server
     post_result = self.player.post_score()
     # Show the gameover screen
     game_continue = self.gameover.run(self.view.window, self.player,
                                       post_result)
     # If restarting the game
     if game_continue:
         # Recreate the snake and gameview
         self.snake = Snake()
         self.view = GameView()
         # Reset the score
         self.player.score = 0
         return True
     else:
         return False
Ejemplo n.º 2
0
 def on_game_started(self, event):
     module_logger.info("MainMenuController: on_game_started called.")
     model = GameModel(self.event_dispatcher)
     view = GameView(self.event_dispatcher)
     controllers = []
     game_controller = GameController(model, self.event_dispatcher)
     mouse_controller = MouseController(self.event_dispatcher)
     controllers.append(game_controller)
     controllers.append(mouse_controller)
     event = MVCChangeEvent(model, view, controllers)
     self.event_dispatcher.dispatch_event(event)
Ejemplo n.º 3
0
def main():
    from main_window import MainWindow
    from network import Network

    window = MainWindow(WIDTH, HEIGHT, "PyMMO")
    window.set_update_rate(1 / 1000)  # SET FPS
    menu_view = GameView()
    window.show_view(menu_view)
    network = Network(window)
    n = threading.Thread(target=network.action)
    n.daemon = True
    n.start()

    g = threading.Thread(target=arcade.run)
    g.daemon = True
    g.run()
Ejemplo n.º 4
0
def test_game_display():
    """1001 - Tests if the game display maze structure correctly"""
    maze_object = Maze("tests/test1.txt", "P")
    view = GameView(maze_object)
    assert "xPx  x" in view.display_maze()
Ejemplo n.º 5
0
class GameController():
    def __init__(self):
        """ Initializing what instances of classes """
        self.snake = Snake()
        self.view = GameView()
        self.apple = Apple()
        self.poison = Poison()
        self.player = Player()
        self.gameover = GameOverController()
        self.gamestart = GameStartController()

    def run(self):
        """ Run the game """
        clock = pygame.time.Clock()
        # Game is running
        running = True

        # Show start screen and get the player's name
        players_name = self.gamestart.run(self.view.window)
        if not players_name:
            running = False
        else:
            # assigning player name that's typed in to the player instance
            self.player.name = players_name

        while running:
            clock.tick(20)

            # Apple
            apples = pygame.sprite.Group()
            apples.add(self.apple)

            # Poison
            poisons = pygame.sprite.Group()
            poisons.add(self.poison)

            # Show the game screen
            self.view.display(self.snake, self.player.score)
            apples.draw(self.view.window)
            poisons.draw(self.view.window)

            # checking to see if snake has eaten apple
            eaten_apple = self.apple.apple_eaten(self.snake.group)
            # if apple has been eaten, generate new apple, make snake longer, and add a point to score
            if eaten_apple:
                self.snake.add_body()
                self.player.add_point()

            # checking to see if new apple overlaps static poison
            self.apple.overlap_poison_with_apple(self.poison, poisons)
            # checking to see if new apple is placed under snake body, if it is, generate new apple
            self.apple.overlap_snake_new_apple(self.snake.group)

            # checking to see if poison has been eaten by snake
            overlap_snake = self.poison.poison_eaten(self.snake.group)
            # if snake has eaten the poison
            if overlap_snake == True:
                # Ask the player to continue
                if not self._game_restart():
                    running = False

            # When the snake hits the wall
            if self.snake.check_hit_wall(self.view.window):
                # Ask the player to continue
                if not self._game_restart():
                    running = False

            # Catch the event
            for event in pygame.event.get():
                # If the window is closed
                if event.type == pygame.locals.QUIT:
                    running = False

                # If the direction keys are typed
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.locals.K_RIGHT:
                        self.snake.turn("Right")
                    elif event.key == pygame.locals.K_LEFT:
                        self.snake.turn("Left")
                    elif event.key == pygame.locals.K_UP:
                        self.snake.turn("Up")
                    elif event.key == pygame.locals.K_DOWN:
                        self.snake.turn("Down")

            # Move the snake
            self.snake.move()

            pygame.display.update()

    def _game_restart(self):
        """
        Send the score to the server, and ask the player to continue
        """
        # Send the score to the server
        post_result = self.player.post_score()
        # Show the gameover screen
        game_continue = self.gameover.run(self.view.window, self.player,
                                          post_result)
        # If restarting the game
        if game_continue:
            # Recreate the snake and gameview
            self.snake = Snake()
            self.view = GameView()
            # Reset the score
            self.player.score = 0
            return True
        else:
            return False
Ejemplo n.º 6
0
class GraphicEngine(Tk):
    def __init__(self, _graphic_engine_options=None):
        #Initialize game engine
        super().__init__()
        self.graphic_engine_on = True
        self.save_number = 0
        if _graphic_engine_options == None:
            self.options = self.loadGraphicEngineOptions()
        else:
            self.options = _graphic_engine_options
        self.textures, self.pil_textures = self.loadTextures()
        self.matrix = self.loadMatrix()
        self.protocol("WM_DELETE_WINDOW", self.onWindowClosing)
        MainMenuView(self, self.textures["ui"], self.options["x_window_size"],
                     self.options["y_window_size"])

    def onWindowClosing(self):
        #Closing window event
        try:
            while self.chunck_loader.is_map_generating == True:
                time.sleep(.1)
        except AttributeError:
            pass
        self.graphic_engine_on = False
        try:
            self.game_view.player.player_move_loop.join(1)
        except AttributeError:
            pass
        #Save game
        if not os.path.exists("saves"):
            os.mkdir("saves")
        if self.save_number != 0:
            with open("saves/save_{}.json".format(str(self.save_number)),
                      "w") as f:
                f.write(self.createDataToSave())
        self.destroy()

    def showWindow(self):
        self.geometry("{}x{}".format(self.options["x_window_size"],
                                     self.options["y_window_size"]))
        self.resizable(width=False, height=False)
        self.mainloop()

    def loadGraphicEngineOptions(self):
        #Load all graphic engine options
        def createOptions():
            #Generate default options
            options = {}
            #Init all options here
            options["x_window_size"] = 600
            options["y_window_size"] = 600
            options["progressive_map_generation"] = False
            options["texture_size"] = 25
            with open("ressources/configuration/graphic_engine.json",
                      "w") as file:
                file.write(json.dumps(options, indent=4))
            return options

        def loadOptions():
            #Load options from file
            with open("ressources/configuration/graphic_engine.json",
                      "r") as file:
                json_content = json.loads(file.read())
            return json_content

        #Execute good function in good case
        if not os.path.exists("ressources/configuration/graphic_engine.json"):
            return createOptions()
        else:
            return loadOptions()

    def loadMatrix(self):
        #Load matrix from json file
        map_name = "earth"
        with open("ressources/maps/{}.json".format(map_name), "r") as file:
            matrix = json.loads(file.read())
        return matrix

    def saveGraphicEngineConfiguration(self):
        #Save graphic engine configuration
        with open("ressources/configuration/graphic_engine.json", "w") as file:
            file.write(json.dumps(self.options, indent=4))

    def loadTextures(self):
        #Load textures from json file and png pictures
        with open("ressources/configuration/textures.json", "r") as file:
            json_content = json.loads(file.read())
        textures = {}
        pil_textures = {}
        size = self.options["texture_size"]
        for category in json_content.keys():
            textures[category] = {}
            pil_textures[category] = {}
            for content in json_content[category].keys():
                if json_content[category][content] != "NONE":
                    try:
                        textures[category][content] = PhotoImage(
                            file="ressources/textures/{}/{}".format(
                                category, json_content[category][content]))
                        pil_textures[category][content] = PIL.Image.open(
                            "ressources/textures/{}/{}".format(
                                category,
                                json_content[category][content])).resize(
                                    (size, size))
                    except TclError as e:
                        print(e)
        return textures, pil_textures

    def loadMap(self, options):
        x, y = options["player_x"], options["player_y"]
        self.screen_size = (self.options["x_window_size"],
                            self.options["y_window_size"])
        self.map_x = self.screen_size[0] * (-1.5) - x % self.screen_size[0]
        self.map_y = self.screen_size[1] * (-1.5) - y % self.screen_size[1]
        coef_x = x // self.screen_size[0] * self.screen_size[0]
        coef_y = y // self.screen_size[1] * self.screen_size[1]
        self.chunck_loader = ChunckLoader(x, y, self, self.pil_textures,
                                          self.matrix, (coef_x, coef_y))
        self.map = self.chunck_loader.loadMapFromCenter(x, y)
        self.player = Player(self.map_x, self.map_y, self.map, self, self,
                             self.textures["fight_ui"])
        threading.Thread(target=self.chunck_loader.startCheckLoop,
                         args=(self.player, )).start()
        self.physical_engine = PhysicalEngine(self.chunck_loader, self)
        self.physical_engine.start()
        self.displayMap()

    def displayMap(self):
        #Display map on screen
        try:
            self.game_view = GameView(self, self.options, self.player,
                                      self.textures, self.pil_textures,
                                      self.map)
            self.game_view.start()
        except AttributeError:
            return 1

    def createDataToSave(self):
        try:
            data_dict = {}
            if self.chunck_loader.x >= 0:
                if self.chunck_loader.y >= 0:
                    data_dict["player_x"] = self.chunck_loader.x % 15000
                    data_dict["player_y"] = self.chunck_loader.y % 15000
                else:
                    data_dict["player_x"] = self.chunck_loader.x % 15000
                    data_dict["player_y"] = self.chunck_loader.y % -15000
            elif self.chunck_loader.x <= 0:
                if self.chunck_loader.y >= 0:
                    data_dict["player_x"] = self.chunck_loader.x % -15000
                    data_dict["player_y"] = self.chunck_loader.y % 15000
                else:
                    data_dict["player_x"] = self.chunck_loader.x % -15000
                    data_dict["player_y"] = self.chunck_loader.y % -15000
            return json.dumps(data_dict)
        except AttributeError as e:
            return str(e)
Ejemplo n.º 7
0
def test_init_argument():
    """ 020A test if constructor recieves two argument """
    with pytest.raises(TypeError):
        maze = GameView()
    with pytest.raises(TypeError):
        maze = GameView([], "as", "as")
Ejemplo n.º 8
0
class GameController:
    '''Call functions from GameView to display the maze. 
       Call functions from Maze to get position of player, items, and exit
       Set up how player will move based on "↑,↓,←,→" command'''
    def __init__(self, maze, window):
        """Constructor for GameController class

        Args:
            maze (Maze): instance of the Maze class
            window (pygame.Surface): display the pygame surface
        """
        self._maze = maze
        self._game_over = False
        self._view = GameView(maze, window)
        self._keyboard_controller = KeyboardController()

    @property
    def player_current_location(self):
        """Getter for player's current location

        Returns:
            (tuple): current location of the player
        """
        return (self._maze.locations["P"][0] + self._maze.movements_player[0],
                self._maze.locations["P"][1] + self._maze.movements_player[1])

    def run(self):
        """This is the main function that calls the methods that control the game based on user's input (↑,↓,←,→,q)
            The pygame window closes when user presses 'q'.
        """
        user_input = self._keyboard_controller.get_action()

        if user_input in ("up", "left", "down", "right"):
            self.move_with_input(user_input)

        elif user_input == "q":
            pygame.quit()

        self._view.display_maze()

    def move_with_input(self, user_input):
        """Gets user input from KeyboardController, matches it with the movement dict
            and updates the player position accordingly.

        Args:
            user_input (str): key pressed by the user
        """
        movement = {
            "up": (-1, 0),
            "down": (1, 0),
            "left": (0, -1),
            "right": (0, 1)
        }

        # position will not change if user_input is not a recognized command
        shift = movement.get(user_input, (0, 0))

        x = shift[0]
        y = shift[1]
        self._maze.move_player(x, y)

        # pygame - set new position in the window
        player_row = self.player_current_location[0]
        player_col = self.player_current_location[1]

        self._maze.player.rect.x = player_col * GridSize.SIZE
        self._maze.player.rect.y = player_row * GridSize.SIZE

        self._view.display_maze()
        if self._maze.get_item():
            self._view.get_items(self._maze.player.backpack)
Ejemplo n.º 9
0
 def __init__(self):
     self.view = GameView()
     self.player_controller = PlayerController.get_instance()
     self.tournament_controller = TournamentController.get_instance()
Ejemplo n.º 10
0
class GameController:
    def __init__(self):
        self.view = GameView()
        self.player_controller = PlayerController.get_instance()
        self.tournament_controller = TournamentController.get_instance()

    def launch(self):
        self.player_controller.load_player_list()
        self.tournament_controller.load_tournament_list()
        while True:
            menu_choice = self.view.show_menu_options()
            if menu_choice == 1:
                self.launch_tournament()
            elif menu_choice == 2:
                while True:
                    self.player_controller.create_new_player()
                    choice = self.view.ask_validation(
                        'Créer un autre joueur ?')
                    self.player_controller.save_player_list()
                    if choice == "0":
                        continue
                    elif choice == "1":
                        break
            elif menu_choice == 3:
                self.player_controller.modify_player_elo()
            elif menu_choice == 4:
                self.generate_rapports()
            elif menu_choice == 5:
                self.exit()
                break

    def launch_tournament(self):
        tournament = self.tournament_controller.get_tournament()
        if tournament is not None:
            self.tournament_controller.save_tournament_list()
            while True:
                choice = self.view.ask_validation(
                    'Voulez vous lancer ce tournoi tout de suite ?')
                if choice == "0":
                    self.tournament_controller.run_tournament(tournament)
                    break
                elif choice == "1":
                    break
                else:
                    continue

    def generate_rapports(self):
        while True:
            choice, subchoice = self.view.display_rapport_menu()
            if choice == 0:
                self.player_controller.display_players(subchoice)
            elif choice == 1:
                self.tournament_controller.display_tournament_player(subchoice)
            elif choice == 2:
                self.tournament_controller.display_tournaments()
            elif choice == 3:
                self.tournament_controller.display_round_tournament()
            elif choice == 4:
                self.tournament_controller.display_match_tournament()
            elif choice == 5:
                break
            choice = self.view.ask_validation('Générer un autre rapport ?')
            if choice == "0":
                continue
            elif choice == "1":
                break

    def exit(self):
        self.player_controller.save_player_list()
        self.tournament_controller.save_tournament_list()