Example #1
0
    def __init__(self, size):
        self.background = pygame.Surface(size)  # make a background surface
        self.background = self.background.convert()
        self.background.fill((0, 0, 0))

        font = pygame.font.Font(None, 40)

        self.score = Score(font)

        self.walls = [Wall((10, 10), (790, 20)), Wall((10, 580), (790, 590))]

        self.bats = []

        control_scheme_1 = ControlScheme()
        control_scheme_1.up = K_w
        control_scheme_1.down = K_s

        control_scheme_2 = ControlScheme()
        control_scheme_2.up = K_UP
        control_scheme_2.down = K_DOWN

        self.bats.append(Bat((10, 200), control_scheme_1))
        self.bats.append(Bat((780, 200), control_scheme_2))

        self.ball = Ball((400, 300))
Example #2
0
    def __init__(self):
        self.high = np.array([1.1, 1.1, 0.85, 1.03, 1.03])
        self.low = np.array([-1.1, -1.1, -0.01, -0.04, -0.04])

        self.WIDTH = world_settings["WIDTH"]
        self.HEIGHT = world_settings["HEIGHT"]

        self.display_render = False
        self.game_over = False

        self.player = Player(
            self,
            random.randint(0, self.WIDTH -
                           player_setting["width"]),  #Randon position x 
            self.HEIGHT - player_setting["height"] -
            player_setting["padding"],  #position bottom
        )
        self.autoplayer = Player(
            self,
            random.randint(0, self.WIDTH -
                           player_setting["width"]),  #Randon position x 
            player_setting["height"] -
            player_setting["padding"],  #position top
        )
        self.ball = Ball(
            self,
            random.randint(16, self.WIDTH - 16),
            self.HEIGHT / 2 - 8,
            [self.player, self.autoplayer]  #Interact with
        )
        self.clock = pg.time.Clock()
Example #3
0
 def __init__(self, window: Window):
     super().__init__(window)
     self.all_sprites = Group()
     self.goals = Group()
     self.pads = Group()
     self.borders = Group()
     self.ball = Ball(yellow, 10)
     self.all_sprites.add(Net())
     self.all_sprites.add(self.ball)
Example #4
0
def main(screen):

    # create the cast {key: tag, value: list}
    cast = {}

    x = int(constants.MAX_X / 2)
    y = int(constants.MAX_Y - 1)
    position = Point(x, y)
    paddle = Player()
    paddle.set_position(position)
    cast["paddle"] = [paddle]

    cast["brick"] = []
    for x in range(5, 75):
        for y in range(2, 6):
            position = Point(x, y)
            brick = Brick()
            brick.set_text("*")
            brick.set_position(position)
            cast["brick"].append(brick)

    x = int(constants.MAX_X / 2)
    y = int(constants.MAX_Y / 2)
    position = Point(x, y)
    velocity = Point(1, -1)
    ball = Ball()
    ball.set_text("@")
    ball.set_position(position)
    ball.set_starting_position(position)
    ball.set_velocity(velocity)
    cast["ball"] = [ball]
    score = Score()
    score.set_position(Point(4, 0))
    cast["score"] = [score]
    lives = Lives()
    lives.set_position(Point(67, 0))
    cast["lives"] = [lives]

    # create the script {key: tag, value: list}
    script = {}

    input_service = InputService(screen)
    output_service = OutputService(screen)
    control_actors_action = ControlActorsAction(input_service)
    move_actors_action = MoveActorsAction()
    handle_collisions_acition = HandleCollisionsAction()
    draw_actors_action = DrawActorsAction(output_service)

    script["input"] = [control_actors_action]
    script["update"] = [move_actors_action, handle_collisions_acition]
    script["output"] = [draw_actors_action]

    # start the game
    director = Director(cast, script)
    director.start_game()
