Example #1
0
    def __init__(self, hud):
        super(GameLayer, self).__init__()
        # 添加板子和球
        self.is_on_exiting = True
        self.paddle = Paddle('images/paddle.png')
        self.add(self.paddle.sprite)
        self.ball = Ball('images/ball.png')
        self.ball.reset_position = (320, self.paddle.sprite.height + self.ball.sprite.height / 2)
        self.add(self.ball.sprite)
        # hud 用于记录,更新关卡,死亡,金币数据
        self.hud = hud
        # 生成关卡
        self.level = Level()
        self.level.levels = self.hud.levels

        self.add(self.hud.gold_hud)
        self.add(self.hud.level_hud)
        self.add(self.hud.death_hud)

        # 添加按键状态
        self.key_pressed_left = False
        self.key_pressed_right = False
        self.key_pressed_up = False
        self.key_pressed_down = False

        self.reset()

        # 定期调用 self.update 函数
        # FPS frame per second 每秒帧数
        self.schedule(self.update)
Example #2
0
    def __init__(self, line_thickness=10, speed=5):
        self.line_thickness = line_thickness
        self.speed = speed
        self.score = 0

        # Initiate variable and set starting positions
        # any future changes made within rectangles
        ball_x = int(window_width / 2 - self.line_thickness / 2)
        ball_y = int(window_height / 2 - self.line_thickness / 2)
        self.ball = Ball(ball_x, ball_y, self.line_thickness,
                         self.line_thickness, self.speed)
        self.paddles = {}
        paddle_height = 50
        paddle_width = self.line_thickness
        user_paddle_x = 20
        computer_paddle_x = window_width - paddle_width - 20

        # you
        self.paddles['user'] = Paddle(user_paddle_x, paddle_width,
                                      paddle_height)
        # computer
        self.paddles['computer'] = AutoPaddle(computer_paddle_x, paddle_width,
                                              paddle_height, self.ball,
                                              self.speed)
        self.scoreboard = Scoreboard(0)
