Esempio n. 1
0
    def reset_game(self):
        """Reset score and position."""

        self.l_score = 0
        self.r_score = 0
        self.finish = False
        self.music.start_music()

        self.l_paddle = Paddle(
            coordinates=(PADDLE_SIDE, (HEIGHT - PADDLE_HEIGHT) // 2),
            colour=COL_PADDLE,
            width=PADDLE_WIDTH,
            height=PADDLE_HEIGHT,
            control_up=pyxel.KEY_W,
            control_down=pyxel.KEY_S,
            move_speed=PADDLE_MOVE_SPEED,
            dimensions=DIMENSIONS,
        )

        self.r_paddle = Paddle(
            coordinates=(
                WIDTH - PADDLE_SIDE - PADDLE_WIDTH,
                (HEIGHT - PADDLE_HEIGHT) // 2,
            ),
            colour=COL_PADDLE,
            width=PADDLE_WIDTH,
            height=PADDLE_HEIGHT,
            control_up=pyxel.KEY_UP,
            control_down=pyxel.KEY_DOWN,
            move_speed=PADDLE_MOVE_SPEED,
            dimensions=DIMENSIONS,
        )

        self.ball = Ball(
            coordinates=(WIDTH // 2, HEIGHT // 2),
            colour=COL_BALL,
            width=BALL_SIDE,
            height=BALL_SIDE,
            initial_velocity=BALL_INITIAL_VELOCITY,
            dimensions=DIMENSIONS,
        )

        self.sparkler = ParticleEmitter(self.ball)

        pickup_types = {
            "sparkle": PickupType(14, self.sparkler.turn_on, self.sparkler.turn_off),
            "expand": PickupType(12, self.expand_paddle, self.contract_paddle),
            "slow": PickupType(8, self.slow_paddle, self.speed_paddle),
            "bounce": PickupType(11, self.ball.bounce_on, self.ball.bounce_off),
            "giantball": PickupType(10, self.ball.giant_on, self.ball.giant_off),
        }
        self.expand_stack = []
        self.speed_stack = []
        pickup_side_buffer = PADDLE_WIDTH + PADDLE_SIDE + 2
        self.pickups = Pickups(
            pickup_types, self.music, pickup_side_buffer, WIDTH - pickup_side_buffer, 0, HEIGHT
        )

        self.reset_after_score()
Esempio n. 2
0
    def __init__(self):
        pyxel.init(*App.screen_size)
        self.background = Background(App.screen_size, App.margin)
        self.ball = Ball(App.screen_size, App.margin)
        self.paddle = Paddle(App.screen_size, App.margin)

        pyxel.run(self.update, self.draw)
Esempio n. 3
0
 def create_paddle(self):
     paddle = Paddle((c.screen_width - c.paddle_width) // 2,
                     c.screen_height - c.paddle_height * 2, c.paddle_width,
                     c.paddle_height, c.paddle_color, c.paddle_speed)
     self.keydown_handlers[pygame.K_LEFT].append(paddle.handle)
     self.keydown_handlers[pygame.K_RIGHT].append(paddle.handle)
     self.keyup_handlers[pygame.K_LEFT].append(paddle.handle)
     self.keyup_handlers[pygame.K_RIGHT].append(paddle.handle)
     self.paddle = paddle
     self.objects.append(self.paddle)
Esempio n. 4
0
 def _initialize_game_objects(self):
     self.screen.fill(BLACK)
     self.line = MiddleLine(GREY, self.screen,
                            (int(self.screen_width / 2), 0), 1,
                            self.screen_height)
     pod_player1_position, pod_player2_position = self._compute_player_pods_initial_positions(
     )
     self.pod_player1 = Paddle('seznam_logo.png', self.screen,
                               pod_player1_position, POD_WIDTH, POD_HEIGHT)
     self.pod_player2 = Paddle('seznam_logo.png', self.screen,
                               pod_player2_position, POD_WIDTH, POD_HEIGHT)
     score_player1_position, score_player2_position = self._compute_player_score_positions(
     )
     self.score_player1 = Score(self.state['player1']['score'],
                                DARK_GREY,
                                self.screen,
                                score_player1_position,
                                width=SCORE_WIDTH,
                                heigth=SCORE_HEIGHT)
     self.score_player2 = Score(self.state['player2']['score'],
                                DARK_GREY,
                                self.screen,
                                score_player2_position,
                                width=SCORE_WIDTH,
                                heigth=SCORE_HEIGHT)
     self.frame = Frame(WHITE,
                        self.screen, (0, 0),
                        self.screen_width,
                        self.screen_height,
                        border=1)
     self.ball = Ball([5, 5],
                      'seznam_icon.png',
                      self.screen,
                      width=BALL_WIDTH,
                      height=BALL_HEIGHT)
     pygame.display.flip()
Esempio n. 5
0
 def initialize_game(self):
     while True:
         window = Window(self.level, self.lives, self.score)
         self.initialize_brickpattern(window)
         ball1 = Ball(config.PADDLE_X + int(config.PADDLE_WIDTH / 2),
                      config.PADDLE_Y - 1, 1, 1, config.BALL_VX,
                      config.BALL_VY, config.BALL_COLOR, config.BALL_SPRITE)
         paddle = Paddle(config.PADDLE_X, config.PADDLE_Y, 1,
                         config.PADDLE_WIDTH, config.PADDLE_COLOR,
                         config.PADDLE_SPRITE)
         window.add(ball1)
         window.addPaddle(paddle)
         self.level, self.lives, self.score = window.render()
         if self.lives == 0:
             print("Game over youe score is :", self.score)
             break
Esempio n. 6
0
    def initialize_game(self):
        begin = clock()

        while True:
            window = Window(self.level, self.lives, self.score)
            self.initialize_brickpattern(window)
            ball1 = Ball(config.PADDLE_X+int(config.PADDLE_WIDTH / 2), config.PADDLE_Y - 1,
                         1, 1, config.BALL_VX, config.BALL_VY, config.BALL_COLOR, config.BALL_SPRITE)
            paddle = Paddle(config.PADDLE_X, config.PADDLE_Y, 1,
                            config.PADDLE_WIDTH, config.PADDLE_COLOR, config.PADDLE_SPRITE)
            window.add(ball1)
            window.addPaddle(paddle)
            self.level, self.lives, self.score = window.render()
            if self.lives == 0:
                print("Game over your score is :", self.score)
                print("time taken :", clock() - begin)
                break
            elif self.lives > 0 and self.level == 5:
                print("You finished the game your score is :", self.score)
                print("Time taken :", clock() - begin)
                break
Esempio n. 7
0
    deadforeternity = 0
    boss = 0
    shoot = 0

    #throws error is window is small
    if wxcor < 140 or wycor < 40:
        print("terminal size is too small")
        time.sleep(3)
        loopvar = 0
    print("welcome to BRICK BREAKER 1.0")
    print("press x to exit")
    print("press c to continue paused game")
    print("press a and d to move paddle")
    print("press s to skip levels")
    #give paddlewidth as a multiple of 2 everytime
    paddle = Paddle(int(wxcor / 2) - 5, wycor - 5, 30, 4, 1)
    ball = Ball(int(wxcor / 2), wycor - 6, 0, 1)
    bossitem = Boss(int(wxcor / 2) - 5, 5, 20)
    # bossitem = 0
    randomvar = random.choice(randvelocity)
    ball.setvel(randomvar, -1)
    # randomloc = random.randint( int(wxcor/2) - 5, wycor-5)
    # ball.setloc(randomloc, wycor - 6)
    # print(randomvar)
    # window.addpaddletoboard(paddle)
    # window.rendergame()
    timeout = config.timeouts
    keyinput = manageinput()
    time.sleep(4)
    #test variable
    test = 0
Esempio n. 8
0
class Pong:
    """The class that sets up and runs the game."""

    def __init__(self):
        """Initiate pyxel, set up initial game variables, and run."""

        pyxel.init(WIDTH, HEIGHT, caption="Pong!", scale=8, fps=60)
        self.music = Music()
        self.reset_game()
        pyxel.run(self.update, self.draw)

    def reset_game(self):
        """Reset score and position."""

        self.l_score = 0
        self.r_score = 0
        self.finish = False
        self.music.start_music()

        self.l_paddle = Paddle(
            coordinates=(PADDLE_SIDE, (HEIGHT - PADDLE_HEIGHT) // 2),
            colour=COL_PADDLE,
            width=PADDLE_WIDTH,
            height=PADDLE_HEIGHT,
            control_up=pyxel.KEY_W,
            control_down=pyxel.KEY_S,
            move_speed=PADDLE_MOVE_SPEED,
            dimensions=DIMENSIONS,
        )

        self.r_paddle = Paddle(
            coordinates=(
                WIDTH - PADDLE_SIDE - PADDLE_WIDTH,
                (HEIGHT - PADDLE_HEIGHT) // 2,
            ),
            colour=COL_PADDLE,
            width=PADDLE_WIDTH,
            height=PADDLE_HEIGHT,
            control_up=pyxel.KEY_UP,
            control_down=pyxel.KEY_DOWN,
            move_speed=PADDLE_MOVE_SPEED,
            dimensions=DIMENSIONS,
        )

        self.ball = Ball(
            coordinates=(WIDTH // 2, HEIGHT // 2),
            colour=COL_BALL,
            width=BALL_SIDE,
            height=BALL_SIDE,
            initial_velocity=BALL_INITIAL_VELOCITY,
            dimensions=DIMENSIONS,
        )

        self.sparkler = ParticleEmitter(self.ball)

        pickup_types = {
            "sparkle": PickupType(14, self.sparkler.turn_on, self.sparkler.turn_off),
            "expand": PickupType(12, self.expand_paddle, self.contract_paddle),
            "slow": PickupType(8, self.slow_paddle, self.speed_paddle),
            "bounce": PickupType(11, self.ball.bounce_on, self.ball.bounce_off),
            "giantball": PickupType(10, self.ball.giant_on, self.ball.giant_off),
        }
        self.expand_stack = []
        self.speed_stack = []
        pickup_side_buffer = PADDLE_WIDTH + PADDLE_SIDE + 2
        self.pickups = Pickups(
            pickup_types, self.music, pickup_side_buffer, WIDTH - pickup_side_buffer, 0, HEIGHT
        )

        self.reset_after_score()

    def reset_after_score(self):
        """Reset paddles and ball."""
        self.start = pyxel.frame_count + 50
        self.speed_up = self.start + SPEED_PERIOD
        self.ball.reset()

    ##############
    # Game logic #
    ##############

    def update(self):
        """Update logic of game. Updates the paddles, ball, and checks for scoring/win condition."""

        self.l_paddle.update()
        self.r_paddle.update()
        self.sparkler.sparkle()

        if pyxel.frame_count > self.start and not self.finish:
            outcome = self.ball.update()
            if outcome:
                self.score(outcome)
            self.check_speed()
            if self.ball.check_collision([self.l_paddle, self.r_paddle]):
                self.music.sfx_hit()
            self.pickups.check_pickup()
            self.pickups.check_collision(self.ball)

        if pyxel.btn(pyxel.KEY_Q):
            pyxel.quit()

        if pyxel.btnp(pyxel.KEY_R):
            self.reset_game()

    def check_speed(self):
        """Adds velocity to the ball periodically."""

        if pyxel.frame_count > self.speed_up:
            self.speed_up += SPEED_PERIOD
            self.ball.x_vol += SPEED_AMOUNT * sign(self.ball.x_vol)
            self.ball.y_vol += SPEED_AMOUNT * sign(self.ball.y_vol)

    def score(self, outcome):
        """Adds to the score if the ball hits the side. Check win condition."""

        self.music.sfx_score()
        if outcome == "l":
            self.l_score += 1
        elif outcome == "r":
            self.r_score += 1

        if self.l_score >= WIN_CONDITION or self.r_score >= WIN_CONDITION:
            self.win_event()

        self.reset_after_score()

    def win_event(self):
        """What happens when someone wins the game!"""

        self.finish = True
        self.music.stop_music()
        self.music.sfx_finish()

    ######################
    # Pickup controllers #
    ######################

    def expand_paddle(self):
        """Expand the pandle temporarily."""

        if self.ball.x_vol > 0:
            paddle = self.l_paddle
        else:
            paddle = self.r_paddle

        paddle.height = PADDLE_HEIGHT_EXPANDED
        paddle.y -= (PADDLE_HEIGHT_EXPANDED - PADDLE_HEIGHT) // 2
        self.expand_stack.append(paddle)

    def contract_paddle(self):
        """Revert paddle side to normal."""

        paddle = self.expand_stack.pop(0)
        if paddle not in self.expand_stack:
            paddle.height = PADDLE_HEIGHT
            paddle.y += (PADDLE_HEIGHT_EXPANDED - PADDLE_HEIGHT) // 2

    def slow_paddle(self):
        """Slow the pandle temporarily."""

        if self.ball.x_vol > 0:
            paddle = self.l_paddle
        else:
            paddle = self.r_paddle

        paddle.move_speed = PADDLE_MOVE_SPEED_SLOW
        paddle.colour = COL_PADDLE_SLOW
        self.speed_stack.append(paddle)

    def speed_paddle(self):
        """Speed the paddle back up to normal speed."""

        paddle = self.speed_stack.pop(0)
        if paddle not in self.speed_stack:
            paddle.move_speed = PADDLE_MOVE_SPEED
            paddle.colour = COL_PADDLE

    ##############
    # Draw logic #
    ##############

    def draw(self):
        """Draw the paddles and ball OR the end screen."""

        if self.finish:
            self.draw_end_screen()
        else:
            pyxel.cls(COL_BACKGROUND)
            self.sparkler.display()
            self.l_paddle.display()
            self.r_paddle.display()
            self.pickups.display()
            self.ball.display()
            self.draw_score()

    def draw_score(self):
        """Draw the score at the top."""

        l_score = "{:01}".format(self.l_score)
        r_score = "{:01}".format(self.r_score)

        buffer = PADDLE_SIDE + PADDLE_WIDTH + 2
        r_x_position = WIDTH - FONT_WIDTH - buffer

        pyxel.text(x=buffer, y=2, s=l_score, col=COL_SCORE)
        pyxel.text(x=r_x_position, y=2, s=r_score, col=COL_SCORE)

    def draw_end_screen(self):
        """Draw the final screen with the winner!"""

        pyxel.cls(col=COL_FINISH)

        display_text = TEXT_FINISH[:]

        if self.l_score >= WIN_CONDITION:
            winner = "The LEFT player!"
        else:
            winner = "The RIGHT player!"
        display_text.insert(1, winner)
        for i, text in enumerate(display_text):
            y_offset = (FONT_HEIGHT + 2) * i
            text_x = self.center_text(text, WIDTH)
            pyxel.text(text_x, HEIGHT_FINISH + y_offset, text, COL_FINISH_TEXT)

    @staticmethod
    def center_text(text, page_width, char_width=FONT_WIDTH):
        """Helper function for calcuating the start x value for centered text."""

        text_width = len(text) * char_width
        return (page_width - text_width) // 2
Esempio n. 9
0
pygame.init()
pygame.display.set_caption("PyPong")
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
font = pygame.font.SysFont("Fira Code", 32)


def update_fps():
    fps = str(int(clock.get_fps()))
    fps_text = font.render(fps, True, pygame.Color("coral"))
    return fps_text


# init game objects
left_paddle = Paddle(32, SC_HEIGHT / 2 - 64)
right_paddle = Paddle(SC_WIDTH - 32, SC_HEIGHT / 2 - 96)
ball = Ball(SC_WIDTH / 2, SC_HEIGHT / 2)
ball.change_v(dvx=-2, dvy=2)

# game loop
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    screen.fill(cl_off_black)
    screen.blit(update_fps(), (16, 5))

    if ball.is_colliding_with(left_paddle) or left_paddle.is_colliding_with(
            ball):
Esempio n. 10
0
class Pong(object):
    def __init__(self):
        # Screen settings
        display = pygame.display.Info()
        self.screen_width = int(display.current_w / 2)
        self.screen_height = int(display.current_h / 2)

        # screen = pygame.display.set_mode([screen_width,screen_height], pygame.FULLSCREEN, 32)
        self.screen = pygame.display.set_mode(
            [self.screen_width, self.screen_height])

        # Font and images
        self.sprite = pygame.sprite.Sprite()
        image = pygame.image.load("seznam_icon.png")
        scaled_image = pygame.transform.smoothscale(
            image, (BALL_WIDTH, BALL_HEIGHT))  # or scale
        self.sprite.image = scaled_image
        self.sprite.rect = self.sprite.image.get_rect()
        self.sprite.rect.topleft = (int(self.screen_width / 2) - 32,
                                    random.randint(0, self.screen_height) - 32
                                    )  # Place the ball somewhere in the middle

        # State
        self.state = {
            'player1': {
                'score': 0,
                'moving_up': False,
                'moving_down': False,
                'movement_speed': 6
            },
            'player2': {
                'score': 0,
                'moving_up': False,
                'moving_down': False,
                'movement_speed': 6
            }
        }

        self.clock = pygame.time.Clock()

        # Initialize game objects
        self._initialize_game_objects()

    def _compute_player_pods_initial_positions(self):
        position1 = (POD_OFFSET,
                     int(self.screen.get_height() / 2) - int(POD_HEIGHT / 2))
        position2 = (self.screen.get_width() - (POD_WIDTH + POD_OFFSET),
                     int(self.screen.get_height() / 2) - int(POD_HEIGHT / 2))
        return position1, position2

    def _compute_player_score_positions(self):
        position1 = (int(self.screen.get_width() / 4) - int(SCORE_WIDTH / 2),
                     int(self.screen.get_height() / 2) - int(SCORE_HEIGHT / 2))
        position2 = (int(self.screen.get_width() / 4) * 3 -
                     int(SCORE_WIDTH / 2),
                     int(self.screen.get_height() / 2) - int(SCORE_HEIGHT / 2))
        return position1, position2

    def _initialize_game_objects(self):
        self.screen.fill(BLACK)
        self.line = MiddleLine(GREY, self.screen,
                               (int(self.screen_width / 2), 0), 1,
                               self.screen_height)
        pod_player1_position, pod_player2_position = self._compute_player_pods_initial_positions(
        )
        self.pod_player1 = Paddle('seznam_logo.png', self.screen,
                                  pod_player1_position, POD_WIDTH, POD_HEIGHT)
        self.pod_player2 = Paddle('seznam_logo.png', self.screen,
                                  pod_player2_position, POD_WIDTH, POD_HEIGHT)
        score_player1_position, score_player2_position = self._compute_player_score_positions(
        )
        self.score_player1 = Score(self.state['player1']['score'],
                                   DARK_GREY,
                                   self.screen,
                                   score_player1_position,
                                   width=SCORE_WIDTH,
                                   heigth=SCORE_HEIGHT)
        self.score_player2 = Score(self.state['player2']['score'],
                                   DARK_GREY,
                                   self.screen,
                                   score_player2_position,
                                   width=SCORE_WIDTH,
                                   heigth=SCORE_HEIGHT)
        self.frame = Frame(WHITE,
                           self.screen, (0, 0),
                           self.screen_width,
                           self.screen_height,
                           border=1)
        self.ball = Ball([5, 5],
                         'seznam_icon.png',
                         self.screen,
                         width=BALL_WIDTH,
                         height=BALL_HEIGHT)
        pygame.display.flip()

    def generate_random_color(self):
        return random.randint(0, 255), random.randint(0, 255), random.randint(
            0, 255)

    def run(self):
        running = True
        while running:
            # Reset playground
            self.screen.fill(BLACK)
            self.line.render()
            self.frame.render()
            self.score_player1.render()
            self.score_player2.render()

            # Movement
            #
            # Because we move on the Y axis, we have to have "reversed" movement.
            if self.state['player1']['moving_up']:
                self.pod_player1.move(0,
                                      -self.state['player1']['movement_speed'],
                                      increment=True)
            if self.state['player1']['moving_down']:
                self.pod_player1.move(0,
                                      self.state['player1']['movement_speed'],
                                      increment=True)
            if self.state['player2']['moving_up']:
                self.pod_player2.move(0,
                                      -self.state['player2']['movement_speed'],
                                      increment=True)
            if self.state['player2']['moving_down']:
                self.pod_player2.move(0,
                                      self.state['player2']['movement_speed'],
                                      increment=True)

            # Events
            for event in pygame.event.get():
                # Cant quit on an event or when Escape button is pressed.
                if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN
                                                 and event.key
                                                 == pygame.K_ESCAPE):
                    running = False

                # Actions
                if event.type == pygame.KEYDOWN and event.key == Q_BUTTON:
                    self.state['player1']['moving_up'] = True
                    self.state['player1']['moving_down'] = False
                if event.type == pygame.KEYDOWN and event.key == UP_BUTTON:
                    self.state['player2']['moving_up'] = True
                    self.state['player2']['moving_down'] = False
                if event.type == pygame.KEYDOWN and event.key == A_BUTTON:
                    self.state['player1']['moving_up'] = False
                    self.state['player1']['moving_down'] = True
                if event.type == pygame.KEYDOWN and event.key == DOWN_BUTTON:
                    self.state['player2']['moving_up'] = False
                    self.state['player2']['moving_down'] = True
                if event.type == pygame.KEYUP and event.key in (A_BUTTON,
                                                                Q_BUTTON):
                    self.state['player1']['moving_up'] = False
                    self.state['player1']['moving_down'] = False
                if event.type == pygame.KEYUP and event.key in (UP_BUTTON,
                                                                DOWN_BUTTON):
                    self.state['player2']['moving_up'] = False
                    self.state['player2']['moving_down'] = False

            # Player pads
            self.pod_player1.render()
            self.pod_player2.render()

            # Move the ball
            try:
                self.ball.render([self.pod_player1, self.pod_player2])
            except GameOverException as e:
                # Change the score
                self.state[e.winning_player_info]['score'] += 1

                # Reset the playground
                self._initialize_game_objects()
                continue
            pygame.display.flip()

            self.clock.tick(60)  # 60 FPS

        pygame.quit()