Esempio n. 1
0
class Application:
    @property
    def screenWidth(self):
        return self.__screenWidth

    @property
    def screenHeight(self):
        return self.__screenHeight

    @property
    def resolution(self):
        return (self.screenWidth, self.screenHeight)

    @property
    def display(self):
        return self.__display

    @property
    def caption(self):
        return self.__caption

    def __init__(self):
        self.__screenWidth = config["game"]["width"]
        self.__screenHeight = config["game"]["height"]
        self.__caption = config["game"]["caption"]
        display = pygame.display.set_mode(self.resolution)
        pygame.display.set_caption(self.caption)
        self.__display = display

    def run(self):
        self.game = Game(self)
        self.menu = Menu(self)
        self.menu.run()
Esempio n. 2
0
def main():
    menu = Menu()
    menu.run()
    if not menu.config.start_game:
        exit(0)
    game = Game(config=menu.config)
    new_game = game.run()
    if new_game:
        main()
Esempio n. 3
0
    def run():

        pygame.init()
        pygame.display.set_caption('Tetris')
        switch_status = 'menu'

        while True:
            if switch_status == 'menu':
                menu = Menu()
                switch_status = menu.run()
            elif switch_status == 'single player':
                single_player = SinglePlayer()
                switch_status = single_player.run()
            elif switch_status == 'multi player':
                multi_player = MultiPlayer()
                switch_status = multi_player.run()
Esempio n. 4
0
class Client:
    """
    Client Class
    """
    def __init__(self):
        pg.init()
        pg.mixer.init()
        self.character = self.dt = None
        self.clock = pg.time.Clock()
        with open("settings.yaml") as f:
            self.settings = yaml.load(f)
            f.close()
        self.init_game_window()
        pg.display.set_caption(self.settings["gen"]["title"])
        pg.key.set_repeat(100, 100)
        self.data = Loader(self.settings)
        self.data.build_path()
        self.data.load_data()
        self.hp = self.max_hp = self.settings["player"]["hp"]
        pg.mouse.set_visible(False)
        pg.display.set_icon(self.data.undervoid_icon)

    def init_game_window(self):
        """
        Initializes a centered game window either with windowed resolution or fullscreen.
        """
        environ["SDL_VIDEO_CENTERED"] = "1"
        if self.settings["gen"]["fullscreen"] == "on":
            self.settings["gen"]["width"], self.settings["gen"]["height"] = (
                pg.display.Info().current_w,
                pg.display.Info().current_h,
            )
            self.screen = pg.display.set_mode((0, 0), pg.FULLSCREEN)
        else:
            self.settings["gen"]["width"] = self.settings["gen"]["winres"][
                "width"]
            self.settings["gen"]["height"] = self.settings["gen"]["winres"][
                "height"]
            self.screen = pg.display.set_mode((self.settings["gen"]["width"],
                                               self.settings["gen"]["height"]))

    def draw(self, game):
        """
        Draws the map and all sprites.
        Draws Player health and gold coins.
        """
        pg.display.set_caption("Undervoid")
        self.screen.fill(game.bg_color)
        self.screen.blit(game.map_img, game.camera.apply_rect(game.map_rect))
        # self.draw_grid()
        for sprite in game.sprite_grouping.all_sprites:
            if isinstance(sprite, Mob) and sprite.hp < sprite.max_hp:
                draw_hp(
                    self,
                    sprite.image,
                    0,
                    0,
                    sprite.hp / sprite.max_hp,
                    self.settings["gen"]["tilesize"],
                    int(self.settings["gen"]["tilesize"] / 10),
                    False,
                )
            self.screen.blit(sprite.image, game.camera.apply(sprite))
        draw_hp(
            self,
            self.screen,
            10,
            self.settings["gen"]["height"] - 30,
            game.player.hp / game.player.max_hp,
            200,
            15,
            True,
        )
        draw_score(self, game.player.coins)
        if self.settings["gen"]["displayfps"] == "on":
            draw_fps(self)
        pg.display.flip()

    def events(self):
        """
        Checks for key/mouse presses.
        Checks if the user is quitting the game.
        """
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.quit()
            if event.type == pg.KEYDOWN:
                if event.key == pg.K_ESCAPE:
                    self.quit()
                if self.menu.inmenu:
                    self.menu.menu_event(event)

    # Text Renderer https://www.sourcecodester.com/tutorials/python/11784/python-pygame-simple-main-menu-selection.html
    def text_format(self,
                    message: str,
                    textFont: str,
                    textSize: int,
                    textColor=[0, 0, 0]) -> pg.font.Font:
        """
        Returns a pygame text ready to be drawn to screen.
        """
        newFont = pg.font.SysFont(textFont, textSize)
        newText = newFont.render(message, 0, textColor)

        return newText

    def show_start_screen(self):
        """
        Initializes the menus, music, and starts menu loop.
        """
        self.font = "franklingothic"
        pg.mixer.music.load(
            path.join(self.data.music_folder,
                      self.settings["music"]["voidwalk"]))
        if self.settings["gen"]["music"] == "on":
            pg.mixer.music.play(-1, 0.0)
        self.menu = Menu(self.clock, self.screen, self.settings, self.data,
                         self.font, self.character)
        self.character = self.menu.run(self.menu.menu_main)

    def show_go_screen(self):
        """
        This method is used upon player death to restart at the main menu.
        """
        self.show_start_screen()
        g = Game(c.data, c.character)
        self.run(g)

    def run(self, game: Game):
        """
        Game loop; ticks the clock, checks for events, updates game state, draws game state
        """
        if self.settings["gen"]["music"] == "on":
            pg.mixer.music.load(
                path.join(self.data.music_folder,
                          self.settings["music"]["leavinghome"]))
            pg.mixer.music.play(-1, 0.0)

        self.playing = True
        while self.playing:
            # tick_busy_loop() uses more cpu but is more accurate
            self.dt = self.clock.tick_busy_loop(
                self.settings["gen"]["fps"]) / 1000
            self.events()
            game.update(self.dt)
            if game.player.hp <= 0:
                self.playing = False
            self.draw(game)

    def quit(self):
        """
        Quits pygame and exits the program
        """
        pg.quit()
        sys.exit()