Example #3
0
    def take(self, play_state):
        paddle = play_state.paddle

        for _ in range(2):
            b = Ball(paddle.x + paddle.width // 2 - 4, paddle.y - 8)
            settings.GAME_SOUNDS['paddle_hit'].play()

            b.vx = random.randint(-80, 80)
            b.vy = random.randint(-170, -100)
            play_state.balls.append(b)

        self.in_play = False
Example #4
0
    def __init__(self, size_=(0, 0)):
        self.size = size_
        self.bg = Color(69, 139, 116)

        self.ball = Ball()
        self.paddle = Paddle()

        brick_size = (50, 25)
        brick_colour = Color(63, 0, 127)
        self.bricks = []

        for x in range(6, self.size[0] - brick_size[0], brick_size[0] + 5):
            for y in range(25, 250, brick_size[1] + 3):
                self.bricks.append(Brick((x, y), brick_size, brick_colour))
Example #5
0
    def __init__(self, size_=(0, 0)):
        self.size = size_
        self.bg = Color(69, 139, 116)

        self.ball = Ball()
        self.paddle = Paddle()

        brick_size = (int(self.size[0] / 9), 25)
        self.bricks = [
            Brick((x, y), brick_size)
            for x in range(int(0.15 * brick_size[0]), self.size[0] -
                           brick_size[0], int(1.1 * brick_size[0]))
            for y in range(brick_size[1], 9 *
                           brick_size[1], int(1.05 * brick_size[1]))
        ]
Example #6
0
    def __init__(self, hud):
        super(GameLayer, self).__init__()
        # 添加板子和球
        self.is_on_exiting = True
        self.paddle = Paddle('images/paddle.png')
        self.add(self.paddle.sprite)
        self.ball = Ball('images/ball.png')
        self.ball.reset_position = (320, self.paddle.sprite.height + self.ball.sprite.height / 2)
        self.add(self.ball.sprite)
        # hud 用于记录,更新关卡,死亡,金币数据
        self.hud = hud
        # 生成关卡
        self.level = Level()
        self.level.levels = self.hud.levels

        self.add(self.hud.gold_hud)
        self.add(self.hud.level_hud)
        self.add(self.hud.death_hud)

        # 添加按键状态
        self.key_pressed_left = False
        self.key_pressed_right = False
        self.key_pressed_up = False
        self.key_pressed_down = False

        self.reset()

        # 定期调用 self.update 函数
        # FPS frame per second 每秒帧数
        self.schedule(self.update)
Example #7
0
 def enter(self, **params):
     self.level = params['level']
     self.paddle = params['paddle']
     self.paddle.x = settings.VIRTUAL_WIDTH//2-32
     self.paddle.y = settings.VIRTUAL_HEIGHT-32
     self.ball = Ball(
         self.paddle.x + self.paddle.width//2 - 4, self.paddle.y - 8
     )
     self.bricks = params.get('bricks', create_level(self.level))
     self.score = params.get('score', 0)
     self.lives = params.get('lives', 3)
     self.broken_bricks_counter = params.get('broken_bricks_counter', 0)
     self.live_factor = params.get('live_factor', 1)
     self.points_to_next_live = params.get(
         'points_to_next_live', settings.LIVE_POINTS_BASE
     )
Example #8
0
    def join(self, old_state=None):
        if old_state == 'menu':

            self.ball = Ball((100,100,100))
            self.player = Paddle((100,100,100), 20, self.HEIGHT/2, 1)
            self.opponent = Paddle((100,100,100), self.WIDTH - 20, self.HEIGHT/2, 2)

            self.all_sprites = pygame.sprite.Group()
            self.all_sprites.add(self.ball, self.player, self.opponent)
Example #9
0
    def __init__(self, size_=(0, 0)):
        self.size = size_
        self.bg = Color(69, 139, 116)
        #Week 12 additions
        self.bg_won = Color(50, 200, 255)
        self.bg_lost = Color(255, 0, 0)
        self.game_over = False
        self.ball_out = False
        self.game_won = False
        #Week 12 additions end

        self.ball = Ball()
        self.paddle = Paddle()

        brick_size = (50, 25)
        brick_colour = Color(63, 0, 127)
        self.bricks = []

        for x in range(6, self.size[0] - brick_size[0], brick_size[0] + 5):
            for y in range(25, 250, brick_size[1] + 3):
                self.bricks.append(Brick((x, y), brick_size, brick_colour))
Example #10
0
class IntroScreen():
    def __init__(self, size_ = (0, 0)):
        self.size = size_
        self.bg = Color(69, 139, 116)

        self.ball = Ball()
        self.paddle = Paddle()
        
    def update(self, delta_ms):
        self.ball.update(delta_ms)
        self.paddle.update(delta_ms)

    def render(self):
        from engine.game_env import Game
        Game.get_surface().fill(self.bg)

        self.ball.render()
        self.paddle.render()
        
    def resize(self, new_size):
        self.size = new_size
Example #11
0
    def __init__(self, levels=1, golds=0, deadcount=0):
        super(GameLayer, self).__init__()
        # 添加板子和球

        self.paddle = Paddle('images/paddle.png')
        self.add(self.paddle.sprite)
        self.ball = Ball('images/ball.png')
        self.ball.reset_position = (320, self.paddle.sprite.height + self.ball.sprite.height/2)
        self.add(self.ball.sprite)
        # 生成关卡
        self.level = Level()
        self.level.levels = levels
        # 添加标签用于记录金币和关卡。死亡次数
        self.gold = golds
        self.deadcount = deadcount

        self.hud = Label('金币: '+str(golds))
        self.level_hud = Label('关卡: '+str(levels))
        self.deadstu = Label('死亡: '+str(deadcount))

        self.hud.position = (0, 460)
        self.level_hud.position = (80, 460)
        self.deadstu.position = (160, 460)
        self.add(self.hud)
        self.add(self.level_hud)
        self.add(self.deadstu)

        # 添加按键状态
        self.key_pressed_left = False
        self.key_pressed_right = False
        self.key_pressed_up = False
        self.key_pressed_down = False

        self.blocks = []
        self.reset()

        # 定期调用 self.update 函数
        # FPS frame per second 每秒帧数
        self.schedule(self.update)
Example #12
0
    def create_entities(self):
        screen = Screen(self.get_width(), self.get_height())
        screen.fill_screen((0, 0, 0))

        mid_line = pygame.Surface((5, self.get_height()))
        mid_line.fill((255, 255, 255))

        count_down_font = pygame.font.SysFont("Comic Sans MS", 100)
        player_one_score = 0
        player_two_score = 0

        screen = Screen(self.get_width(), self.get_height())
        screen.fill_screen((0, 0, 0))

        mid_line = pygame.Surface((5, self.get_height()))
        mid_line.fill((255, 255, 255))

        ball = Ball(screen.screen, 10)

        paddle_one = Paddle(screen, 20, 50)
        paddle_two = Paddle(screen, 960, 50)

        entities = {
            "screen": screen,
            "paddle_one": paddle_one,
            "paddle_two": paddle_two,
            "ball": ball,
            "player_one_score": player_one_score,
            "player_two_score": player_two_score,
            "mid_line": mid_line,
            "width": self.get_width(),
            "height": self.get_height(),
            "count_down_font": count_down_font
        }

        return entities
Example #13
0
class ServeState(BaseState):
    def enter(self, **params):
        self.level = params['level']
        self.paddle = params['paddle']
        self.paddle.x = settings.VIRTUAL_WIDTH//2-32
        self.paddle.y = settings.VIRTUAL_HEIGHT-32
        self.ball = Ball(
            self.paddle.x + self.paddle.width//2 - 4, self.paddle.y - 8
        )
        self.bricks = params.get('bricks', create_level(self.level))
        self.score = params.get('score', 0)
        self.lives = params.get('lives', 3)
        self.broken_bricks_counter = params.get('broken_bricks_counter', 0)
        self.live_factor = params.get('live_factor', 1)
        self.points_to_next_live = params.get(
            'points_to_next_live', settings.LIVE_POINTS_BASE
        )

    def update(self, dt):
        if settings.pressed_keys.get(pygame.K_RETURN):
            self.state_machine.change(
                'play',
                level=self.level,
                paddle=self.paddle,
                ball=self.ball,
                score=self.score,
                lives=self.lives,
                bricks=self.bricks,
                broken_bricks_counter=self.broken_bricks_counter,
                points_to_next_live=self.points_to_next_live,
                live_factor=self.live_factor
            )

        keys = pygame.key.get_pressed()
        
        if keys[pygame.K_LEFT]:
            self.paddle.vx = -settings.PADDLE_SPEED
        elif keys[pygame.K_RIGHT]:
            self.paddle.vx = settings.PADDLE_SPEED
        else:
            self.paddle.vx = 0

        self.paddle.update(dt)
        self.ball.x = self.paddle.x + self.paddle.width//2 - 2

    def render(self, surface):
        
        heart_x = settings.VIRTUAL_WIDTH-120

        i = 0
        # Draw filled hearts
        while i < self.lives:
            surface.blit(
                settings.GAME_TEXTURES['hearts'], (heart_x, 5),
                settings.GAME_FRAMES['hearts'][0]
            )
            heart_x += 11
            i += 1
        
        # Draw empty hearts
        while i < 3:
            surface.blit(
                settings.GAME_TEXTURES['hearts'], (heart_x, 5),
                settings.GAME_FRAMES['hearts'][1]
            )
            heart_x += 11
            i += 1

        render_text(
            surface, f'Score: {self.score}', settings.GAME_FONTS['tiny'],
            settings.VIRTUAL_WIDTH-80, 5, (255, 255, 255)
        )

        for brick in self.bricks[0]:
            brick.render(surface)

        self.paddle.render(surface)
        self.ball.render(surface)

        render_text(
            surface, f'Level {self.level}', settings.GAME_FONTS['large'],
             settings.VIRTUAL_WIDTH//2, settings.VIRTUAL_HEIGHT//2-30,
             (255, 255, 255), center=True
        )
        render_text(
            surface, 'Press Enter to serve!', settings.GAME_FONTS['medium'],
            settings.VIRTUAL_WIDTH//2, settings.VIRTUAL_HEIGHT//2,
            (255, 255, 255), center=True
        )
Example #14
0
class GameLayer(Layer):
    is_event_handler = True

    def __init__(self, hud):
        super(GameLayer, self).__init__()
        # 添加板子和球
        self.is_on_exiting = True
        self.paddle = Paddle('images/paddle.png')
        self.add(self.paddle.sprite)
        self.ball = Ball('images/ball.png')
        self.ball.reset_position = (320, self.paddle.sprite.height + self.ball.sprite.height / 2)
        self.add(self.ball.sprite)
        # hud 用于记录,更新关卡,死亡,金币数据
        self.hud = hud
        # 生成关卡
        self.level = Level()
        self.level.levels = self.hud.levels

        self.add(self.hud.gold_hud)
        self.add(self.hud.level_hud)
        self.add(self.hud.death_hud)

        # 添加按键状态
        self.key_pressed_left = False
        self.key_pressed_right = False
        self.key_pressed_up = False
        self.key_pressed_down = False

        self.reset()

        # 定期调用 self.update 函数
        # FPS frame per second 每秒帧数
        self.schedule(self.update)

    def reset(self):
        self.paddle.reset()
        self.ball.reset()
        # 清空界面上的block
        for b in self.level.blocks:
            self.remove(b.sprite)
        # 再初始化新的砖块
        self.level.reset()
        for b in self.level.blocks:
            self.add(b.sprite)

    def game_over(self):
        self.hud.death += 1
        self.is_on_exiting = False
        scene = create_scene(GameOver(self.hud))
        director.replace(scene)

    def update_hud(self):
        self.hud.update()

    def update_blocks(self):
        for b in self.level.blocks:
            if collised(b.sprite, self.ball.sprite):
                print(1)
                self.ball.hit()
                b.live -= 1
                if b.live < 0:
                    self.level.blocks.remove(b)
                    self.remove(b.sprite)
                else:
                    b.reset()
                self.hud.gold += 1
                self.update_hud()
                print('金币:', self.hud.gold)
                break

    def update_ball(self):
        if self.ball.fired:
            self.ball.update()
        else:
            bx, by = self.ball.sprite.position
            px, py = self.paddle.sprite.position
            self.ball.sprite.position = (px, by)
        collide = collised(self.ball.sprite, self.paddle.sprite)
        if collide:
            xisu = 1
            bx, by = self.ball.sprite.position
            px, py = self.paddle.sprite.position
            offect_scale = (bx - px) / (self.paddle.sprite.width / 2)
            ball_speedx_change = offect_scale * xisu
            self.ball.speedx += ball_speedx_change
            self.ball.hit()
        if self.ball.dead():
            self.game_over()

    def update_paddle(self):
        self.paddle.update()

    def update_input(self):
        self.paddle.move_right = self.key_pressed_right
        self.paddle.move_left = self.key_pressed_left
        if self.key_pressed_up:
            self.ball.fire()

    def update_newlevel(self):
        if len(self.level.blocks) == 0:
            self.is_on_exiting = False
            if self.level.next():
                print(self.level.levels)
                self.hud.levels += 1
                scene = create_scene(GuoCangDongHua(self.hud))
            else:
                scene = create_scene(GameComplite(self.hud))
            director.replace(scene)

    def update(self, dt):
        if self.is_on_exiting:
            self.update_newlevel()
            self.update_ball()
            self.update_paddle()
            self.update_input()
            self.update_blocks()
            self.update_hud()

    def on_key_press(self, key, modifiers):
        k = symbol_string(key)
        status = True
        if k == 'LEFT':
            self.key_pressed_left = status
        elif k == 'RIGHT':
            self.key_pressed_right = status
        elif k == 'UP':
            self.key_pressed_up = status

    def on_key_release(self, key, modifiers):
        k = symbol_string(key)

        status = False
        if k == 'LEFT':
            self.key_pressed_left = status
        elif k == 'RIGHT':
            self.key_pressed_right = status
        elif k == 'UP':
            self.key_pressed_up = status
Example #15
0
class GameLayer(Layer):
    is_event_handler = True

    def __init__(self, hud):
        super(GameLayer, self).__init__()
        # 添加板子和球
        self.is_on_exiting = True
        self.paddle = Paddle('images/paddle.png')
        self.add(self.paddle.sprite)
        self.ball = Ball('images/ball.png')
        self.ball.reset_position = (320, self.paddle.sprite.height + self.ball.sprite.height / 2)
        self.add(self.ball.sprite)
        # hud 用于记录,更新关卡,死亡,金币数据
        self.hud = hud
        # 生成关卡
        self.level = Level()
        self.level.levels = self.hud.levels

        self.add(self.hud.gold_hud)
        self.add(self.hud.level_hud)
        self.add(self.hud.death_hud)

        # 添加按键状态
        self.key_pressed_left = False
        self.key_pressed_right = False
        self.key_pressed_up = False
        self.key_pressed_down = False

        self.reset()

        # 定期调用 self.update 函数
        # FPS frame per second 每秒帧数
        self.schedule(self.update)

    def reset(self):
        self.paddle.reset()
        self.ball.reset()
        # 清空界面上的block
        for b in self.level.blocks:
            self.remove(b.sprite)
        # 再初始化新的砖块
        self.level.reset()
        for b in self.level.blocks:
            self.add(b.sprite)

    def game_over(self):
        self.hud.death += 1
        self.is_on_exiting = False
        scene = create_scene(GameOver(self.hud))
        director.replace(scene)

    def update_hud(self):
        self.hud.update()

    def update_blocks(self):
        for b in self.level.blocks:
            if collised(b.sprite, self.ball.sprite):
                print(1)
                self.ball.hit()
                b.live -= 1
                if b.live < 0:
                    self.level.blocks.remove(b)
                    self.remove(b.sprite)
                else:
                    b.reset()
                self.hud.gold += 1
                self.update_hud()
                print('金币:', self.hud.gold)
                break

    def update_ball(self):
        if self.ball.fired:
            self.ball.update()
        else:
            bx, by = self.ball.sprite.position
            px, py = self.paddle.sprite.position
            self.ball.sprite.position = (px, by)
        collide = collised(self.ball.sprite, self.paddle.sprite)
        if collide:
            xisu = 1
            bx, by = self.ball.sprite.position
            px, py = self.paddle.sprite.position
            offect_scale = (bx - px) / (self.paddle.sprite.width / 2)
            ball_speedx_change = offect_scale * xisu
            self.ball.speedx += ball_speedx_change
            self.ball.hit()
        if self.ball.dead():
            self.game_over()

    def update_paddle(self):
        self.paddle.update()

    def update_input(self):
        self.paddle.move_right = self.key_pressed_right
        self.paddle.move_left = self.key_pressed_left
        if self.key_pressed_up:
            self.ball.fire()

    def update_newlevel(self):
        if len(self.level.blocks) == 0:
            self.is_on_exiting = False
            if self.level.next():
                print(self.level.levels)
                self.hud.levels += 1
                scene = create_scene(GuoCangDongHua(self.hud))
            else:
                scene = create_scene(GameComplite(self.hud))
            director.replace(scene)

    def update(self, dt):
        if self.is_on_exiting:
            self.update_newlevel()
            self.update_ball()
            self.update_paddle()
            self.update_input()
            self.update_blocks()
            self.update_hud()

    def on_key_press(self, key, modifiers):
        k = symbol_string(key)
        status = True
        if k == 'LEFT':
            self.key_pressed_left = status
        elif k == 'RIGHT':
            self.key_pressed_right = status
        elif k == 'UP':
            self.key_pressed_up = status

    def on_key_release(self, key, modifiers):
        k = symbol_string(key)

        status = False
        if k == 'LEFT':
            self.key_pressed_left = status
        elif k == 'RIGHT':
            self.key_pressed_right = status
        elif k == 'UP':
            self.key_pressed_up = status
Example #16
0
#pygame initiation
clock = pygame.time.Clock()

WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pong")
strip = pygame.Rect(WIDTH // 2 - 2, 0, 4, HEIGHT)

#set the game objects
player = Player('assets/Paddle.png', WIDTH - 20, HEIGHT // 2, SPEED)
opponent = Opponent('assets/Paddle.png', 20, WIDTH // 2, 5)
paddle_group = pygame.sprite.Group()
paddle_group.add(player)
paddle_group.add(opponent)

ball = Ball('assets/Ball.png', WIDTH // 2, HEIGHT // 2, 4, 4, paddle_group)
ball_sprite = pygame.sprite.GroupSingle()
ball_sprite.add(ball)

game = Game(WIN, ball_sprite, paddle_group)

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

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_DOWN:
                player.movement += player.speed
            if event.key == pygame.K_UP:
Example #17
0
def main():
    screen = pygame.display.set_mode(SCREEN_SIZE)
    clock = pygame.time.Clock()
    ball = Ball(
        x=int(SCREEN_SIZE[0] / 2) - 20,
        y=40,
        speed_x=0,
        speed_y=0
    )
    key_states = KeyStates()
    MIN_X = 0 + ball.width
    MAX_X = SCREEN_SIZE[0] - ball.width
    MAX_Y = SCREEN_SIZE[1] - ball.height
    active = True
    while active:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                active = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    key_states.key_states['R'] = True
                if event.key == pygame.K_LEFT:
                    key_states.key_states['L'] = True
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_RIGHT:
                    key_states.key_states['R'] = False
                if event.key == pygame.K_LEFT:
                    key_states.key_states['L'] = False

        screen.fill(BLACK)
        if key_states.key_states['R']:
            ball.update_speed_x(speed_x=ball.speed_x + 1)
        if key_states.key_states['L']:
            ball.update_speed_x(speed_x=ball.speed_x - 1)
        if not key_states.key_states['R'] and ball.speed_x > 0:
            ball.update_speed_x(speed_x=ball.speed_x - 1)
        if not key_states.key_states['L'] and ball.speed_x < 0:
            ball.update_speed_x(speed_x=ball.speed_x + 1)
        if ball.x < MIN_X:
            ball.x = MIN_X
            ball.speed_x *= -1
            splat_sound.play()
            ball.set_color_state()
        if ball.x > MAX_X:
            ball.x = MAX_X
            ball.speed_x *= -1
            splat_sound.play()
            ball.set_color_state()
        if ball.y > MAX_Y:
            ball.y = MAX_Y
            ball.speed_y *= -1
            ball.set_color_state()
        ball.update_speed_y(ball.speed_y + 1)
        ball.update_position()
        pygame.draw.ellipse(
            screen,
            ball.colors[ball.color_state],
            [ball.x, ball.y, ball.width, ball.height],
            BALL_EDGE_WIDTH
        )
        pygame.display.flip()
        clock.tick(60)
    pygame.quit()
Example #18
0
carryOn = True
clock = pygame.time.Clock()

# Open the game window
screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption(WINDOW_TITLE)

# Create game entities
background = Entity(join('media', 'fancy-court.png'))
#enemy = AI(join('media', 'fancy-paddle-grey.png'), followSpeed=4, posX=758, posY=236)
player1 = Player(join('media', 'fancy-paddle-green.png'), posX=10, posY=236)
player2 = Player(join('media', 'fancy-paddle-green.png'), posX=758, posY=236)
ball = Ball(join('media', 'fancy-ball.png'),
            player1,
            player2,
            direction=(1, 0),
            speed=10,
            leftZone=16,
            rightZone=800 - 16)
player1Ghost = Entity(join('media', 'ghost.png'))
player2Ghost = Entity(join('media', 'ghost.png'))
drawGroup = pygame.sprite.Group()
drawGroup.add(background)
drawGroup.add(player1)
drawGroup.add(player2)
drawGroup.add(ball)
drawGroup.add(player1Ghost)
drawGroup.add(player2Ghost)

# Game setup
ballStartPosition = (SCREEN_SIZE[0] / 2 - ball.rect.w / 2,
Example #19
0
pygame.init()
clock = pygame.time.Clock()
pygame.display.set_caption('Ping Pong')

screen_width = 1280
screen_height = 960
bg_color = pygame.Color('grey20')
light_grey = pygame.Color('green')
game_window = GameWindow(screen_width, screen_height)

ball_point = Point(game_window.get_width() // 2 - 15,
                   game_window.get_height() // 2 - 15)
ball_speed = Speed(7, 7)  # speed at x and y direction
ball_shape = Shape(30, 30)
ball = Ball(ball_point, ball_speed, ball_shape)
ball_color = pygame.Color('blue')
ball.set_color(ball_color)

player_point = Point(game_window.get_width() - 20,
                     game_window.get_height() // 2 - 70)
player_speed = Speed(0, 0)  # speed at x and y direction
player_shape = Shape(10, 140)
player = Player(player_point, player_speed, player_shape)
player_color = pygame.Color('white')
player.set_color(player_color)

opponent_point = Point(10, screen_height // 2 - 70)
opponent_speed = Speed(0, 7)  # speed at x and y direction
opponent_shape = Shape(10, 140)
opponent = Player(opponent_point, opponent_speed, opponent_shape)
Example #20
0
pyglet.gl.glClearColor(1, 1, 1, 1)

main_batch = pyglet.graphics.Batch()

balls = []


@game_window.event
def on_draw():
    game_window.clear()
    main_batch.draw()


def update(dt):
    for o in balls:
        o.update(dt)


if __name__ == '__main__':

    for i in range(int(sys.argv[1])):
        balls.append(Ball(x=random.randint(0, resources.WIDTH),
                          y=random.randint(0, resources.HEIGHT),
                          velocity_x=(random.random() - 0.5) * int(sys.argv[2]),
                          velocity_y=(random.random() - 0.5) * int(sys.argv[2]),
                          batch=main_batch,
                          mass=random.random()))

    pyglet.clock.schedule_interval(update, 1/120.0)
    pyglet.app.run()
Example #21
0
class IntroScreen():
    def __init__(self, size_=(0, 0)):
        self.size = size_
        self.bg = Color(69, 139, 116)

        self.ball = Ball()
        self.paddle = Paddle()

        brick_size = (50, 25)
        brick_colour = Color(63, 0, 127)
        self.bricks = []

        for x in range(6, self.size[0] - brick_size[0], brick_size[0] + 5):
            for y in range(25, 250, brick_size[1] + 3):
                self.bricks.append(Brick((x, y), brick_size, brick_colour))

    def update(self, delta_ms):
        self.ball.update(delta_ms)
        self.paddle.update(delta_ms)

        if not self.ball.launched:
            self.ball.rect.centerx = self.paddle.rect.centerx
            self.ball.rect.bottom = self.paddle.rect.top
            self.launch_ball()

        for br in self.bricks:
            br.update(delta_ms)

        self.brick_bounce()
        self.bound_ball()
        self.bind_paddle()

        self.paddle_bounce()

    def render(self):
        from engine.game_env import Game
        Game.get_surface().fill(self.bg)

        for br in self.bricks:
            br.render()

        self.ball.render()
        self.paddle.render()

    def resize(self, new_size):
        self.size = new_size

    def bound_ball(self):
        if self.ball.rect.left < 0:
            self.ball.rect.left = 0
            self.ball.vel[0] *= -1
        if self.ball.rect.right > self.size[0]:
            self.ball.rect.right = self.size[0]
            self.ball.vel[0] *= -1
        if self.ball.rect.top < 0:
            self.ball.rect.top = 0
            self.ball.vel[1] *= -1
        if self.ball.rect.bottom > self.size[1]:
            self.ball.rect.bottom = self.size[1]
            self.ball.vel[1] *= -1

    def bind_paddle(self):
        if self.paddle.rect.left < 0:
            self.paddle.rect.left = 0
        if self.paddle.rect.right > self.size[0]:
            self.paddle.rect.right = self.size[0]

    def paddle_bounce(self):
        tolerance = 0.2929

        overlap = self.paddle.rect.clip(self.ball.rect)

        if overlap:
            if overlap.width < overlap.height:
                if self.ball.rect.centerx < overlap.centerx:
                    self.ball.rect.right = overlap.left - 1
                else:
                    self.ball.rect.left = overlap.right + 1
                self.ball.vel[0] *= -1

                if overlap.height < self.ball.rect.height * tolerance:
                    if self.ball.rect.centery < overlap.centery:
                        self.ball.rect.bottom = overlap.top - 1
                        self.ball.vel[1] *= -1

            elif overlap.width > overlap.height:
                self.ball.rect.bottom = overlap.top - 1
                self.ball.vel[1] *= -1

                if overlap.width < self.ball.rect.width * tolerance:
                    if self.ball.rect.centerx < overlap.centerx:
                        self.ball.rect.right = overlap.left - 1
                    else:
                        self.ball.rect.left = overlap.right + 1
            else:
                if self.ball.rect.centerx < overlap.centerx:
                    self.ball.rect.right = overlap.left - 1
                else:
                    self.ball.rect.left = overlap.right + 1
                if self.ball.rect.centery < overlap.centery:
                    self.ball.rect.bottom = overlap.top - 1
                else:
                    self.ball.rect.top = self.paddle.rect.bottom + 1
                self.ball.vel[0] *= -1
                self.ball.vel[1] *= -1

    def brick_bounce(self):
        for brick in self.bricks:
            if brick.active:
                test_x = self.ball.rect.centerx
                test_y = self.ball.rect.centery

                if self.ball.rect.centerx < brick.rect.left:
                    test_x = brick.rect.left
                elif self.ball.rect.centerx > brick.rect.right:
                    test_x = brick.rect.right

                if self.ball.rect.centery < brick.rect.top:
                    test_y = brick.rect.top
                elif self.ball.rect.centery > brick.rect.bottom:
                    test_y = brick.rect.bottom

                dist_x = self.ball.rect.centerx - test_x
                dist_y = self.ball.rect.centery - test_y

                dist_x *= dist_x
                dist_y *= dist_y

                distance = (dist_x + dist_y)**0.5

                if distance <= self.ball.radius:
                    brick.active = False
                    overlap = self.ball.rect.clip(brick.rect)

                    if overlap.width < overlap.height:
                        self.ball.vel[0] *= -1
                    elif overlap.width > overlap.height:
                        self.ball.vel[1] *= -1
                    else:
                        self.ball.vel[0] *= -1
                        self.ball.vel[1] *= -1

    def launch_ball(self):
        from pygame.locals import K_SPACE
        from engine.game_env import Game
        if Game.get_key(K_SPACE):
            self.ball.launch()
Example #22
0
class Game():
    def __init__(self, line_thickness=10, speed=5):
        self.line_thickness = line_thickness
        self.speed = speed
        self.score = 0

        # Initiate variable and set starting positions
        # any future changes made within rectangles
        ball_x = int(window_width / 2 - self.line_thickness / 2)
        ball_y = int(window_height / 2 - self.line_thickness / 2)
        self.ball = Ball(ball_x, ball_y, self.line_thickness,
                         self.line_thickness, self.speed)
        self.paddles = {}
        paddle_height = 50
        paddle_width = self.line_thickness
        user_paddle_x = 20
        computer_paddle_x = window_width - paddle_width - 20

        # you
        self.paddles['user'] = Paddle(user_paddle_x, paddle_width,
                                      paddle_height)
        # computer
        self.paddles['computer'] = AutoPaddle(computer_paddle_x, paddle_width,
                                              paddle_height, self.ball,
                                              self.speed)
        self.scoreboard = Scoreboard(0)

    # Draws the arena the game will be played in.
    def draw_arena(self):
        display_surf.fill((0, 0, 0))
        # Draw outline of arena
        pygame.draw.rect(display_surf, WHITE,
                         ((0, 0), (window_width, window_height)),
                         self.line_thickness * 2)
        # Draw centre line
        pygame.draw.line(display_surf, WHITE, (int(window_width / 2), 0),
                         (int(window_width / 2), window_height),
                         int(self.line_thickness / 4))

    def update(self):
        self.ball.move()
        self.paddles['computer'].move()

        if self.ball.hit_paddle(self.paddles['computer']):
            self.ball.bounce('x')
        elif self.ball.hit_paddle(self.paddles['user']):
            self.ball.bounce('x')
            self.score += 1
        elif self.ball.pass_computer():
            self.score += 5
        elif self.ball.pass_player():
            self.score = 0

        self.draw_arena()
        self.ball.draw()
        self.paddles['user'].draw()
        self.paddles['computer'].draw()
        self.scoreboard.display(self.score)
Example #23
0
    def __init__(self):

        pygame.font.init()
        #pygame.mixer.init()

        game_font = pygame.font.SysFont('Comic Sans MS', 45)
        placar_font = pygame.font.SysFont('Comic Sans MS', 20)

        score = 0
        score_text_surface = game_font.render('Pontos: ' + str(score), False,
                                              (255, 255, 255))

        placar = 35
        name = "Carlos"
        placar_text_surface = placar_font.render(
            'Melhor Jogador: ' + name + ' - ' + str(placar), False,
            (0, 0, 255))

        def get_image(path):
            global _image_library
            image = _image_library.get(path)
            if image == None:
                canonicalized_path = path.replace('/', os.sep).replace(
                    '\\', os.sep)
                image = pygame.image.load(canonicalized_path)
                _image_library[path] = image
            return image

        # variaveis do heroi
        hero = Zombie()
        hero_group = pygame.sprite.Group(hero)

        # variaveis da bolinha
        #ball_position = get_ball_positon()
        ball = Ball()
        ball.set_random_position(hero)

        # cria o timer
        #time_left = CONST.GAME_TIME
        #time_text_surface = game_font.render(str(time_left), False,(0,0,0))
        #DEC_TIME = 1
        #pygame.time.set_timer(DEC_TIME, 1000)

        #Timer Novo (bug do mouse)
        start_ticks = pygame.time.get_ticks()
        time_left = CONST.GAME_TIME
        count_errors_bug = 0
        mirror = False
        bug = False
        alreadySaid = [False, False, False, False, False, False]
        first = True
        opc0 = opc1 = opc2 = opc3 = 0

        time_text_surface = game_font.render(str(time_left), False,
                                             (255, 255, 255))
        pygame.time.set_timer(pygame.USEREVENT, 1000)

        screen = pygame.display.set_mode(
            (CONST.DISPLAY_SIZE_X, CONST.DISPLAY_SIZE_Y), pygame.FULLSCREEN)
        done = False
        clock = pygame.time.Clock()

        # loop principal
        while not done:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit(0)
                if event.type == pygame.USEREVENT:
                    if time_left > 0:
                        seconds = (pygame.time.get_ticks() -
                                   start_ticks) / 1000
                        novo = (pygame.time.get_ticks() - start_ticks) / 1000
                        #print(seconds)
                        if seconds > 8:
                            bug_probability = random.randint(0, 10)
                            #print("Bug Probability = " + str(bug_probability))
                            if bug_probability == 1:
                                bug = True
                            else:
                                bug = False
                            if (seconds % 5) == 0:
                                mirror = True
                                opc0 = random.randint(0, 3)
                                opc1 = random.randint(0, 3)
                                opc2 = random.randint(0, 3)
                                opc3 = random.randint(0, 3)
                                hero.zombie_error()
                            elif ((novo % 4) == 0):
                                mirror = False
                            #countDown sound
                        if (time_left == 6):
                            for i in range(0, 6):
                                alreadySaid[i] = False
                        if (time_left == 6
                                and alreadySaid[time_left - 1] == False):
                            countdown = pygame.mixer.Sound('src/sounds/5.wav')
                            countdown.play()
                            alreadySaid[time_left - 1] = True
                        if (time_left == 5
                                and alreadySaid[time_left - 1] == False):
                            countdown = pygame.mixer.Sound('src/sounds/4.wav')
                            countdown.play()
                            alreadySaid[time_left - 1] = True
                        if (time_left == 4
                                and alreadySaid[time_left - 1] == False):
                            countdown = pygame.mixer.Sound('src/sounds/3.wav')
                            countdown.play()
                            alreadySaid[time_left - 1] = True
                        if (time_left == 3
                                and alreadySaid[time_left - 1] == False):
                            countdown = pygame.mixer.Sound('src/sounds/2.wav')
                            countdown.play()
                            alreadySaid[time_left - 1] = True
                        if (time_left == 2
                                and alreadySaid[time_left - 1] == False):
                            countdown = pygame.mixer.Sound('src/sounds/1.wav')
                            countdown.play()
                            alreadySaid[time_left - 1] = True
                        if (time_left == 1
                                and alreadySaid[time_left - 1] == False):
                            countdown = pygame.mixer.Sound('src/sounds/0.wav')
                            countdown.play()
                            alreadySaid[time_left - 1] = True
                        time_left -= 1
                    else:
                        done = True

            # pega as teclas pressionadas
            pressed = pygame.key.get_pressed()
            #print(mirror)

            if bug:
                if pressed[pygame.K_UP]:
                    hero.human_error()
                    count_errors_bug += 1
                elif pressed[pygame.K_DOWN]:
                    hero.human_error()
                    count_errors_bug += 1
                elif pressed[pygame.K_LEFT]:
                    hero.human_error()
                    count_errors_bug += 1
                elif pressed[pygame.K_RIGHT]:
                    hero.human_error()
                    count_errors_bug += 1
            elif mirror:
                if pressed[pygame.K_UP]:
                    hero.wrong_way(opc0)
                elif pressed[pygame.K_DOWN]:
                    hero.wrong_way(opc1)
                elif pressed[pygame.K_LEFT]:
                    hero.wrong_way(opc2)
                elif pressed[pygame.K_RIGHT]:
                    hero.wrong_way(opc3)
            else:
                if pressed[pygame.K_UP]:
                    hero.move_up()
                elif pressed[pygame.K_DOWN]:
                    hero.move_down()
                elif pressed[pygame.K_LEFT]:
                    hero.move_left()
                elif pressed[pygame.K_RIGHT]:
                    hero.move_right()
            # checa se a bola está dentro do heroi
            if hero.has_ball_inside(ball):
                score += 1
                score_text_surface = game_font.render('Pontos: ' + str(score),
                                                      False, (255, 255, 255))
                hero.bite()
                ball.set_random_position(hero)
                #if time_left > 5:
                time_left += 2
                #else:
                #    time_left += (5 - time_left) + 1

            # atualiza o tempo
            if time_left < 6:
                time_text_surface = game_font.render(str(time_left), False,
                                                     (255, 0, 0))
            else:
                time_text_surface = game_font.render(str(time_left), False,
                                                     (255, 255, 255))

            screen.fill((0, 0, 0))
            hero_group.update()
            hero_group.draw(screen)
            screen.blit(get_image('img/cerebro.png'), (ball.pos.x, ball.pos.y))
            screen.blit(score_text_surface, (CONST.DISPLAY_SIZE_X - 250, 10))
            screen.blit(time_text_surface, (CONST.DISPLAY_SIZE_X / 2 - 0, 10))
            screen.blit(placar_text_surface,
                        (CONST.DISPLAY_SIZE_X / 2 - 450, 30))
            #if count_errors_bug > 1:
            #   screen.blit(wtf_text_surface,(CONST.DISPLAY_SIZE_X - 0,0))
            pygame.display.flip()
            clock.tick(60)
Example #24
0
class IntroScreen():
    def __init__(self, size_=(0, 0)):
        self.size = size_
        self.bg = Color(69, 139, 116)

        self.ball = Ball()
        self.paddle = Paddle()

        brick_size = (int(self.size[0] / 9), 25)
        self.bricks = [
            Brick((x, y), brick_size)
            for x in range(int(0.15 * brick_size[0]), self.size[0] -
                           brick_size[0], int(1.1 * brick_size[0]))
            for y in range(brick_size[1], 9 *
                           brick_size[1], int(1.05 * brick_size[1]))
        ]

    def update(self, delta_ms):
        self.ball.update(delta_ms)
        self.paddle.update(delta_ms)

        self.bound_ball()
        self.bind_paddle()

        self.paddle_bounce()
        self.brick_bounce()

        for br in self.bricks:
            br.update(delta_ms)

    def render(self):
        from engine.game_env import Game
        Game.get_surface().fill(self.bg)

        for br in self.bricks:
            br.render()

        self.ball.render()
        self.paddle.render()

    def resize(self, new_size):
        self.size = new_size

    def bound_ball(self):
        if self.ball.rect.left < 0:
            self.ball.rect.left = 0
            self.ball.vel[0] *= -1
        if self.ball.rect.right > self.size[0]:
            self.ball.rect.right = self.size[0]
            self.ball.vel[0] *= -1
        if self.ball.rect.top < 0:
            self.ball.rect.top = 0
            self.ball.vel[1] *= -1
        if self.ball.rect.bottom > self.size[1]:
            self.ball.rect.bottom = self.size[1]
            self.ball.vel[1] *= -1

    def bind_paddle(self):
        if self.paddle.rect.left < 0:
            self.paddle.rect.left = 0
        if self.paddle.rect.right > self.size[0]:
            self.paddle.rect.right = self.size[0]

    def paddle_bounce(self):
        tolerance = 0.2929

        overlap = self.paddle.rect.clip(self.ball.rect)

        if overlap:
            if overlap.width < overlap.height:
                if self.ball.rect.centerx < overlap.centerx:
                    self.ball.rect.right = overlap.left - 1
                else:
                    self.ball.rect.left = overlap.right + 1
                self.ball.vel[0] *= -1

                if overlap.height < self.ball.rect.height * tolerance:
                    if self.ball.rect.centery < overlap.centery:
                        self.ball.rect.bottom = overlap.top - 1
                        self.ball.vel[1] *= -1

            elif overlap.width > overlap.height:
                self.ball.rect.bottom = overlap.top - 1
                self.ball.vel[1] *= -1

                if overlap.width < self.ball.rect.width * tolerance:
                    if self.ball.rect.centerx < overlap.centerx:
                        self.ball.rect.right = overlap.left - 1
                    else:
                        self.ball.rect.left = overlap.right + 1
            else:
                if self.ball.rect.centerx < overlap.centerx:
                    self.ball.rect.right = overlap.left - 1
                else:
                    self.ball.rect.left = overlap.right + 1
                if self.ball.rect.centery < overlap.centery:
                    self.ball.rect.bottom = overlap.top - 1
                else:
                    self.ball.rect.top = self.paddle.rect.bottom + 1
                self.ball.vel[0] *= -1
                self.ball.vel[1] *= -1

    def brick_bounce(self):
        for br in self.bricks:
            if br.active:
                test_x = self.ball.rect.centerx
                test_y = self.ball.rect.centery

                if self.ball.rect.centerx < br.rect.left:
                    test_x = br.rect.left
                elif self.ball.rect.centerx > br.rect.right:
                    test_x = br.rect.right

                if self.ball.rect.centery < br.rect.top:
                    test_y = br.rect.top
                elif self.ball.rect.centery > br.rect.bottom:
                    test_y = br.rect.bottom

                dist_x = self.ball.rect.centerx - test_x
                dist_y = self.ball.rect.centery - test_y

                dist_x *= dist_x
                dist_y *= dist_y

                dist = (dist_x + dist_y)**0.5

                if dist < self.ball.radius:
                    br.active = False
                    if dist_x < dist_y:
                        self.ball.vel[1] *= -1
                    elif dist_y < dist_x:
                        self.ball.vel[0] *= -1
                    else:
                        self.ball.vel[0] *= -1
                        self.ball.vel[1] *= -1
Example #25
0
    def __init__(self):
        
        pygame.font.init()
        game_font = pygame.font.SysFont('Comic Sans MS', 45)
        placar_font = pygame.font.SysFont('Comic Sans MS', 20)

        score = 0
        score_text_surface = game_font.render('Pontos: '+str(score), False,(0,0,0))

        placar = 100
        name = "Carlos"
        placar_text_surface = placar_font.render('Melhor Jogador: ' + name + ' - '+str(placar), False, (0,0,255))

       

        def get_image(path):
            global _image_library
            image = _image_library.get(path)
            if image == None:
                canonicalized_path = path.replace('/', os.sep).replace('\\', os.sep)
                image = pygame.image.load(canonicalized_path)
                _image_library[path] = image
            return image


        # variaveis do heroi
        hero = Zombie()
        hero_group = pygame.sprite.Group(hero)

        # variaveis da bolinha
        #ball_position = get_ball_positon()
        ball = Ball()
        ball.set_random_position(hero)

        # cria o timer
        time_left = CONST.GAME_TIME
        time_text_surface = game_font.render(str(time_left), False,(0,0,0))
        DEC_TIME = 1
        pygame.time.set_timer(DEC_TIME, 1000)

        screen = pygame.display.set_mode((CONST.DISPLAY_SIZE_X, CONST.DISPLAY_SIZE_Y))
        done = False
        clock = pygame.time.Clock()

        # loop principal
        while not done:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit(0)
                if event.type == DEC_TIME:
                    if time_left > 0:
                        time_left -= 1
                    else:
                        done = True
            
            # pega as teclas pressionadas
            pressed = pygame.key.get_pressed()

            if pressed[pygame.K_UP]:
                hero.move_up()
            elif pressed[pygame.K_DOWN]:
                hero.move_down()
            elif pressed[pygame.K_LEFT]:
                hero.move_left()
            elif pressed[pygame.K_RIGHT]:
                hero.move_right()
          
            # checa se a bola está dentro do heroi
            if hero.has_ball_inside(ball):
                score += 1
                score_text_surface = game_font.render('Pontos: ' + str(score), False,(0,0,0))
                ball.set_random_position(hero)

            # atualiza o tempo
            if time_left < 6:
                time_text_surface = game_font.render(str(time_left), False,(255,0,0))
            else:
                time_text_surface = game_font.render(str(time_left), False,(0,0,0))

            screen.fill((0, 0, 0))
            hero_group.update()
            hero_group.draw(screen)
            screen.blit(get_image('img/cerebro.png'), (ball.pos.x, ball.pos.y))
            screen.blit(score_text_surface,(CONST.DISPLAY_SIZE_X - 250,10))
            screen.blit(time_text_surface,(CONST.DISPLAY_SIZE_X/2 - 0,10))
            screen.blit(placar_text_surface,(CONST.DISPLAY_SIZE_X/2 - 450,30))
            pygame.display.flip()
            clock.tick(60)
Example #26
0
class GameLayer(Layer):
    is_event_handler = True

    def __init__(self, levels=1, golds=0, deadcount=0):
        super(GameLayer, self).__init__()
        # 添加板子和球

        self.paddle = Paddle('images/paddle.png')
        self.add(self.paddle.sprite)
        self.ball = Ball('images/ball.png')
        self.ball.reset_position = (320, self.paddle.sprite.height + self.ball.sprite.height/2)
        self.add(self.ball.sprite)
        # 生成关卡
        self.level = Level()
        self.level.levels = levels
        # 添加标签用于记录金币和关卡。死亡次数
        self.gold = golds
        self.deadcount = deadcount

        self.hud = Label('金币: '+str(golds))
        self.level_hud = Label('关卡: '+str(levels))
        self.deadstu = Label('死亡: '+str(deadcount))

        self.hud.position = (0, 460)
        self.level_hud.position = (80, 460)
        self.deadstu.position = (160, 460)
        self.add(self.hud)
        self.add(self.level_hud)
        self.add(self.deadstu)

        # 添加按键状态
        self.key_pressed_left = False
        self.key_pressed_right = False
        self.key_pressed_up = False
        self.key_pressed_down = False

        self.blocks = []
        self.reset()

        # 定期调用 self.update 函数
        # FPS frame per second 每秒帧数
        self.schedule(self.update)
    # def on_enter(self):
    #     self.visible = True

    def reset(self):
        self.paddle.reset()
        self.ball.reset()
        # 清空界面上的block
        for b in self.blocks:
            self.remove(b)
        # 再初始化新的砖块
        self.blocks = []
        positions = self.level.blocks_pos
        number_of_blocks = len(positions)
        for i in range(number_of_blocks):
            b = Sprite('images/block.png')
            b.position = positions[i]
            self.add(b)
            self.blocks.append(b)

    def game_over(self):
        self.deadcount += 1
        scene = Scene(GameOver(self.level.levels, self.gold, self.deadcount))
        director.replace(scene)

    def update_hud(self):
        self.hud.element.text = '金币: ' + str(self.gold)
        self.level_hud.element.text = '关卡: ' + str(self.level.levels)

    def update_blocks(self):
        for b in self.blocks:
            if collision(b, self.ball.sprite):
                self.ball.hit()
                self.blocks.remove(b)
                self.remove(b)
                self.gold += 1
                self.update_hud()
                print('金币:', self.gold)
                break

    def update_ball(self):
        if self.ball.fired:
            self.ball.update()
        else:
            bx, by = self.ball.sprite.position
            px, py = self.paddle.sprite.position
            self.ball.sprite.position = (px, by)
        collide = collision(self.ball.sprite, self.paddle.sprite)
        if collide:
            self.ball.hit()
        if self.ball.dead():
            self.game_over()

    def update_paddle(self):
        self.paddle.update()

    def update_input(self):
        self.paddle.move_right = self.key_pressed_right
        self.paddle.move_left = self.key_pressed_left
        if self.key_pressed_up:
            self.ball.fire()

    def update_newlevel(self):
        if len(self.blocks) == 0:
            self.level.next()
            print(self.level.levels)
            # self.reset()
            scene = Scene(GuoCangDongHua(self.level.levels, self.gold, self.deadcount))
            director.replace(scene)
            # director.replace(FadeTransition(Scene(GameLayer(self.level.levels, self.gold))))

    def update(self, dt):
        self.update_newlevel()
        self.update_ball()
        self.update_paddle()
        self.update_input()
        self.update_blocks()
        self.update_hud()

    def on_key_press(self, key, modifiers):
        k = symbol_string(key)
        status = True
        if k == 'LEFT':
            self.key_pressed_left = status
        elif k == 'RIGHT':
            self.key_pressed_right = status
        elif k == 'UP':
            self.key_pressed_up = status

    def on_key_release(self, key, modifiers):
        k = symbol_string(key)

        status = False
        if k == 'LEFT':
            self.key_pressed_left = status
        elif k == 'RIGHT':
            self.key_pressed_right = status
        elif k == 'UP':
            self.key_pressed_up = status
Example #27
0
    def __init__(self):

        pygame.font.init()

        # coloca o background
        background = pygame.image.load("img/background2.jpg")

        game_font = pygame.font.SysFont('Comic Sans MS', 45)
        placar_font = pygame.font.SysFont('Comic Sans MS', 20)

        score = 0
        score_text_surface = game_font.render('Pontos: ' + str(score), False,
                                              (255, 255, 255))

        placar = 35
        name = "Carlitos"
        placar_text_surface = placar_font.render(
            'Melhor Jogador: ' + name + ' - ' + str(placar), False,
            (0, 0, 255))

        def get_image(path):
            global _image_library
            image = _image_library.get(path)
            if image == None:
                canonicalized_path = path.replace('/', os.sep).replace(
                    '\\', os.sep)
                image = pygame.image.load(canonicalized_path)
                _image_library[path] = image
            return image

        # variaveis do heroi
        hero = Zombie()
        hero_group = pygame.sprite.Group(hero)

        # variaveis da bolinha
        ball = Ball()
        ball.set_random_position(hero)

        #Timer Novo (bug do mouse)
        start_ticks = pygame.time.get_ticks()
        time_left = CONST.GAME_TIME

        mirror = False
        alreadySaid = [False, False, False, False, False, False]
        opc0 = opc1 = opc2 = opc3 = 0

        time_text_surface = game_font.render(str(time_left), False,
                                             (255, 255, 255))
        pygame.time.set_timer(pygame.USEREVENT, 1000)

        screen = pygame.display.set_mode(
            (CONST.DISPLAY_SIZE_X, CONST.DISPLAY_SIZE_Y), pygame.FULLSCREEN)
        done = False
        clock = pygame.time.Clock()

        # loop principal
        while not done:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit(0)
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_UP:
                        data_harvest.pressed_keys.append(
                            ['PRESS_K_UP',
                             datetime.datetime.now()])
                        hero.shuffle_random_direction()
                    if event.key == pygame.K_DOWN:
                        data_harvest.pressed_keys.append(
                            ['PRESS_K_DOWN',
                             datetime.datetime.now()])
                        hero.shuffle_random_direction()
                    if event.key == pygame.K_LEFT:
                        data_harvest.pressed_keys.append(
                            ['PRESS_K_LEFT',
                             datetime.datetime.now()])
                        hero.shuffle_random_direction()
                    if event.key == pygame.K_RIGHT:
                        data_harvest.pressed_keys.append(
                            ['PRESS_K_RIGHT',
                             datetime.datetime.now()])
                        hero.shuffle_random_direction()

                if event.type == pygame.KEYUP:
                    if event.key == pygame.K_UP:
                        data_harvest.pressed_keys.append(
                            ['RELEASE_K_UP',
                             datetime.datetime.now()])
                    if event.key == pygame.K_DOWN:
                        data_harvest.pressed_keys.append(
                            ['RELEASE_K_DOWN',
                             datetime.datetime.now()])
                    if event.key == pygame.K_LEFT:
                        data_harvest.pressed_keys.append(
                            ['RELEASE_K_LEFT',
                             datetime.datetime.now()])
                    if event.key == pygame.K_RIGHT:
                        data_harvest.pressed_keys.append(
                            ['RELEASE_K_RIGHT',
                             datetime.datetime.now()])

                if event.type == pygame.USEREVENT:
                    if time_left > 0:
                        seconds = (pygame.time.get_ticks() -
                                   start_ticks) / 1000

                        # configura as probabilidades de bug
                        if seconds < 8:
                            error_probability = 0
                        elif seconds < 25:
                            error_probability = random.randint(0, 15)
                        elif seconds < 40:
                            error_probability = random.randint(0, 11)
                        else:
                            error_probability = random.randint(0, 7)

                        if error_probability == 1:
                            hero.random_movement()

                        if error_probability == 2:
                            hero.slow_down()

                        if error_probability == 3:
                            hero.human_error()

                        if (seconds % 5) == 0:
                            hero.zombie_scream()

                        #countDown sound
                        if (time_left == 6):
                            for i in range(0, 6):
                                alreadySaid[i] = False
                        if (time_left == 6
                                and alreadySaid[time_left - 1] == False):
                            countdown = pygame.mixer.Sound('src/sounds/5.wav')
                            alreadySaid[time_left - 1] = True
                            countdown.play()
                        if (time_left == 5
                                and alreadySaid[time_left - 1] == False):
                            countdown = pygame.mixer.Sound('src/sounds/4.wav')
                            alreadySaid[time_left - 1] = True
                            countdown.play()
                        if (time_left == 4
                                and alreadySaid[time_left - 1] == False):
                            countdown = pygame.mixer.Sound('src/sounds/3.wav')
                            alreadySaid[time_left - 1] = True
                            countdown.play()
                        if (time_left == 3
                                and alreadySaid[time_left - 1] == False):
                            countdown = pygame.mixer.Sound('src/sounds/2.wav')
                            alreadySaid[time_left - 1] = True
                            countdown.play()
                        if (time_left == 2
                                and alreadySaid[time_left - 1] == False):
                            countdown = pygame.mixer.Sound('src/sounds/1.wav')
                            alreadySaid[time_left - 1] = True
                            countdown.play()
                        if (time_left == 1
                                and alreadySaid[time_left - 1] == False):
                            countdown = pygame.mixer.Sound('src/sounds/0.wav')
                            alreadySaid[time_left - 1] = True
                            countdown.play()
                        time_left -= 1
                    else:
                        done = True

                        # salva os dados coletados
                        dir_path = data_harvest.player_name + "-" + str(
                            datetime.datetime.now())
                        os.makedirs('data/' + dir_path)
                        pd.DataFrame(data_harvest.pressed_keys).to_csv(
                            "data/" + dir_path + "/pressed_keys.csv",
                            index=None,
                            header=['PRESSED_KEY', 'TIME'])
                        pd.DataFrame(data_harvest.random_events).to_csv(
                            "data/" + dir_path + "/random_events.csv",
                            index=None,
                            header=['RANDOM_EVENT', 'TIME'])
                        pd.DataFrame(data_harvest.hero_movement).to_csv(
                            "data/" + dir_path + "/hero_movement.csv",
                            index=None,
                            header=['DIRECTION', 'SPEED', 'TIME'])
                        data_harvest.final_score = score
                        pd.DataFrame([data_harvest.final_score
                                      ]).to_csv("data/" + dir_path + "/" +
                                                data_harvest.player_name,
                                                index=None,
                                                header=['SCORE'])

            # pega as teclas pressionadas
            pressed = pygame.key.get_pressed()

            if pressed[pygame.K_ESCAPE]:
                quit(0)

            else:
                if pressed[pygame.K_UP]:
                    hero.move_up()
                elif pressed[pygame.K_DOWN]:
                    hero.move_down()
                elif pressed[pygame.K_LEFT]:
                    hero.move_left()
                elif pressed[pygame.K_RIGHT]:
                    hero.move_right()
            # checa se a bola está dentro do heroi
            if hero.has_ball_inside(ball):
                data_harvest.random_events.append(
                    ['ZOMBIE_EATS', datetime.datetime.now()])
                score += 1
                score_text_surface = game_font.render('Pontos: ' + str(score),
                                                      False, (255, 255, 255))
                hero.bite()
                ball.set_random_position(hero)
                time_left += 2

            # atualiza o tempo
            if time_left < 6:
                time_text_surface = game_font.render(str(time_left), False,
                                                     (255, 0, 0))
            else:
                time_text_surface = game_font.render(str(time_left), False,
                                                     (255, 255, 255))

            screen.fill((0, 0, 0))
            screen.blit(background, (0, 70))
            hero_group.update()
            hero_group.draw(screen)
            screen.blit(get_image('img/cerebro.png'), (ball.pos.x, ball.pos.y))
            screen.blit(score_text_surface, (CONST.DISPLAY_SIZE_X - 250, 10))
            screen.blit(time_text_surface, (CONST.DISPLAY_SIZE_X / 2 - 0, 10))
            screen.blit(placar_text_surface,
                        (CONST.DISPLAY_SIZE_X / 2 - 450, 30))
            pygame.display.flip()
            clock.tick(60)
Example #28
0
class IntroScreen():
    def __init__(self, size_=(0, 0)):
        self.size = size_
        self.bg = Color(69, 139, 116)

        self.ball = Ball()
        self.paddle = Paddle()

        brick_size = (50, 25)
        brick_colour = Color(63, 0, 127)
        self.bricks = []

        for x in range(6, self.size[0] - brick_size[0], brick_size[0] + 5):
            for y in range(25, 250, brick_size[1] + 3):
                self.bricks.append(Brick((x, y), brick_size, brick_colour))

    def update(self, delta_ms):
        self.ball.update(delta_ms)
        self.paddle.update(delta_ms)

        self.bound_ball()
        self.bind_paddle()

        self.paddle_bounce()

        for br in self.bricks:
            br.update(delta_ms)

    def render(self):
        from engine.game_env import Game
        Game.get_surface().fill(self.bg)

        for br in self.bricks:
            br.render()

        self.ball.render()
        self.paddle.render()

    def resize(self, new_size):
        self.size = new_size

    def bound_ball(self):
        if self.ball.rect.left < 0:
            self.ball.rect.left = 0
            self.ball.vel[0] *= -1
        if self.ball.rect.right > self.size[0]:
            self.ball.rect.right = self.size[0]
            self.ball.vel[0] *= -1
        if self.ball.rect.top < 0:
            self.ball.rect.top = 0
            self.ball.vel[1] *= -1
        if self.ball.rect.bottom > self.size[1]:
            self.ball.rect.bottom = self.size[1]
            self.ball.vel[1] *= -1

    def bind_paddle(self):
        if self.paddle.rect.left < 0:
            self.paddle.rect.left = 0
        if self.paddle.rect.right > self.size[0]:
            self.paddle.rect.right = self.size[0]

    def paddle_bounce(self):
        tolerance = 0.2929

        overlap = self.paddle.rect.clip(self.ball.rect)

        if overlap:
            if overlap.width < overlap.height:
                if self.ball.rect.centerx < overlap.centerx:
                    self.ball.rect.right = overlap.left - 1
                else:
                    self.ball.rect.left = overlap.right + 1
                self.ball.vel[0] *= -1

                if overlap.height < self.ball.rect.height * tolerance:
                    if self.ball.rect.centery < overlap.centery:
                        self.ball.rect.bottom = overlap.top - 1
                        self.ball.vel[1] *= -1

            elif overlap.width > overlap.height:
                self.ball.rect.bottom = overlap.top - 1
                self.ball.vel[1] *= -1

                if overlap.width < self.ball.rect.width * tolerance:
                    if self.ball.rect.centerx < overlap.centerx:
                        self.ball.rect.right = overlap.left - 1
                    else:
                        self.ball.rect.left = overlap.right + 1
            else:
                if self.ball.rect.centerx < overlap.centerx:
                    self.ball.rect.right = overlap.left - 1
                else:
                    self.ball.rect.left = overlap.right + 1
                if self.ball.rect.centery < overlap.centery:
                    self.ball.rect.bottom = overlap.top - 1
                else:
                    self.ball.rect.top = self.paddle.rect.bottom + 1
                self.ball.vel[0] *= -1
                self.ball.vel[1] *= -1
Example #29
0
class IntroScreen():
    def __init__(self, size_=(0, 0)):
        self.size = size_
        self.bg = Color(69, 139, 116)

        self.ball = Ball()
        self.paddle = Paddle()

    def update(self, delta_ms):
        self.ball.update(delta_ms)
        self.paddle.update(delta_ms)

        self.bound_ball()
        self.bind_paddle()

        self.paddle_bounce()

    def render(self):
        from engine.game_env import Game
        Game.get_surface().fill(self.bg)

        self.ball.render()
        self.paddle.render()

    def resize(self, new_size):
        self.size = new_size

    def bound_ball(self):
        if self.ball.rect.left < 0:
            self.ball.rect.left = 0
            self.ball.vel[0] *= -1
        if self.ball.rect.right > self.size[0]:
            self.ball.rect.right = self.size[0]
            self.ball.vel[0] *= -1
        if self.ball.rect.top < 0:
            self.ball.rect.top = 0
            self.ball.vel[1] *= -1
        if self.ball.rect.bottom > self.size[1]:
            self.ball.rect.bottom = self.size[1]
            self.ball.vel[1] *= -1

    def bind_paddle(self):
        if self.paddle.rect.left < 0:
            self.paddle.rect.left = 0
        if self.paddle.rect.right > self.size[0]:
            self.paddle.rect.right = self.size[0]

    def paddle_bounce(self):
        tolerance = 0.2929

        overlap = self.paddle.rect.clip(self.ball.rect)

        if overlap:
            if overlap.width < overlap.height:
                if self.ball.rect.centerx < overlap.centerx:
                    self.ball.rect.right = overlap.left - 1
                else:
                    self.ball.rect.left = overlap.right + 1
                self.ball.vel[0] *= -1

                if overlap.height < self.ball.rect.height * tolerance:
                    if self.ball.rect.centery < overlap.centery:
                        self.ball.rect.bottom = overlap.top - 1
                        self.ball.vel[1] *= -1

            elif overlap.width > overlap.height:
                self.ball.rect.bottom = overlap.top - 1
                self.ball.vel[1] *= -1

                if overlap.width < self.ball.rect.width * tolerance:
                    if self.ball.rect.centerx < overlap.centerx:
                        self.ball.rect.right = overlap.left - 1
                    else:
                        self.ball.rect.left = overlap.right + 1
            else:
                if self.ball.rect.centerx < overlap.centerx:
                    self.ball.rect.right = overlap.left - 1
                else:
                    self.ball.rect.left = overlap.right + 1
                if self.ball.rect.centery < overlap.centery:
                    self.ball.rect.bottom = overlap.top - 1
                else:
                    self.ball.rect.top = self.paddle.rect.bottom + 1
                self.ball.vel[0] *= -1
                self.ball.vel[1] *= -1
Example #30
0
            o.update(dt_a)
        [heapq.heappush(pq, col) for col in collision(balls=balls)]
        ta += dt_a

    for o in balls:
        o.update(tb - ta)


if __name__ == '__main__':
    pq = []
    balls = []
    # initialize all the balls
    for i in range(int(sys.argv[1])):
        balls.append(Ball(x=random.randint(10, resources.WIDTH - 10),
                          y=random.randint(10, resources.HEIGHT - 0),
                          velocity_x=random.random() - 0.5,
                          velocity_y=random.random() - 0.5,
                          batch=main_batch,
                          mass=random.random()))
    balls.append(Ball(x=100, y=100,
                      velocity_y=int(sys.argv[2]), velocity_x=int(sys.argv[2]),
                      batch=main_batch, mass=4))
    # initialize the priority queue
    for ball in balls:
        [heapq.heappush(pq, col) for col in ball.predict(time=0, balls=balls)]

    t = TimeElapsed()
    # regular interval draws
    pyglet.clock.schedule_interval(update, 1/60.0, pq=pq, t=t)
    pyglet.app.run()
Example #31
0
    def __init__(self, size_=(0, 0)):
        self.size = size_
        self.bg = Color(69, 139, 116)

        self.ball = Ball()
        self.paddle = Paddle()