Beispiel #1
0
    def create_objects(self) -> None:
        y = 140
        self.header = TextObject(self.game,
                                 text='',
                                 x=self.game.SCREEN_WIDTH / 2,
                                 y=y)
        self.header.font = PACMAN_FONT
        self.header.update_text('PAC - MAN')
        self.objects.append(self.header)

        x = (self.game.SCREEN_WIDTH - self.BTN_WIDTH) / 2

        self.play_btn = ButtonObject(self.game, x, y + 160, self.BTN_WIDTH,
                                     self.BTN_HEIGHT, self.game.set_main_scene,
                                     'PLAY', 'play')
        self.objects.append(self.play_btn)

        self.hs_btn = ButtonObject(self.game, x, y + 240, self.BTN_WIDTH,
                                   self.BTN_HEIGHT,
                                   self.game.set_highscores_scene,
                                   'HIGHSCORES', 'multi')
        self.objects.append(self.hs_btn)

        self.settings_btn = ButtonObject(self.game, x, y + 320, self.BTN_WIDTH,
                                         self.BTN_HEIGHT,
                                         self.game.set_settings_scene,
                                         'SETTINGS', 'multi')
        self.objects.append(self.settings_btn)

        self.exit_btn = ButtonObject(self.game, x, y + 400, self.BTN_WIDTH,
                                     self.BTN_HEIGHT, self.game.exit_game,
                                     'EXIT', 'exit')
        self.objects.append(self.exit_btn)
Beispiel #2
0
 def create_objects(self) -> None:
     x = (self.game.SCREEN_WIDTH - self.BUTTON_WIDTH) / 2
     self.highscore_table = HighScoresTable(self.game,
                                            x=self.game.SCREEN_WIDTH / 2,
                                            y=150)
     self.label = TextObject(self.game,
                             text='GAME OVER',
                             x=self.game.SCREEN_WIDTH / 2,
                             y=50,
                             font_size=50)
     self.result_label = TextObject(self.game,
                                    text='',
                                    color=Color.RED,
                                    x=self.game.SCREEN_WIDTH / 2,
                                    y=100,
                                    font_size=45)
     self.return_button = ButtonObject(self.game, x, 600, self.BUTTON_WIDTH,
                                       self.BUTTON_HEIGHT,
                                       self.game.set_menu_scene, 'MENU',
                                       'multi')
     self.exit_button = ButtonObject(self.game, x, 650, self.BUTTON_WIDTH,
                                     self.BUTTON_HEIGHT,
                                     self.game.exit_game, 'EXIT', 'exit')
     self.objects.append(self.highscore_table)
     self.objects.append(self.label)
     self.objects.append(self.result_label)
     self.objects.append(self.return_button)
     self.objects.append(self.exit_button)