Esempio n. 5
0
class Game(object):
    def __init__(self, screen, tutorialMenu, fakeNewsMenu, saveFile=None):
        self.isRunning = False
        if saveFile is None:
            self.map = Map("assets/maps/default.json")
            self.player = Player()
        else:
            self.load(saveFile)

        self.openMenu = "[Esc] Open Menu"
        self.openMenu = screen.fonts["25"].render(self.openMenu, 1,
                                                  (255, 255, 255))
        self.closeMenu = "[Esc] Close Menu"
        self.closeMenu = screen.fonts["25"].render(self.closeMenu, 1,
                                                   (255, 255, 255))
        self.ennemyController = EnnemyController(5)
        button_help = Button((700, 300), (300, 60),
                             "How to Build Walls",
                             tutorialMenu.run,
                             screen=screen)
        button_help.build(screen)

        button_fakeNewsMenu = Button((1100, 300), (300, 60),
                                     "Fake News",
                                     fakeNewsMenu.run,
                                     screen=screen)
        button_fakeNewsMenu.build(screen)

        button_quit = Button((1500, 300), (300, 60), "Quit", self.stop)
        button_quit.build(screen)
        self.pauseMenu = Menu(None,
                              [button_help, button_fakeNewsMenu, button_quit],
                              True)

        self.winMenu = Menu(pygame.image.load("assets/img/youWon.jpg"), [],
                            True)
        button_continue = Button((10, 1000), (300, 60), "4 Years Later >>",
                                 self.winMenu.stop)
        button_continue.build(screen)
        self.winMenu.buttons.append(button_continue)

        button_quit = Button((10, 1000), (300, 60), "Quit Because I'm Bad",
                             exit)
        button_quit.build(screen)
        self.loseMenu = Menu(pygame.image.load("assets/img/youLose.jpg"),
                             [button_quit], True)
        button_continue = Button((400, 1000), (300, 60),
                                 "Continue & Sue Bedin", self.loseMenu.stop)
        button_continue.build(screen)
        self.loseMenu.buttons.append(button_continue)

        self.invocations = []
        self.twats = []

        button_resume = Button((300, 300), (300, 60), "Resume",
                               self.pauseMenu.stop)
        button_resume.build(screen)
        self.pauseMenu.buttons.append(button_resume)
        self.gameEndTime = cst.GAME_TIME

        self.ballots = {
            "republican": Ballot((1800, 20), "assets/img/republican.png"),
            "democrat": Ballot((1800, 140), "assets/img/democrat.png"),
        }

    def load(self, saveFile):
        """
        Loads the game from a save file, creates an empty game if the save is None
        """
        save = json.load(open(saveFile, "r"))
        self.map = Map(save['map'])
        self.player = Player(save['player'])

    def update(self, screen):
        self.gameEndTime = int(self.gameEndTime - screen.timeElapsed)
        if self.gameEndTime <= 0:
            if self.ballots["republican"].votes > self.ballots[
                    "democrat"].votes:
                self.winMenu.run(screen)
            else:
                button_info = Button((100, 800), (
                    700, 60
                ), f'You : {self.ballots["republican"].votes} - Bedin : {self.ballots["democrat"].votes}',
                                     exit)
                button_info.build(screen)
                button_info.clickable = False
                self.loseMenu.buttons.append(button_info)
                self.loseMenu.run(screen)
            self.stop()

        if self.player.popularity < 20:
            button_info = Button(
                (100, 800), (500, 60),
                f"Your popularity went below 20% ... You Bad Boy", exit)
            button_info.build(screen)
            button_info.clickable = False
            self.loseMenu.buttons.append(button_info)
            self.loseMenu.run(screen)
            self.stop()

        for event in screen.events():
            action = self.player.eventUpdate(event)
            if action == "HIT":
                self.ennemyController.hit(self.player.hitbox,
                                          self.player.damage)
            elif action == "KAMEHAMEHA":
                self.ennemyController.hit(self.player.hitbox, 50)
            elif action == "BUILDWALL":
                self.invocations.append(
                    Wall([
                        self.player.position[0] + 205, self.player.position[1]
                    ]))

            if event.type == pygame.locals.KEYDOWN:
                if event.key == pygame.locals.K_ESCAPE:
                    self.pauseMenu.run(screen, self)

        for inv in self.invocations[:]:
            result = inv.update(self.ennemyController)
            if result == "DEAD":
                del self.invocations[self.invocations.index(inv)]

        self.player.update(screen, self.ennemyController, self.invocations,
                           self.twats)

        for twat in self.twats[:]:
            result = twat.update(screen)
            if result == "DEAD":
                del self.twats[self.twats.index(twat)]

        deaths, baddeaths, democrat_votes, republican_votes = self.ennemyController.update(
            screen, self.player.popularity)
        self.player.addSpecialAttack(deaths * 5)
        for baddeath in range(baddeaths):
            twat = Twat(screen,
                        [random.randint(200, 1400),
                         random.randint(30, 600)])
            self.twats.append(twat)
            self.player.popularity -= twat.rt * 0.1
            self.player.updatePopularity(screen)

        self.player.popularity += deaths * 0.2
        self.player.updatePopularity(screen)

        for key, ballot in self.ballots.items():
            if key == "democrat":
                ballot.add_votes(democrat_votes)
            elif key == "republican":
                ballot.add_votes(republican_votes)
            ballot.update(screen)

    def draw(self, screen):
        self.map.draw(screen, self.player)
        self.ennemyController.draw(screen)
        for inv in self.invocations:
            inv.draw(screen)

        self.player.draw(screen)
        for twat in self.twats:
            twat.draw(screen)

        for key, ballot in self.ballots.items():
            ballot.draw(screen)

    def stop(self):
        self.isRunning = False
        self.pauseMenu.stop()

    def getTimeDisplay(self):
        return str(datetime.timedelta(seconds=self.gameEndTime))

    def run(self, screen):
        self.isRunning = True
        while self.isRunning:
            self.update(screen)
            self.draw(screen)
            screen.blit(self.openMenu, (10, 10))
            self.gameEndTimeDisplay = screen.fonts["75"].render(
                self.getTimeDisplay(), 0, (255, 255, 255))
            screen.blit(self.gameEndTimeDisplay, (10, 30))
            screen.flip()