Example #5
0
class GameWindow(pyglet.window.Window):
    def __init__(self):
        super().__init__(800, 600)

        self.batch = pyglet.graphics.Batch()
        self.keys = key.KeyStateHandler()
        self.push_handlers(self.keys)

        self.paddle_left = Paddle((50, 50, 30, 180), self.batch)
        self.paddle_right = Paddle((self.width - 80, 50, 30, 180), self.batch)

        self.ball = Ball((self.width//2, self.height//2, 25, 25), self.batch)
        self.ball.velocity_x = -200
        self.ball.velocity_y = -200

    def on_draw(self):
        """ Called each frame, Clears screen and draws objects & lines """
        self.clear()
        self.batch.draw()

        # Lines for debugging
        pyglet.graphics.draw(2, pyglet.gl.GL_LINES, ('v2i', (0, 20, self.width, 20)))
        pyglet.graphics.draw(2, pyglet.gl.GL_LINES, ('v2i', (20, 0, 20, self.height)))
        pyglet.graphics.draw(2, pyglet.gl.GL_LINES, ('v2i', (0, 580, self.width, 580)))
        pyglet.graphics.draw(2, pyglet.gl.GL_LINES, ('v2i', (780, 0, 780, self.height)))

    def update(self, dt):
        # Input handling
        if self.keys[key.UP]:
            self.paddle_left.velocity_y = 200
        elif self.keys[key.DOWN]:
            self.paddle_left.velocity_y = -200
        else:
            self.paddle_left.velocity_y = 0

        # Right paddle AI
        self.paddle_right.move_paddle(self.ball)

        # Ball/paddle collision logic
        if self.ball.does_collide(self.paddle_left) or \
                self.ball.does_collide(self.paddle_right):
            self.ball.velocity_x = self.ball.velocity_x * -1

        self.paddle_left.update(dt)
        self.paddle_right.update(dt)
        self.ball.update(dt)
Example #6
0
class PongGame:
    def __init__(self, size):
        self.background = pygame.Surface(size)  # make a background surface
        self.background = self.background.convert()
        self.background.fill((0, 0, 0))

        font = pygame.font.Font(None, 40)

        self.score = Score(font)

        self.walls = [Wall((10, 10), (790, 20)), Wall((10, 580), (790, 590))]

        self.bats = []

        control_scheme_1 = ControlScheme()
        control_scheme_1.up = K_w
        control_scheme_1.down = K_s

        control_scheme_2 = ControlScheme()
        control_scheme_2.up = K_UP
        control_scheme_2.down = K_DOWN

        self.bats.append(Bat((10, 200), control_scheme_1))
        self.bats.append(Bat((780, 200), control_scheme_2))

        self.ball = Ball((400, 300))

    def process_event(self, event):
        for bat in self.bats:
            bat.process_event(event)

    def update(self, time_delta):
        for bat in self.bats:
            bat.update(time_delta)

        self.ball.update(time_delta, self.bats, self.walls)

        if self.ball.position[0] < 0:
            self.ball.reset()
            self.score.increase_player_2_score()
        elif self.ball.position[0] > 800:
            self.ball.reset()
            self.score.increase_player_1_score()

    def draw(self, surface):
        surface.blit(self.background, (0, 0))

        for wall in self.walls:
            wall.render(surface)

        for bat in self.bats:
            bat.render(surface)

        self.ball.render(surface)
        self.score.render(surface)
Example #7
0
 def setUp(self) -> None:
     ball = Ball(pong.config.white, 10)
     engine = ComputerControlEngine(ball)
     self.left_player = Player('left', 'left', engine)
     self.right_player = Player('right', 'right', engine)
     self.score_manager = ScoreManager(self.left_player, self.right_player,
                                       (1, 5))
     self.score_board = ScoreBoard(self.score_manager)
     self.scene = Scene(Window(100, 100, 'Test'))
Example #8
0
 def __init__(self, port1, port2):
     pg.init()
     self.state = game_utils.IN_MENU
     # INIT BUTTONS
     self.game_btn = GameButton(0, "START GAME", self)
     self.opt_btn = OptionsButton(1, "OPTIONS", self)
     self.exit_btn = ExitButton(2, "EXIT", self)
     self.cal_btn = CalibrateButton(0, "CALIBRATE", self)
     self.music_btn = MusicButton(1, "MUSIC ON", self)
     self.back_btn = BackButton(2, "BACK", self)
     # self.player_blue = PlayerPad('LEFT', None, self)
     self.player_blue = PlayerPad('LEFT', port1, self)
     # self.player_red = PlayerPad('RIGHT', port2, self)
     self.ball = Ball(game_utils.BALL_X, game_utils.BALL_Y)
     self.music = True
     self.clock = pg.time.Clock()
     self.display = pg.display.set_mode(
         (game_utils.B_WIDTH, game_utils.B_HEIGHT))
     pg.display.set_caption('Pressure Project v1.0')
Example #9
0
    def from_config(cls, config, player_position_generator):
        ball = Ball.from_config(config)
        home_team = Team.from_config(config)
        away_team = Team.from_config(config)
        home_goal = Goal.from_config(config)
        away_goal = Goal.from_config(config)
        away_goal.position = -away_goal.position
        field = Field.from_config(config)
        duration = config["duration"]
        friction = config["friction"]

        return Game(ball, home_team, away_team, home_goal, away_goal, field, duration, friction, player_position_generator)
Example #10
0
    def __init__(self):
        super().__init__(800, 600)

        self.batch = pyglet.graphics.Batch()
        self.keys = key.KeyStateHandler()
        self.push_handlers(self.keys)

        self.paddle_left = Paddle((50, 50, 30, 180), self.batch)
        self.paddle_right = Paddle((self.width - 80, 50, 30, 180), self.batch)

        self.ball = Ball((self.width//2, self.height//2, 25, 25), self.batch)
        self.ball.velocity_x = -200
        self.ball.velocity_y = -200
Example #11
0
 def setUp(self) -> None:
     super().setUp()
     self.ball = Ball((100, 100, 100), 10)
Example #12
0
class TestBall(TestCase):
    def setUp(self) -> None:
        super().setUp()
        self.ball = Ball((100, 100, 100), 10)

    def test_bounce_with_right_pad(self):
        self.ball.dx = 1
        self.ball.dy = 1

        self.ball.bounce_with_pad()

        self.assertEqual(-1, self.ball.dx)
        self.assertEqual(1, self.ball.dy)

    def test_bounce_with_left_pad(self):
        self.ball.dx = -1
        self.ball.dy = 1

        self.ball.bounce_with_pad()

        self.assertEqual(1, self.ball.dx)
        self.assertEqual(1, self.ball.dy)

    def test_bounce_in_central_right_pad_region_resets_speed(self):
        self.ball.dx = 2
        self.ball.dy = 2

        self.ball.bounce_with_pad()

        self.assertEqual(-1, self.ball.dx)
        self.assertEqual(1, self.ball.dy)

    def test_bounce_in_central_left_pad_region_resets_speed(self):
        self.ball.dx = -2
        self.ball.dy = -2

        self.ball.bounce_with_pad()

        self.assertEqual(1, self.ball.dx)
        self.assertEqual(-1, self.ball.dy)

    def test_bounce_with_border_top(self):
        self.ball.dx = 1
        self.ball.dy = -1

        self.ball.bounce_with_border()

        self.assertEqual(1, self.ball.dy)
        self.assertEqual(1, self.ball.dx)

    def test_bounce_with_border_bottom(self):
        self.ball.dx = 1
        self.ball.dy = 1

        self.ball.bounce_with_border()

        self.assertEqual(-1, self.ball.dy)
        self.assertEqual(1, self.ball.dx)
Example #13
0
 def test_win_set(self):
     ball = Ball(pong.config.white, 10)
     engine = ComputerControlEngine(ball)
     self.player = Player('left', 'left', engine)
     self.player.win_set()
     self.assertEqual(1, self.player.sets())
Example #14
0
import pygame
import sys

from game.ball import Ball
from game.paddle import Paddle

pygame.init()

size = width, height = 640, 480
speed = [1, 1]
black = 0, 0, 0

screen = pygame.display.set_mode(size)

ball = Ball()

paddle1 = Paddle(pygame.K_w, pygame.K_s)
paddle2 = Paddle(pygame.K_UP, pygame.K_DOWN, width - 20, 1)
actors = [paddle1, paddle2, ball]

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()
        elif event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
            for x in actors:
                x.handle_event(event)

    screen.fill(black)
    ball.check_collision(paddle2)
    ball.check_collision(paddle1)
    for x in actors:
Example #15
0
 def preparePlayer():
     ball = Ball(pong.config.white, 10)
     engine = ComputerControlEngine(ball)
     return Player('left', 'left', engine)
Example #16
0
class GameScene(Scene):
    def __init__(self, window: Window):
        super().__init__(window)
        self.all_sprites = Group()
        self.goals = Group()
        self.pads = Group()
        self.borders = Group()
        self.ball = Ball(yellow, 10)
        self.all_sprites.add(Net())
        self.all_sprites.add(self.ball)

    def run(self):

        self.prepare_borders()

        player_one_side = 'left'
        player_two_side = 'right'
        player_one_speed = self.window.game.human_speed
        player_two_speed = self.window.game.human_speed
        player_one_engine = self.player_engine(left_keys)
        player_two_engine = self.player_engine(right_keys)

        if self.window.game.game_mode == 1:
            player_one_side = self.window.game_side()
            if player_one_side == 'left':
                player_two_side = 'right'
            else:
                player_two_side = 'left'
            player_one_speed = self.window.game.human_speed
            player_two_speed = self.window.game.computer_speed
            player_two_engine = self.player_engine(())
        elif self.window.game.game_mode == 0:
            player_one_speed = self.window.game.computer_speed
            player_two_speed = self.window.game.computer_speed
            player_one_engine = self.player_engine(())
            player_two_engine = self.player_engine(())

        player_one = Player('human', player_one_side, player_one_engine, player_one_speed)
        player_two = Player('computer', player_two_side, player_two_engine, player_two_speed)

        self.window.score_manager = ScoreManager(
            match=(3, POINTS_TO_WIN),
            player_one=player_one,
            player_two=player_two
        )
        self.window.score_board = ScoreBoard(self.window.score_manager)

        player_one.pad.borders = self.borders
        player_two.pad.borders = self.borders

        self.all_sprites.add(player_one.goal)
        self.all_sprites.add(player_two.goal)

        self.goals.add(player_one.goal)
        self.goals.add(player_two.goal)

        self.all_sprites.add(player_one.pad)
        self.all_sprites.add(player_two.pad)

        self.pads.add(player_one.pad)
        self.pads.add(player_two.pad)

        self.ball.pads = self.pads
        self.ball.borders = self.borders
        self.ball.goals = self.goals

        # Game loop
        clock = Clock()
        pygame.time.set_timer(COMPUTER_MOVES_EVENT, COMPUTER_MOVES_TIMER_MS)
        end_of_match = False

        while not end_of_match:

            end_of_set = False
            while not end_of_set:
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        end_of_match = True
                        break
                    player_one.handle(event)
                    player_two.handle(event)

                pygame.event.pump()
                self.all_sprites.update()

                # Manage goals
                self.ball.manage_goals()

                # Game draw
                self.window.screen.fill(green)
                self.window.score_board.draw(self)
                self.all_sprites.draw(self.window.screen)

                # Screen update
                pygame.display.flip()

                if self.window.score_manager.end_of_set():
                    end_of_set = True
                    self.window.score_manager.end_set()
                    self.window.score_manager.new_set()

                    if self.window.score_manager.end_of_game():
                        end_of_match = True

                clock.tick(FPS)
        return 0

    def player_engine_for_second_player(self, keys):
        if self.window.game.game_mode == 1 or self.window.game.game_mode == 0:
            return ComputerControlEngine(self.ball)

        return KeyboardControlEngine(keys)

    def player_engine(self, keys):
        if len(keys) == 0:
            return ComputerControlEngine(self.ball)

        return KeyboardControlEngine(keys)

    def prepare_borders(self):
        border_top = Border(0)
        border_bottom = Border(590)
        self.all_sprites.add(border_top)
        self.all_sprites.add(border_bottom)
        self.borders.add(border_top)
        self.borders.add(border_bottom)
Example #17
0
class CustomEnv:
    def __init__(self):
        self.high = np.array([1.1, 1.1, 0.85, 1.03, 1.03])
        self.low = np.array([-1.1, -1.1, -0.01, -0.04, -0.04])

        self.WIDTH = world_settings["WIDTH"]
        self.HEIGHT = world_settings["HEIGHT"]

        self.display_render = False
        self.game_over = False

        self.player = Player(
            self,
            random.randint(0, self.WIDTH -
                           player_setting["width"]),  #Randon position x 
            self.HEIGHT - player_setting["height"] -
            player_setting["padding"],  #position bottom
        )
        self.autoplayer = Player(
            self,
            random.randint(0, self.WIDTH -
                           player_setting["width"]),  #Randon position x 
            player_setting["height"] -
            player_setting["padding"],  #position top
        )
        self.ball = Ball(
            self,
            random.randint(16, self.WIDTH - 16),
            self.HEIGHT / 2 - 8,
            [self.player, self.autoplayer]  #Interact with
        )
        self.clock = pg.time.Clock()

    def return_observation(self):
        return [
            self.ball.vector["x"], self.ball.vector["y"],
            self.player.x / self.WIDTH, self.ball.x / self.WIDTH,
            self.ball.y / self.HEIGHT
        ]

    def reset(self):
        self.__init__()
        return self.return_observation()

    def step(self, action):
        self.ball.update()  #Upgrade positon ball
        self.ball.speed += 0.001  #Acceleration
        self.player.move(action -
                         1)  #action happens input (0, 1, 2) - 1 = (-1, 0, 1)
        self.autoplayer.auto(self.ball)  #Auto move bot
        return self.return_observation(), self.player.score, self.game_over

    def render(self, FPS):
        if not self.display_render:
            self.display = pg.display.set_mode((self.WIDTH, self.HEIGHT))
            self.display_render = True
        pg.event.get()
        pg.display.update()
        self.display.fill((0, 0, 0))
        self.ball.draw()
        self.player.draw()
        self.autoplayer.draw()
        self.clock.tick(FPS)
Example #18
0
class Board:
    """Description: game board contains main gui and game widgets"""
    def __init__(self, port1, port2):
        pg.init()
        self.state = game_utils.IN_MENU
        # INIT BUTTONS
        self.game_btn = GameButton(0, "START GAME", self)
        self.opt_btn = OptionsButton(1, "OPTIONS", self)
        self.exit_btn = ExitButton(2, "EXIT", self)
        self.cal_btn = CalibrateButton(0, "CALIBRATE", self)
        self.music_btn = MusicButton(1, "MUSIC ON", self)
        self.back_btn = BackButton(2, "BACK", self)
        # self.player_blue = PlayerPad('LEFT', None, self)
        self.player_blue = PlayerPad('LEFT', port1, self)
        # self.player_red = PlayerPad('RIGHT', port2, self)
        self.ball = Ball(game_utils.BALL_X, game_utils.BALL_Y)
        self.music = True
        self.clock = pg.time.Clock()
        self.display = pg.display.set_mode(
            (game_utils.B_WIDTH, game_utils.B_HEIGHT))
        pg.display.set_caption('Pressure Project v1.0')

    def run(self):
        """Description: method contains board logic running in a loop"""

        while self.state != game_utils.EXIT:
            for event in pg.event.get():
                self.check_for_events(event)
            if self.state != game_utils.EXIT:
                # BEGIN CAL
                self.draw_calibration_messages()
                # MENU
                self.menu_loop()
                # GAME
                self.game_loop()
            pg.display.flip()
            self.clock.tick(game_utils.FPS)
        # clean exit
        pg.quit()
        sys.exit(0)

    def check_for_events(self, event):
        """Description: method check for event happened on the board
        :param: Pygame event
        """
        def check_key_event():
            """Description: function checks event for key press"""
            def check_key_testing():
                """Description: function check events for testing purposes"""
                if (event.key == K_w) and (self.state == game_utils.IN_GAME):
                    self.player_blue.keyPressed = True
                    self.player_blue.direction = "UP"
                elif (event.key == K_s) and (self.state == game_utils.IN_GAME):
                    self.player_blue.keyPressed = True
                    self.player_blue.direction = "DOWN"

            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    if self.state != game_utils.IN_MENU:
                        self.state = game_utils.IN_MENU
                elif (event.key == K_RETURN) or (event.key == K_KP_ENTER):
                    if (self.state == game_utils.IN_GAME_CAL) or\
                            (self.state == game_utils.IN_MENU_CAL):
                        # self.player_blue.calibrate_device()
                        if self.state == game_utils.IN_GAME_CAL:
                            self.state = game_utils.CAL_MIN
                        elif self.state == game_utils.IN_MENU_CAL:
                            self.state = game_utils.IN_OPTIONS
                    elif self.state == game_utils.CAL_MIN:
                        self.begin_calibration_cycle()
                        self.state = game_utils.CAL_MAX
                    elif self.state == game_utils.CAL_MAX:
                        self.begin_calibration_cycle()
                        self.state = game_utils.IN_GAME
                else:
                    check_key_testing()
            elif event.type == KEYUP:
                if (event.key == K_w) and (self.state == game_utils.IN_GAME):
                    self.player_blue.keyPressed = False
                elif (event.key == K_s) and (self.state == game_utils.IN_GAME):
                    self.player_blue.keyPressed = False

        # --------------------
        if event.type == QUIT:
            self.state = game_utils.EXIT
        elif event.type == MOUSEBUTTONUP:
            if self.state == game_utils.IN_MENU:
                self.check_menu_events(pg.mouse.get_pos())
            elif self.state == game_utils.IN_OPTIONS:
                self.check_options_events(pg.mouse.get_pos())
        else:
            check_key_event()

    def game_loop(self):
        """Description: method contains game logic sequence"""

        # GAME LOOP
        if self.state == game_utils.IN_GAME:
            # game logic
            self.display.fill(game_utils.WHITE)
            self.draw_board()
            self.draw_scores()
            self.player_blue.move()
            # self.pRed.move()
            # -- For testing --
            # self.player_blue.move_key()
            # -----------------
            self.ball.move(self.player_blue)
            self.player_blue.update(self.display)
            # self.pRed.update(self.display)
            self.ball.update(self.display)

    def menu_loop(self):
        """Description: method contains menu logic sequence"""

        if (self.state == game_utils.IN_MENU) or (self.state
                                                  == game_utils.IN_OPTIONS):
            self.display.fill(game_utils.LIGHT_BLUE)
            self.draw_authors()
            self.draw_header()
            self.draw_images()
        if self.state == game_utils.IN_MENU:
            self.draw_menu_buttons()
        elif self.state == game_utils.IN_OPTIONS:
            self.draw_options_buttons()

    def begin_calibration_cycle(self):
        """Description: method start player device calibration"""

        if self.state == game_utils.CAL_MIN:
            self.player_blue.calibrate_min()
            # self.pRed.calibrate_min()
        elif self.state == game_utils.CAL_MAX:
            self.player_blue.calibrate_max()
            # self.pRed.calibrate_max()

    def draw_board(self):
        """Description: method draws basic game board structure"""

        pg.draw.rect(self.display, game_utils.BLACK,
                     (0, 0, game_utils.B_WIDTH, game_utils.B_HEIGHT),
                     game_utils.CAGE_WIDTH)
        pg.draw.line(self.display, game_utils.BLACK,
                     (int(game_utils.B_WIDTH / 2 - 2), 0),
                     (int(game_utils.B_WIDTH / 2 - 2), game_utils.B_HEIGHT), 4)

    def draw_images(self):
        """Description: method draws images on the board"""

        logo_rect = game_utils.LOGO.get_rect()
        logo_rect.center = (game_utils.B_WIDTH - 45, game_utils.B_HEIGHT - 45)
        self.display.blit(game_utils.LOGO, logo_rect)

    def draw_scores(self):
        """Description: method draws player scores on the board"""

        size = int(game_utils.B_HEIGHT * .1)
        font = pg.font.Font(game_utils.ARCADE_FONT, size)
        score1 = font.render(str(self.player_blue.score), True,
                             game_utils.BLACK)
        # score2 = font.render(str(self.pRed.score), True, game_utils.BLACK)
        rect1 = score1.get_rect()
        # rect2 = score2.get_rect()
        rect1.topright = (int(game_utils.B_WIDTH / 2) - 10,
                          game_utils.OFFSET_HEIGHT)
        # rect2.topleft = (int(game_utils.B_WIDTH/2)-10, game_utils.OFFSET_HEIGHT)
        self.display.blit(score1, rect1)
        # self.display.blit(score2, rect2)

    def draw_menu_buttons(self):
        """Description: method draws main menu buttons"""

        pg.draw.rect(self.display, self.game_btn.color,
                     self.game_btn.get_rect(), 0)
        self.display.blit(self.game_btn.text, self.game_btn.get_text_rect())

        pg.draw.rect(self.display, self.opt_btn.color, self.opt_btn.get_rect(),
                     0)
        self.display.blit(self.opt_btn.text, self.opt_btn.get_text_rect())

        pg.draw.rect(self.display, self.exit_btn.color,
                     self.exit_btn.get_rect(), 0)
        self.display.blit(self.exit_btn.text, self.exit_btn.get_text_rect())

    def draw_options_buttons(self):
        """Description: method draws options menu buttons"""

        pg.draw.rect(self.display, self.cal_btn.color, self.cal_btn.get_rect(),
                     0)
        self.display.blit(self.cal_btn.text, self.cal_btn.get_text_rect())

        pg.draw.rect(self.display, self.music_btn.color,
                     self.music_btn.get_rect(), 0)
        self.display.blit(self.music_btn.text, self.music_btn.get_text_rect())

        pg.draw.rect(self.display, self.back_btn.color,
                     self.back_btn.get_rect(), 0)
        self.display.blit(self.back_btn.text, self.back_btn.get_text_rect())

    def check_menu_events(self, pos):
        """Description: method checks menu buttons events
        :param: Mouse position
        """

        if self.game_btn.get_rect().collidepoint(pos) == 1:
            self.game_btn.on_click()
        elif self.opt_btn.get_rect().collidepoint(pos) == 1:
            self.opt_btn.on_click()
        elif self.exit_btn.get_rect().collidepoint(pos) == 1:
            self.exit_btn.on_click()

    def check_options_events(self, pos):
        """Description: method checks options menu events
        :param: Mouse position
        """

        if self.cal_btn.get_rect().collidepoint(pos) == 1:
            self.cal_btn.on_click()
        elif self.music_btn.get_rect().collidepoint(pos) == 1:
            self.music_btn.on_click()
        elif self.back_btn.get_rect().collidepoint(pos) == 1:
            self.back_btn.on_click()

    def draw_header(self):
        """Description: method draws board header"""

        font = pg.font.Font(game_utils.ARCADE_FONT,
                            int(game_utils.B_HEIGHT * 0.22))
        text = font.render("SENSOR  PONG", True, game_utils.WHITE)
        text_rect = text.get_rect()
        text_rect.center = (int(game_utils.B_WIDTH / 2),
                            int(game_utils.B_HEIGHT * 0.2))
        self.display.blit(text, text_rect)

    def draw_authors(self):
        """Description: method draws authors"""

        size = int(game_utils.B_HEIGHT * .045)
        font = pg.font.Font(game_utils.ARCADE_FONT, size)
        text = "BHGE  PiCoding  Club"
        text = font.render(text, True, game_utils.WHITE)
        text_rect = text.get_rect()
        text_rect.bottomleft = (25, int(game_utils.B_HEIGHT * 0.92))
        self.display.blit(text, text_rect)

    def draw_calibration_messages(self):
        """Description: method draws calibration messages"""
        def display_print(text_size, msg, pos):
            """Description: function prints messages on display
            :param: Text size
            :param: Message to print
            :param: Text position
            """

            text = font.render(msg, True, game_utils.WHITE)
            text_rect = text.get_rect()
            text_rect.center = (int(game_utils.B_WIDTH / 2),
                                int(game_utils.B_HEIGHT / 2) - text_size * pos)
            self.display.blit(text, text_rect)

        if (self.state
                == game_utils.IN_GAME_CAL) or (self.state
                                               == game_utils.IN_MENU_CAL):
            self.display.fill(game_utils.LIGHT_BLUE)
            size = int(game_utils.B_HEIGHT * .09)
            font = pg.font.Font(game_utils.ARCADE_FONT, size)
            display_print(size, "ATTENTION", 2)
            display_print(size, "HOLD   THE   SENSOR   IN", 1)
            display_print(size, "PLAYABLE   POSITION", 0)
            display_print(size, "CALIBRATION   WILL   BE", -1)
            display_print(size, "DONE  FOR  ALL  PLAYERS", -2)
            font = pg.font.Font("fonts/arcade.ttf", int(size * 0.5))
            display_print(int(size * 0.5), "Press   ENTER   to continue", -10)

        elif self.state == game_utils.CAL_MIN or self.state == game_utils.CAL_MAX:
            self.display.fill(game_utils.LIGHT_BLUE)
            size = int(game_utils.B_HEIGHT * .09)
            font = pg.font.Font(game_utils.ARCADE_FONT, size)
            display_print(int(size * 0.5), "Press   ENTER   to continue", -10)
            if self.state == game_utils.CAL_MIN:
                display_print(size, "HOLD SENSOR AT LOWER POINT", 0)
            elif self.state == game_utils.CAL_MAX:
                display_print(size, "HOLD SENSOR AT UPPER POINT", 0)
Example #19
0
 def setUp(self) -> None:
     self.ball = Ball((100, 100, 100), 10)
     self.pad = Pad('left', 1, KeyboardControlEngine(('u', 'd')))
     self.pad.rect.y = 100
Example #20
0
 def build_ball():
     return Ball(size=Size(15, 15),
                 position=Position(400, 300),
                 color=(255, 255, 255))
Example #21
0
def run_game():
    pygame.init()

    # Define some colors
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)

    # Open a new window
    size = (700, 500)
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("Pong")

    paddleA = Paddle(WHITE, 10, 100)
    paddleA.rect.x = 20
    paddleA.rect.y = 200

    paddleB = Paddle(WHITE, 10, 100)
    paddleB.rect.x = 670
    paddleB.rect.y = 200

    ball = Ball(WHITE, 10, 10)
    ball.rect.x = 345
    ball.rect.y = 195

    #This will be a list that will contain all the sprites we intend to use in our game.
    all_sprites_list = pygame.sprite.Group()

    # Add the car to the list of objects
    all_sprites_list.add(paddleA)
    all_sprites_list.add(paddleB)
    all_sprites_list.add(ball)

    # The loop will carry on until the user exit the game (e.g. clicks the close button).
    carryOn = True

    # The clock will be used to control how fast the screen updates
    clock = pygame.time.Clock()

    #Initialise player scores
    scoreA = 0
    scoreB = 0

    while carryOn:
        # --- Main event loop
        for event in pygame.event.get():  # User did something
            if event.type == pygame.QUIT:  # If user clicked close
                carryOn = False  # Flag that we are done so we exit this loop
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_x:  #Pressing the x Key will quit the game
                    carryOn = False

        #Moving the paddles when the use uses the arrow keys (player A) or "W/S" keys (player B)
        keys = pygame.key.get_pressed()
        if keys[pygame.K_w]:
            paddleA.moveUp(5)
        if keys[pygame.K_s]:
            paddleA.moveDown(5)
        if keys[pygame.K_UP]:
            paddleB.moveUp(5)
        if keys[pygame.K_DOWN]:
            paddleB.moveDown(5)

        # --- Game logic should go here
        all_sprites_list.update()

        #Check if the ball is bouncing against any of the 4 walls:
        if ball.rect.x >= 690:
            scoreA += 1
            ball.velocity[0] = -ball.velocity[0]
        if ball.rect.x <= 0:
            scoreB += 1
            ball.velocity[0] = -ball.velocity[0]
        if ball.rect.y > 490:
            ball.velocity[1] = -ball.velocity[1]
        if ball.rect.y < 0:
            ball.velocity[1] = -ball.velocity[1]

        #Detect collisions between the ball and the paddles
        if pygame.sprite.collide_mask(
                ball, paddleA) or pygame.sprite.collide_mask(ball, paddleB):
            ball.bounce()

        # --- Drawing code should go here
        # First, clear the screen to black.
        screen.fill(BLACK)
        #Draw the net
        pygame.draw.line(screen, WHITE, [349, 0], [349, 500], 5)

        #Now let's draw all the sprites in one go. (For now we only have 2 sprites!)
        all_sprites_list.draw(screen)

        #Display scores:
        font = pygame.font.Font(None, 74)
        text = font.render(str(scoreA), 1, WHITE)
        screen.blit(text, (250, 10))
        text = font.render(str(scoreB), 1, WHITE)
        screen.blit(text, (420, 10))

        # --- Go ahead and update the screen with what we've drawn.
        pygame.display.flip()

        # --- Limit to 60 frames per second
        clock.tick(60)

    #Once we have exited the main program loop we can stop the game engine:
    pygame.quit()
 def setUp(self) -> None:
     self.ball = Ball(pong.config.white, 10)
     self.engine = ComputerControlEngine(self.ball)
     self.pad = Pad('left', 1, self.engine)
     self.pad.rect.y = 100