Beispiel #3
0
 def __init__(self,
              game,
              x: int,
              y: int,
              width: int,
              height: int,
              text_color: pygame.color.Color = (255, 255, 255),
              color: pygame.color.Color = None,
              start_index: int = 0,
              *args) -> None:
     super().__init__(game)
     self.values = args
     self.current_index = start_index
     self.color = color
     self.rect = pygame.rect.Rect(x, y, width, height)
     self.text_area = TextObject(game, 'Comic Sans MS', 32, False, False,
                                 self.values[self.current_index],
                                 text_color, x + width // 2,
                                 y + height // 2)
     self.button_back = ButtonObject(self.game,
                                     x,
                                     y,
                                     50,
                                     height,
                                     color=self.color,
                                     function=self.switch_back,
                                     text="<")
     self.button_next = ButtonObject(self.game,
                                     x + width - 50,
                                     y,
                                     50,
                                     height,
                                     color=self.color,
                                     function=self.switch_next,
                                     text=">")
Beispiel #4
0
 def __init__(self, game):
     super().__init__(game)
     self.start_time = time.time()
     self.platform = PlatformObject(game, speed=GameScene.standart_speed)
     self.balls = [BallObject(game, speed=[GameScene.standart_speed, GameScene.standart_speed])
                   for _ in range(GameScene.balls_count)]
     self.collision_count = 0
     self.score_text = TextObject(self.game, 0, 0, self.get_score_text(), ORANGE)
     self.score_text.move(10, 10)
     self.objects += self.balls
     self.objects.append(self.score_text)
     self.objects.append(self.platform)
     self.reset_balls_position()
Beispiel #5
0
class FinalSceneScores(BaseScene):
    BUTTON_WIDTH = 500
    BUTTON_HEIGHT = 40

    def __init__(self, game):
        self.highscore_table = None
        self.label = None
        self.result_label = None
        self.return_button = None
        self.exit_button = None
        super().__init__(game)

    def create_objects(self) -> None:
        x = (self.game.SCREEN_WIDTH - self.BUTTON_WIDTH) / 2
        self.highscore_table = HighScoresTable(self.game,
                                               x=self.game.SCREEN_WIDTH / 2,
                                               y=150)
        self.label = TextObject(self.game,
                                text='GAME OVER',
                                x=self.game.SCREEN_WIDTH / 2,
                                y=50,
                                font_size=50)
        self.result_label = TextObject(self.game,
                                       text='',
                                       color=Color.RED,
                                       x=self.game.SCREEN_WIDTH / 2,
                                       y=100,
                                       font_size=45)
        self.return_button = ButtonObject(self.game, x, 600, self.BUTTON_WIDTH,
                                          self.BUTTON_HEIGHT,
                                          self.game.set_menu_scene, 'MENU',
                                          'multi')
        self.exit_button = ButtonObject(self.game, x, 650, self.BUTTON_WIDTH,
                                        self.BUTTON_HEIGHT,
                                        self.game.exit_game, 'EXIT', 'exit')
        self.objects.append(self.highscore_table)
        self.objects.append(self.label)
        self.objects.append(self.result_label)
        self.objects.append(self.return_button)
        self.objects.append(self.exit_button)

    def on_activate(self) -> None:
        if self.game.is_win:
            Sounds.WIN.play()
        else:
            Sounds.LOSE.play()
        self.result_label.update_text(
            'WIN' if self.game.is_win else 'LOSE',
            Color.GREEN if self.game.is_win else Color.SOFT_RED)
        self.highscore_table.read_scores()
Beispiel #6
0
    def create_objects(self) -> None:

        self.matrix = MatrixMap(self.game)
        self.objects.append(self.matrix)

        self.info_border = DrawableObject(self.game, 0, 0,
                                          self.game.SCREEN_WIDTH,
                                          self.matrix.FIELD_Y,
                                          self.game.settings[
                                              "level_border_color"])
        self.info_bg = DrawableObject(self.game, self.BORDER_SIZE,
                                      self.BORDER_SIZE,
                                      self.game.SCREEN_WIDTH - self.BORDER_SIZE * 2,
                                      self.matrix.FIELD_Y - self.BORDER_SIZE * 2,
                                      Color.BLACK)
        tmp_x = self.BORDER_SIZE*5 + MAIN_FONT.size('SCORE: 0000')[0] // 2
        self.score_bar = TextObject(self.game, text='SCORE: 0', x=tmp_x, y=20)

        tmp_x = self.game.SCREEN_WIDTH - MAIN_FONT.size('TIME: 0000')[
            0] // 2 - self.BORDER_SIZE*5
        self.time_bar = TextObject(self.game, text='TIME: 0', x=tmp_x, y=20)

        tmp_x = self.game.SCREEN_WIDTH // 2
        self.lives_bar = TextObject(self.game, text=f'SCORE: {self.game.score}',
                                    x=tmp_x, y=20)
        self.pause_bar = TextObject(self.game, text='PAUSED',
                                    x=tmp_x, y=-self.BARS_Y, color=Color.RED)
        self.ready_bar = TextObject(self.game, text='',
                                    x=tmp_x, y=-self.BARS_Y, color=Color.YELLOW)
        self.go_bar = TextObject(self.game, text='GO!',
                                 x=tmp_x, y=self.BARS_Y, color=Color.GREEN)

        self.pause_button = ButtonObject(self.game,
                                         self.game.SCREEN_WIDTH - 210, self.BARS_Y,
                                         200, 40, self.switch_pause,
                                         'PAUSE', 'multi')
        self.menu_button = ButtonObject(self.game, 10, self.BARS_Y, 200, 40,
                                        self.game.set_menu_scene, 'TO MENU',
                                        'exit')

        self.objects.append(self.info_border)
        self.objects.append(self.info_bg)
        self.objects.append(self.score_bar)
        self.objects.append(self.time_bar)
        self.objects.append(self.lives_bar)
        self.objects.append(self.pause_bar)
        self.objects.append(self.ready_bar)
        self.objects.append(self.go_bar)
        self.objects.append(self.pause_button)
        self.objects.append(self.menu_button)
Beispiel #7
0
 def __init__(self, game):
     super().__init__(game)
     self.next_state = False
     self.name = None
     self.game.fileul = FileUploader()
     self.objects.append(
         TextObject(self.game, self.game.width // 2,
                    self.game.height // 2 - 145, "Enter your name:", WHITE))
     self.objects.append(
         InputBox(self.game, self.game.width // 2 - 100,
                  self.game.height // 2 - 95 - 25, 200, 50, 'nick'))
     self.objects.append(
         ButtonObject(self.game,
                      self.game.width // 2 - 100,
                      self.game.height // 2 - 20 - 25,
                      200,
                      50,
                      RED,
                      self.start_game,
                      text='Запуск игры'))
     self.objects.append(
         ButtonObject(self.game,
                      self.game.width // 2 - 100,
                      self.game.height // 2 + 25,
                      200,
                      50,
                      RED,
                      self.game.exit_game,
                      text='Выход'))
Beispiel #8
0
    def create_objects(self) -> None:
        alphabet0 = (chr(i) for i in range(65, 91))
        alphabet1 = (chr(i) for i in range(65, 91))
        alphabet2 = (chr(i) for i in range(65, 91))
        x = (self.game.SCREEN_WIDTH - self.SWITCHER_WIDTH) / 2

        self.label = (TextObject(self.game,
                                 text='GAME OVER',
                                 x=self.game.SCREEN_WIDTH / 2,
                                 y=50,
                                 font_size=50))
        self.name_label = (TextObject(self.game,
                                      text='AAA',
                                      font_size=40,
                                      x=self.game.SCREEN_WIDTH / 2 + 130,
                                      y=100))
        self.enter_name_label = (TextObject(self.game,
                                            text='ENTER NICKNAME: ',
                                            x=self.game.SCREEN_WIDTH / 2 - 40,
                                            y=100))
        self.first_letter = (ArrowSwitcher(self.game, x, 150,
                                           self.SWITCHER_WIDTH,
                                           self.SWITCHER_HEIGHT, Color.WHITE,
                                           Color.SOFT_RED, 0, *alphabet0))
        self.second_letter = (ArrowSwitcher(self.game, x, 200,
                                            self.SWITCHER_WIDTH,
                                            self.SWITCHER_HEIGHT, Color.WHITE,
                                            Color.SOFT_RED, 0, *alphabet1))
        self.third_letter = (ArrowSwitcher(self.game, x, 250,
                                           self.SWITCHER_WIDTH,
                                           self.SWITCHER_HEIGHT, Color.WHITE,
                                           Color.SOFT_RED, 0, *alphabet2))
        self.enter_button = (ButtonObject(self.game, x, 350,
                                          self.SWITCHER_WIDTH,
                                          self.SWITCHER_HEIGHT,
                                          self.go_to_game_over_scene_2,
                                          'ENTER', 'play'))
        self.letters = [
            self.first_letter,
            self.second_letter,
            self.third_letter,
        ]
        self.objects.append(self.label)
        self.objects.append(self.enter_name_label)
        self.objects.append(self.name_label)
        self.objects += self.letters
        self.objects.append(self.enter_button)
Beispiel #9
0
    def __init__(self, game):
        super().__init__(game)
        self.last_seconds_passed = 0
        self.three_hs = [0, 0, 0]

        self.text = TextObject(self.game, self.game.width // 2, 50,
                               self.get_gameover_text_formatted(),
                               (255, 255, 255))
        self.first_record_text = TextObject(self.game, self.game.width // 2,
                                            self.game.height * 0.25,
                                            '1) ' + str(self.three_hs[0]),
                                            GREEN)
        self.second_record_text = TextObject(self.game, self.game.width // 2,
                                             self.game.height * 0.50,
                                             '2) ' + str(self.three_hs[1]),
                                             YELLOW)
        self.third_record_text = TextObject(self.game, self.game.width // 2,
                                            self.game.height * 0.75,
                                            '3) ' + str(self.three_hs[2]),
                                            ORANGE)

        self.objects.append(self.text)
        self.objects.append(self.first_record_text)
        self.objects.append(self.second_record_text)
        self.objects.append(self.third_record_text)

        self.update_start_time()
Beispiel #10
0
 def process_draw(self):
     y = self.y
     header = TextObject(self.game, text='HIGHSCORES:', x=self.x, y=self.y)
     header.process_draw()
     i = 0
     while i < len(self.score_strings) and \
             i < HighScoresTable.COUNT_NOTES_FOR_PRINT:
         score = self.score_strings[i]
         text_score = score[0] + ' ' + str(score[1])
         y += 40
         score_bar = TextObject(self.game, text=text_score, x=self.x, y=y)
         i += 1
         score_bar.process_draw()
Beispiel #11
0
    def __init__(self, game):
        super().__init__(game)
        self.balls = [BallObject(game) for _ in range(GameScene.balls_count)]
        self.platform = Platform(game, 'images/brick.png',
                                 game.width // 2 + 50, game.height - 50, 4)
        self.collision_count = 0
        self.score = 0
        self.hs_arr = []
        self.update_highs_scores()
        self.status_text = TextObject(self.game, 0, 0,
                                      self.get_collisions_text(),
                                      (255, 255, 255))
        self.score_text = TextObject(self.game, 0, 0, self.get_score_text(),
                                     (255, 255, 255))
        self.status_text.move(10, 10)
        self.objects += self.balls
        self.objects.append(self.status_text)
        self.objects.append(self.score_text)
        self.objects.append(self.platform)

        self.reset_balls_position()
Beispiel #12
0
 def __init__(self,
              game,
              T_rect,
              SB_rect,
              Number,
              T_thic=0,
              SB_thic=0,
              shift=0):
     super().__init__(game)
     self.can_draw = True
     self.shift = shift
     self.num = Number
     self.thickness = T_thic // 3
     self.SB_thic = SB_thic
     self.SB_rect = SB_rect
     self.T_rect = T_rect
     self.rect.x = self.T_rect.x + self.thickness  # // 2
     self.rect.y = self.T_rect.y + self.thickness + self.shift  # // 2
     self.rect.width = self.T_rect.width - self.SB_rect.width - self.SB_thic * 3 - self.thickness
     self.rect.height = Field.std_height
     self.text = TextObject(self.game, 0, 0, self.get_status_text(), WHITE)
Beispiel #13
0
 def __init__(self, game):
     super().__init__(game)
     self.table = Table(game)
     self.gomenu = False
     self.objects.append(
         ButtonObject(self.game,
                      self.game.width - 150,
                      self.game.height - 100,
                      100,
                      50,
                      RED,
                      self.go_menu,
                      text='MENU'))
     self.text = TextObject(self.game, self.game.width // 2,
                            self.game.height // 5,
                            self.get_gameover_text_formatted(),
                            (255, 255, 255))
     self.objects.append(self.text)
     self.objects.append(self.table)
Beispiel #14
0
class Field(BaseElTable):
    std_height = 35

    def __init__(self,
                 game,
                 T_rect,
                 SB_rect,
                 Number,
                 T_thic=0,
                 SB_thic=0,
                 shift=0):
        super().__init__(game)
        self.can_draw = True
        self.shift = shift
        self.num = Number
        self.thickness = T_thic // 3
        self.SB_thic = SB_thic
        self.SB_rect = SB_rect
        self.T_rect = T_rect
        self.rect.x = self.T_rect.x + self.thickness  # // 2
        self.rect.y = self.T_rect.y + self.thickness + self.shift  # // 2
        self.rect.width = self.T_rect.width - self.SB_rect.width - self.SB_thic * 3 - self.thickness
        self.rect.height = Field.std_height
        self.text = TextObject(self.game, 0, 0, self.get_status_text(), WHITE)

    def check_borders(self):
        if self.rect.y < self.T_rect.y:
            self.can_draw = False
        else:
            self.can_draw = True

    def process_draw(self):
        self.check_borders()
        if self.can_draw:
            pygame.draw.rect(self.game.screen, ORANGE, self.rect,
                             self.thickness)
            self.text.process_draw()

    def get_status_text(self):
        #self.game.fileul.read_file_data()
        return f'Name: {self.game.fileul.data[self.num][0]} Score: {self.game.fileul.data[self.num][1]}'

    def process_logic(self):
        self.text.update_text(self.get_status_text())
        self.text.move_center(self.rect.x + self.rect.width // 2,
                              self.rect.y + self.rect.height // 2)

    def set_pos_y(self, y):
        self.rect.y = self.T_rect.y + self.thickness + self.shift + y
Beispiel #15
0
class GameOverScene(BaseScene):
    text_format = 'Game over ({})'
    seconds_to_end = 3

    def __init__(self, game):
        super().__init__(game)
        self.last_seconds_passed = 0
        self.three_hs = [0, 0, 0]

        self.text = TextObject(self.game, self.game.width // 2, 50,
                               self.get_gameover_text_formatted(),
                               (255, 255, 255))
        self.first_record_text = TextObject(self.game, self.game.width // 2,
                                            self.game.height * 0.25,
                                            '1) ' + str(self.three_hs[0]),
                                            GREEN)
        self.second_record_text = TextObject(self.game, self.game.width // 2,
                                             self.game.height * 0.50,
                                             '2) ' + str(self.three_hs[1]),
                                             YELLOW)
        self.third_record_text = TextObject(self.game, self.game.width // 2,
                                            self.game.height * 0.75,
                                            '3) ' + str(self.three_hs[2]),
                                            ORANGE)

        self.objects.append(self.text)
        self.objects.append(self.first_record_text)
        self.objects.append(self.second_record_text)
        self.objects.append(self.third_record_text)

        self.update_start_time()

    def get_gameover_text_formatted(self):
        return self.text_format.format(self.seconds_to_end -
                                       self.last_seconds_passed)

    def on_activate(self):
        self.update_start_time()
        self.update_highscores()
        self.update_highscores_text()

    def update_start_time(self):
        self.time_start = datetime.now()

    def update_highscores(self):
        with open('highscores.txt', 'r') as hs_file:
            hs_arr = sorted([round(float(i), 2) for i in hs_file.readlines()],
                            reverse=True)
            self.three_hs = hs_arr[0:3]

    def update_highscores_text(self):
        self.first_record_text.update_text('1) ' + str(self.three_hs[0]))
        self.second_record_text.update_text('2) ' + str(self.three_hs[1]))
        self.third_record_text.update_text('3) ' + str(self.three_hs[2]))

    def process_logic(self):
        time_current = datetime.now()
        seconds_passed = (time_current - self.time_start).seconds
        if self.last_seconds_passed != seconds_passed:
            self.last_seconds_passed = seconds_passed
            self.objects[0].update_text(self.get_gameover_text_formatted())
        if seconds_passed >= self.seconds_to_end:
            self.game.set_scene(self.game.SCENE_MENU)
Beispiel #16
0
class ArrowSwitcher(DrawableObject):
    def __init__(self,
                 game,
                 x: int,
                 y: int,
                 width: int,
                 height: int,
                 text_color: pygame.color.Color = (255, 255, 255),
                 color: pygame.color.Color = None,
                 start_index: int = 0,
                 *args) -> None:
        super().__init__(game)
        self.values = args
        self.current_index = start_index
        self.color = color
        self.rect = pygame.rect.Rect(x, y, width, height)
        self.text_area = TextObject(game, 'Comic Sans MS', 32, False, False,
                                    self.values[self.current_index],
                                    text_color, x + width // 2,
                                    y + height // 2)
        self.button_back = ButtonObject(self.game,
                                        x,
                                        y,
                                        50,
                                        height,
                                        color=self.color,
                                        function=self.switch_back,
                                        text="<")
        self.button_next = ButtonObject(self.game,
                                        x + width - 50,
                                        y,
                                        50,
                                        height,
                                        color=self.color,
                                        function=self.switch_next,
                                        text=">")

    def switch_back(self) -> None:
        self.current_index -= 1
        if self.current_index < 0:
            self.current_index = len(self.values) - 1
        self.set_text(self.values[self.current_index])

    def switch_next(self) -> None:
        self.current_index += 1
        if self.current_index > len(self.values) - 1:
            self.current_index = 0
        self.set_text(self.values[self.current_index])

    def set_center(self, x: int, y: int) -> None:
        super(self).set_center(x, y)
        self.text_area.rect = self.rect
        self.button_back.rect = self.rect
        self.button_next.rect = self.rect

    def set_position(self, x: int, y: int) -> None:
        super().set_position(x, y)
        self.text_area.rect = self.rect
        self.button_back.rect = self.rect
        self.button_next.rect = self.rect

    def switch_to(self, new_index):
        if 0 <= new_index < len(self.values):
            self.current_index = new_index
            self.set_text(self.values[new_index])

    def set_text(self, text) -> None:
        self.text = text
        self.text_area.text = text
        self.text_area.update_text(text)

    def process_event(self, event) -> None:
        self.button_back.process_event(event)
        self.button_next.process_event(event)

    def process_draw(self) -> None:
        self.text_area.process_draw()
        self.button_back.process_draw()
        self.button_next.process_draw()

    def get_current_value(self) -> str:
        return self.values[self.current_index]
Beispiel #17
0
class GameScene(BaseScene):
    max_collisions = 15
    balls_count = 1
    collision_tolerance = 6
    standart_speed = randrange(2, 3)
    accelerate = 1.15

    def __init__(self, game):
        super().__init__(game)
        self.start_time = time.time()
        self.platform = PlatformObject(game, speed=GameScene.standart_speed)
        self.balls = [BallObject(game, speed=[GameScene.standart_speed, GameScene.standart_speed])
                      for _ in range(GameScene.balls_count)]
        self.collision_count = 0
        self.score_text = TextObject(self.game, 0, 0, self.get_score_text(), ORANGE)
        self.score_text.move(10, 10)
        self.objects += self.balls
        self.objects.append(self.score_text)
        self.objects.append(self.platform)
        self.reset_balls_position()

    def process_event(self, event):
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                self.game.set_scene(self.game.SCENE_MENU)
            elif event.key == pygame.K_a or event.key == pygame.K_d:
                self.platform.process_event(event)

    def update_score(self):
        self.score_text.update_text(self.get_score_text())
        self.score_text.move(10, 10)

    def get_score(self):
        return int(time.time() - self.start_time)

    def get_score_text(self):
        return f'Score: {self.get_score()} seconds'

    def get_random_position(self, radius):
        return randint(10, self.game.width - radius * 2 - 10), randint(10, self.game.height - radius * 2 - 10)

    def set_random_position(self, ball):
        pos = self.get_random_position(ball.radius)
        ball.move(*pos)

    def reset_balls_position(self):
        for ball in self.balls:
            ball.move(self.game.width, self.game.height)

    def set_random_unique_position(self):
        for index in range(len(self.balls)):
            other_rects = [self.balls[i].rect for i in range(len(self.balls)) if i != index]
            self.set_random_position(self.balls[index])
            while self.balls[index].rect.collidelist(other_rects) != -1:
                self.set_random_position(self.balls[index])

    def on_activate(self):
        self.start_time = time.time()
        self.collision_count = 0
        self.reset_balls_position()
        self.set_random_unique_position()
        self.score_text.update_text(self.get_score_text())
        self.score_text.move(10, 10)

    def collide_platform_with_ball(self):
        if self.platform.rect.colliderect(self.balls[0].rect):
            if abs(self.balls[0].rect.bottom - self.platform.rect.top) < GameScene.collision_tolerance and \
                    self.balls[0].speed[1] > 0:
                self.balls[0].speed[1] *= -GameScene.accelerate
            elif abs(self.balls[0].rect.left - self.platform.rect.right) < GameScene.collision_tolerance and \
                    self.balls[0].speed[0] < 0:
                self.balls[0].speed[0] *= -GameScene.accelerate
            elif abs(self.balls[0].rect.right - self.platform.rect.left) < GameScene.collision_tolerance and\
                    self.balls[0].speed[0] > 0:
                self.balls[0].speed[0] *= -GameScene.accelerate

    def check_game_over(self):
        if self.balls[0].rect.bottom >= self.game.height:
            self.game.fileul.set_score(self.get_score())
            self.game.fileul.write_file_data()
            self.game.set_scene(self.game.SCENE_GAMEOVER)
            self.start_time = 0

    def process_logic(self):
        super().process_logic()
        self.collide_platform_with_ball()
        self.update_score()
        self.check_game_over()
Beispiel #18
0
class GameScene(BaseScene):
    max_collisions = 15
    balls_count = 3

    def __init__(self, game):
        super().__init__(game)
        self.balls = [BallObject(game) for _ in range(GameScene.balls_count)]
        self.platform = Platform(game, 'images/brick.png',
                                 game.width // 2 + 50, game.height - 50, 4)
        self.collision_count = 0
        self.score = 0
        self.hs_arr = []
        self.update_highs_scores()
        self.status_text = TextObject(self.game, 0, 0,
                                      self.get_collisions_text(),
                                      (255, 255, 255))
        self.score_text = TextObject(self.game, 0, 0, self.get_score_text(),
                                     (255, 255, 255))
        self.status_text.move(10, 10)
        self.objects += self.balls
        self.objects.append(self.status_text)
        self.objects.append(self.score_text)
        self.objects.append(self.platform)

        self.reset_balls_position()

    def process_event(self, event):
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                self.game.set_scene(self.game.SCENE_MENU)
        self.platform.process_event(event)

    def get_random_position(self, radius):
        return randint(10, self.game.width - radius * 2 - 10), randint(
            10, self.game.height - radius * 2 - 10)

    def set_random_position(self, ball):
        pos = self.get_random_position(ball.radius)
        ball.move(*pos)

    def reset_balls_position(self):
        for ball in self.balls:
            ball.move(self.game.width, self.game.height)

    def set_random_unique_position(self):
        for index in range(len(self.balls)):
            other_rects = [
                self.balls[i].rect for i in range(len(self.balls))
                if i != index
            ]
            self.set_random_position(self.balls[index])
            while self.balls[index].rect.collidelist(other_rects) != -1:
                self.set_random_position(self.balls[index])

    def on_activate(self):
        self.collision_count = 0
        self.score = 0
        self.reset_balls_position()
        self.set_random_unique_position()
        self.status_text.update_text(self.get_collisions_text())
        self.status_text.move(10, 10)
        self.score_text.update_text(self.get_score_text())
        self.score_text.move(10, 40)

    def check_ball_intercollisions(self):
        for i in range(len(self.balls) - 1):
            for j in range(i + 1, len(self.balls)):
                if self.balls[i].collides_with(self.balls[j]):
                    self.balls[i].bounce(self.balls[j])

    def get_collisions_text(self):
        return 'Wall collisions: {}/{}'.format(self.collision_count,
                                               GameScene.max_collisions)

    def get_score_text(self):
        return 'Score: ' + str(int(self.score))

    def check_ball_edge_collision(self):
        for ball in self.balls:
            if ball.edge_collision():
                self.collision_count += 1
                self.status_text.update_text(self.get_collisions_text())
                self.status_text.move(10, 10)

    def increase_score(self):
        self.score += 0.01
        self.score_text.update_text(self.get_score_text())
        self.score_text.move(10, 40)

    def add_new_highscore(self):
        with open('highscores.txt', 'a') as hs_file:
            hs_file.writelines('\n' + str(round(self.score, 2)))
        print('Highscore has been written')

    def update_highs_scores(self):
        with open('highscores.txt', 'r') as hs_file:
            self.hs_arr = [round(float(i), 2) for i in hs_file.readlines()]

    def check_game_over(self):
        if self.collision_count >= GameScene.max_collisions:
            self.add_new_highscore()
            self.update_highs_scores()
            self.game.set_scene(self.game.SCENE_GAMEOVER)

    def check_ball_platform_collision(self):
        for ball_ndx in range(len(self.balls)):
            self.balls[ball_ndx].check_platform_collision(self.platform)

    def process_logic(self):
        super().process_logic()
        self.increase_score()
        self.check_ball_edge_collision()
        self.check_ball_intercollisions()
        self.check_ball_platform_collision()
        self.platform.move()
        self.check_game_over()
Beispiel #19
0
    def create_objects(self) -> None:
        self.game.settings = read_json_from_file(SETTINGS_PATH)

        self.lvl_count = int(self.game.settings['lvl_count'])
        self.lvl_skin = int(self.game.settings['lvl_skin'])
        self.cell_skin = int(self.game.settings['cell_skin'])
        self.settings_1 = ["Level: " + (str(i) + "/" + str(self.lvl_count - 1)) for i in range(self.lvl_count)]
        self.settings_2 = ['Mode: score_cup', 'Mode: survival', 'Mode: hunt']
        self.settings_3 = ['Coop: False', 'Coop: True']
        self.settings_4 = ['First Pacman skin: classic',
                           'First Pacman skin: bordered',
                           'First Pacman skin: inverted',
                           'First Pacman skin: ghost', ]
        self.settings_5 = ['Second Pacman skin: classic',
                           'Second Pacman skin: bordered',
                           'Second Pacman skin: inverted',
                           'Second Pacman skin: ghost', ]
        self.settings_6 = ['Level texture: ' + (str(i) + "/" + str(self.lvl_skin - 1)) for i in range(self.lvl_skin)]
        self.settings_7 = ['Cell texture: ' + (str(i) + "/" + str(self.cell_skin - 1)) for i in range(self.cell_skin)]
        self.settings_8 = ['Long turn buffer: True', 'Long turn buffer: False']

        x = (self.game.SCREEN_WIDTH - self.SWITCHER_WIDTH) / 2
        self.lvl_config = (ArrowSwitcher(self.game,
                                         x, 70,
                                         self.SWITCHER_WIDTH,
                                         self.SWITCHER_HEIGHT,
                                         Color.WHITE, Color.SOFT_RED,
                                         0, *self.settings_1))
        self.mode_config = (ArrowSwitcher(self.game,
                                          x, 130,
                                          self.SWITCHER_WIDTH,
                                          self.SWITCHER_HEIGHT,
                                          Color.WHITE, Color.ORANGE,
                                          0, *self.settings_2))
        self.coop_config = (ArrowSwitcher(self.game,
                                          x, 190,
                                          self.SWITCHER_WIDTH,
                                          self.SWITCHER_HEIGHT,
                                          Color.WHITE, Color.YELLOW,
                                          0, *self.settings_3))
        self.pacman1_config = (ArrowSwitcher(self.game,
                                             x, 250,
                                             self.SWITCHER_WIDTH,
                                             self.SWITCHER_HEIGHT,
                                             Color.WHITE, Color.GREEN,
                                             0, *self.settings_4))
        self.pacman2_config = (ArrowSwitcher(self.game,
                                             x, 310,
                                             self.SWITCHER_WIDTH,
                                             self.SWITCHER_HEIGHT,
                                             Color.WHITE, Color.SOFT_BLUE,
                                             0, *self.settings_5))
        self.background_config = (ArrowSwitcher(self.game,
                                                x, 370,
                                                self.SWITCHER_WIDTH,
                                                self.SWITCHER_HEIGHT,
                                                Color.WHITE, Color.BLUE,
                                                0, *self.settings_6))
        self.cell_config = (ArrowSwitcher(self.game,
                                          x, 430,
                                          self.SWITCHER_WIDTH,
                                          self.SWITCHER_HEIGHT,
                                          Color.WHITE, Color.PURPLE,
                                          0, *self.settings_7))
        self.long_buffer_config = (ArrowSwitcher(self.game,
                                                 x, 490,
                                                 self.SWITCHER_WIDTH,
                                                 self.SWITCHER_HEIGHT,
                                                 Color.WHITE, Color.GREY,
                                                 0, *self.settings_8))
        self.configs = [
            self.lvl_config,
            self.mode_config,
            self.coop_config,
            self.pacman1_config,
            self.pacman2_config,
            self.background_config,
            self.cell_config,
            self.long_buffer_config,
        ]
        self.objects += self.configs
        self.objects.append(
            ButtonObject(self.game, x, 550, self.SWITCHER_WIDTH, 40,
                         self.game.set_menu_scene, 'SAVE AND RETURN', 'exit'))
        self.objects.append(
            ButtonObject(self.game, x, 610, self.SWITCHER_WIDTH, 40,
                         self.quit_without_saving, 'RETURN', 'exit'))
        self.objects.append(TextObject(self.game, text='SETTINGS',
                                       font_size=50,
                                       x=self.game.SCREEN_WIDTH / 2, y=30))
Beispiel #20
0
class MainScene(BaseScene):
    TICKS_TO_REVIVE = 40
    TICKS_TO_DEATH_SOUND = 30
    BORDER_SIZE = 2
    BARS_Y = 50

    def __init__(self, game):

        game.score = 0

        self.game_mode = game.settings['mode']

        self.last_timer = datetime.datetime.now()
        self.played_seconds = 0

        self.lives = 3

        self.death_music_timer = 0

        self.revivings_pause_ticks = self.TICKS_TO_REVIVE

        self.paused = False

        super().__init__(game)

    def create_objects(self) -> None:

        self.matrix = MatrixMap(self.game)
        self.objects.append(self.matrix)

        self.info_border = DrawableObject(self.game, 0, 0,
                                          self.game.SCREEN_WIDTH,
                                          self.matrix.FIELD_Y,
                                          self.game.settings[
                                              "level_border_color"])
        self.info_bg = DrawableObject(self.game, self.BORDER_SIZE,
                                      self.BORDER_SIZE,
                                      self.game.SCREEN_WIDTH - self.BORDER_SIZE * 2,
                                      self.matrix.FIELD_Y - self.BORDER_SIZE * 2,
                                      Color.BLACK)
        tmp_x = self.BORDER_SIZE*5 + MAIN_FONT.size('SCORE: 0000')[0] // 2
        self.score_bar = TextObject(self.game, text='SCORE: 0', x=tmp_x, y=20)

        tmp_x = self.game.SCREEN_WIDTH - MAIN_FONT.size('TIME: 0000')[
            0] // 2 - self.BORDER_SIZE*5
        self.time_bar = TextObject(self.game, text='TIME: 0', x=tmp_x, y=20)

        tmp_x = self.game.SCREEN_WIDTH // 2
        self.lives_bar = TextObject(self.game, text=f'SCORE: {self.game.score}',
                                    x=tmp_x, y=20)
        self.pause_bar = TextObject(self.game, text='PAUSED',
                                    x=tmp_x, y=-self.BARS_Y, color=Color.RED)
        self.ready_bar = TextObject(self.game, text='',
                                    x=tmp_x, y=-self.BARS_Y, color=Color.YELLOW)
        self.go_bar = TextObject(self.game, text='GO!',
                                 x=tmp_x, y=self.BARS_Y, color=Color.GREEN)

        self.pause_button = ButtonObject(self.game,
                                         self.game.SCREEN_WIDTH - 210, self.BARS_Y,
                                         200, 40, self.switch_pause,
                                         'PAUSE', 'multi')
        self.menu_button = ButtonObject(self.game, 10, self.BARS_Y, 200, 40,
                                        self.game.set_menu_scene, 'TO MENU',
                                        'exit')

        self.objects.append(self.info_border)
        self.objects.append(self.info_bg)
        self.objects.append(self.score_bar)
        self.objects.append(self.time_bar)
        self.objects.append(self.lives_bar)
        self.objects.append(self.pause_bar)
        self.objects.append(self.ready_bar)
        self.objects.append(self.go_bar)
        self.objects.append(self.pause_button)
        self.objects.append(self.menu_button)

    def process_logic(self) -> None:
        if self.paused:
            self.last_timer = datetime.datetime.now()
        elif self.death_music_timer > 0:
            self.death_music_timer -= 1
        elif self.revivings_pause_ticks > 0:
            self.revivings_pause_ticks -= 1
            self.ready_bar.rect.y = self.BARS_Y
            self.ready_bar.update_text(f'READY! {self.revivings_pause_ticks}')
            self.go_bar.rect.y = -self.BARS_Y
        elif self.revivings_pause_ticks == 0:
            self.revivings_pause_ticks = -1
            self.ready_bar.rect.y = -self.BARS_Y
            self.go_bar.rect.y = self.BARS_Y
        else:
            self.pacmans_reviving()
            super(MainScene, self).process_logic()

    def additional_logic(self) -> None:
        now = datetime.datetime.now()
        delta = now - self.last_timer
        self.last_timer = now
        self.played_seconds += delta.total_seconds()
        self.time_bar.update_text(f'TIME: {int(self.played_seconds)}')

        if self.game_mode == 'survival':
            self.game.set_scores(int(self.played_seconds) * 10)

        self.score_bar.update_text(f'SCORE: {self.game.score}')

        self.lives_bar.update_text(f'LIVES: {self.lives}')

        if self.is_win():
            self.end_game(True)
        elif self.is_lose():
            self.end_game(False)

    @staticmethod
    def scary_mode_on():
        Ghost.scary_mode_on()

    def pacmans_reviving(self):
        pacmans = self.matrix.pacmans
        ghosts = self.matrix.ghosts
        for pacman in pacmans:
            obj = pacman.obj
            if not obj.alive and self.lives > 0:
                self.revivings_pause_ticks = self.TICKS_TO_REVIVE
                self.lives -= 1
                for p in pacmans:
                    p.obj.revive()
                for g in ghosts:
                    g.obj.set_spawn_pos()
                self.music_reload()

    def is_win(self):
        if self.game_mode == 'score_cup':
            return self.matrix.seeds_count <= 0
        elif self.game_mode == 'hunt':
            return self.matrix.ghosts_count <= 0
        return False

    def is_lose(self):
        if self.matrix.pacmans_count <= 0 and self.lives <= 0:
            return True
        return False

    def end_game(self, win=False):
        self.game.is_win = win
        self.game.set_scene(self.game.GAMEOVER_SCENE_INDEX)

    def on_activate(self) -> None:
        self.__init__(self.game)
        self.music_reload()

    def music_reload(self, ):
        Sounds.SIREN.stop()
        Sounds.BEGINING.play()
        Sounds.SIREN.play(-1, fade_ms=50000)

    def on_deactivate(self) -> None:
        Sounds.SIREN.stop()

    def process_event(self, event: pygame.event.Event) -> None:
        if self.revivings_pause_ticks == -1 and self.death_music_timer == 0:
            if self.paused:
                self.menu_button.process_event(event)
                self.pause_button.process_event(event)
                self.additional_event_check(event)
            else:
                super(MainScene, self).process_event(event)

    def additional_event_check(self, event: pygame.event.Event) -> None:
        if event.type == pygame.KEYDOWN and event.key == pygame.K_p:
            self.switch_pause()

    def switch_pause(self):
        self.go_bar.rect.y *= -1
        self.pause_bar.rect.y = self.BARS_Y if self.pause_bar.rect.y < 0 else -self.BARS_Y
        self.paused = not self.paused

    def process_draw(self) -> None:
        super(MainScene, self).process_draw()