Пример #1
0
 def test_inc_play2(self):
     ball = Ball()
     ball.position['x'] = -1
     self.score.check_score(ball)
     self.assertEqual(0, self.score.player1)
     self.assertEqual(1, self.score.player2)
     self.checkFinalPosition(ball)
Пример #2
0
 def test_inc_play1(self):
     ball = Ball()
     ball.position['x'] = constants.SCREEN_WIDTH + 1
     self.score.check_score(ball)
     self.assertEqual(1, self.score.player1)
     self.assertEqual(0, self.score.player2)
     self.checkFinalPosition(ball)
Пример #3
0
class Player():
    def __init__(self, game, pop):
        self.pop = pop
        self.game = game
        self.ball = Ball(game)
        self.ball.player = self
        self.paddle = Paddle(game, self.ball)
        self.paddle.player = self
        self.alive = True
        self.neural_net = Neural_Network(5, 2, HIDDENNODES, 1)
        self.score = 0
        self.color = (
            int(randint(0, POPULATION_SIZE) * (200 / POPULATION_SIZE) + 50),
            int(randint(0, POPULATION_SIZE) * (200 / POPULATION_SIZE) + 50),
            int(randint(0, POPULATION_SIZE) * (200 / POPULATION_SIZE) + 50))

    def reset(self):
        self.score = 0
        self.alive = True
        self.ball.reset()
        self.paddle.reset()

    def copy(self):
        c = Player(self.game, self.pop)
        c.neural_net = self.neural_net.copy()
        c.color = self.color
        return c

    def die(self):
        self.score = self.game.score
        self.alive = False
        self.pop.living -= 1
        if self.score > self.pop.highscore:
            self.pop.highscore = self.score
        if self.pop.living == 0:
            self.pop.winner = self

    def update(self):
        input = [
            -1 if self.paddle.pos.x > self.ball.pos.x else 1,
            (self.ball.pos.y - HALFSCREENSIZE[1]) / HALFSCREENSIZE[1],
            self.ball.vel.x, self.ball.vel.y,
            (self.paddle.pos.x - HALFSCREENSIZE[0]) / HALFSCREENSIZE[0]
        ]
        choices = self.get_choices(input)
        self.paddle.pos.x += abs(choices[0] * PLAYERSPEED)
        self.paddle.pos.x -= abs(choices[1] * PLAYERSPEED)
        self.ball.update()
        self.paddle.update()

    def get_choices(self, input):
        return self.neural_net.run(input)
Пример #4
0
 def __init__(self, game, pop):
     self.pop = pop
     self.game = game
     self.ball = Ball(game)
     self.ball.player = self
     self.paddle = Paddle(game, self.ball)
     self.paddle.player = self
     self.alive = True
     self.neural_net = Neural_Network(5, 2, HIDDENNODES, 1)
     self.score = 0
     self.color = (
         int(randint(0, POPULATION_SIZE) * (200 / POPULATION_SIZE) + 50),
         int(randint(0, POPULATION_SIZE) * (200 / POPULATION_SIZE) + 50),
         int(randint(0, POPULATION_SIZE) * (200 / POPULATION_SIZE) + 50))
Пример #5
0
    def setUp(self):
        self.racket = Racket(constants.SCREEN_MARGIN, 10)
        self.racket.dimension["height"] = 70
        self.racket2 = Racket(constants.SCREEN_WIDTH - constants.SCREEN_MARGIN - 10, 10)
        self.racket2.dimension["height"] = 70

        self.ball = Ball()
        self.ball.direction["y"] = 1
        self.ball.direction["x"] = 1
        self.ball.speeds["x"] = 1
        self.ball.speeds["y"] = 1
Пример #6
0
def round_init(gd: GameData):
    gd.paddleA = Paddle(WHITE, PADDLE_SIZE[0], PADDLE_SIZE[1])
    gd.paddleA.x = 20
    gd.paddleA.y = (PLAY_AREA[1] / 2 - PADDLE_SIZE[1] / 2) + BANNER_HEIGHT

    gd.paddleB = Paddle(WHITE, PADDLE_SIZE[0], PADDLE_SIZE[1])
    gd.paddleB.x = PLAY_AREA[0] - 20 - PADDLE_SIZE[0]
    gd.paddleB.y = (PLAY_AREA[1] / 2 - PADDLE_SIZE[1] / 2) + BANNER_HEIGHT

    gd.ball = Ball(RED, BALL_SIZE[0], BALL_SIZE[1], gd.serve)
    gd.ball.x = PLAY_AREA[0] / 2
    gd.ball.y = (PLAY_AREA[1] / 2) + BANNER_HEIGHT - BALL_SIZE[1]

    all_sprites_list = pygame.sprite.Group()
Пример #7
0
 def add_ball(self):
     ball = Ball()
     self.all_sprites_list.add(ball)
     self.ball_list.add(ball)
Пример #8
0
        x0 = settings.margin + (settings.brick_width + settings.margin) * i
        y0 = window.height - ((settings.brick_height + settings.margin) * (j + 1))
        bricks.append(Rectangle(x0, y0, settings.brick_width, settings.brick_height, color=colors[j]))

# Set up paddle

paddle = Rectangle(window.width / 2. - settings.paddle_width / 2.,
                  0,
                  settings.paddle_width,
                  settings.paddle_height,
                  side_bounce=True)

# Set up ball

ball = Ball(window.width / 2.,
            settings.empty_height / 2.,
            settings.ball_radius,
            random.uniform(-5, 5), 400)

playing = True


def update(dt):

    global playing

    if not playing:
        return

    ball.move(dt)

    segment = ball.check_collision(window_edges)
Пример #9
0
def game_screen(window):
    global timer
    # Variável para o ajuste de velocidade
    clock = pygame.time.Clock()
    assets = load_assets()

    all_sprites = pygame.sprite.Group()
    # Criando os jogadores
    player1 = Player(assets['player1_img'], 1)
    player2 = Player(assets['player2_img'], 2)
    all_sprites.add(player1)
    all_sprites.add(player2)

    # Criando o array das bolas
    all_balls = pygame.sprite.Group()

    #inicia e cria a fonte
    pygame.font.init()
    font = pygame.font.Font(None, 48)

    pont = [0, 0]  #array de apoio para detectar alteraçao na pontuação

    state = PLAYING
    # ===== Loop principal =====
    pygame.mixer.music.play(loops=-1)
    while state == PLAYING:
        clock.tick(FPS)
        timer += 1
        if timer > FPS * 10:  #cria uma nova bola apos o timer
            timer = 0
            bola = Ball(assets['ball_img'])
            #definir a direção e a velocidade inicial da bola
            a = 1  #variavel da direção da bola
            if Points[0] > pont[
                    0]:  #se o player 1 acabou de ganhar um ponto, a primeira bola vai ir para seu oposto
                pont[0] += 1
                a = 1
            if Points[1] > pont[
                    1]:  #se o player 2 acabou de ganhar um ponto, a primeira bola vai ir para seu oposto
                pont[1] += 1
                a = -1
            if len(
                    all_balls
            ) % 2 == 0:  #apos a primeira bola, as seguintes apareceram alternando as direções
                bola.speedx = a * ball_speed
            else:
                bola.speedx = a * ball_speed
            all_sprites.add(bola)
            all_balls.add(bola)

        for bolinha in all_balls:  #atualiza as condiçoes das bolinhas
            # colisao da bola com os players, que randomiza os valores da direção
            #player1
            if bolinha.rect.left < player1.rect.right + contato and bolinha.rect.left > player1.rect.right and bolinha.rect.top < player1.rect.bottom and bolinha.rect.bottom > player1.rect.top:
                assets['pew_sound'].play()
                rng = random.randint(12, 20)
                angulo = (rng * math.pi) / 16
                bolinha.speedx = -(ball_speed * math.cos(angulo))
                bolinha.speedy = ball_speed * math.sin(angulo)
            #player2
            if bolinha.rect.right > player2.rect.left - contato and bolinha.rect.right < player2.rect.left and bolinha.rect.top < player2.rect.bottom and bolinha.rect.bottom > player2.rect.top:
                assets['pew_sound'].play()
                rng = random.randint(12, 20)
                angulo = (rng * math.pi) / 16
                bolinha.speedx = ball_speed * math.cos(angulo)
                bolinha.speedy = ball_speed * math.sin(angulo)
            #renicia as bolinhas caso alg pontue
            if bolinha.rect.left > WIDTH:  #player 1 ganha ponto
                assets['destroy_sound'].play()
                bolinha.rect.centerx = WIDTH / 2
                bolinha.rect.centery = HEIGHT / 2
                bolinha.speedx = ball_speed
                bolinha.speedy = 0
                Points[0] += 1
                timer = 8 * FPS
                for bolinha in all_balls:
                    bolinha.kill()

            if bolinha.rect.right < 0:  #player 2 ganha ponto
                assets['destroy_sound'].play()
                bolinha.rect.centerx = WIDTH / 2
                bolinha.rect.centery = HEIGHT / 2
                bolinha.speedx = -ball_speed
                bolinha.speedy = 0
                Points[1] += 1
                timer = 8 * FPS
                for bolinha in all_balls:
                    bolinha.kill()

        # ----- Trata eventos
        for event in pygame.event.get():
            # ----- Verifica consequências
            if event.type == pygame.QUIT:
                state = DONE
            # Só verifica o teclado se está no estado de jogo
            if state == PLAYING:
                # Verifica se apertou alguma tecla.
                if event.type == pygame.KEYDOWN:
                    # Dependendo da tecla, altera a velocidade.
                    #player1
                    if event.key == pygame.K_w:
                        player1.speedy = -10
                    if event.key == pygame.K_s:
                        player1.speedy = 10
                    #player2
                    if event.key == pygame.K_UP:
                        player2.speedy = -10
                    if event.key == pygame.K_DOWN:
                        player2.speedy = 10
                # Verifica se soltou alguma tecla.
                if event.type == pygame.KEYUP:
                    # Dependendo da tecla, altera a velocidade.
                    #player1
                    if event.key == pygame.K_w:
                        player1.speedy = 0
                    if event.key == pygame.K_s:
                        player1.speedy = 0
                    #player2
                    if event.key == pygame.K_UP:
                        player2.speedy = 0
                    if event.key == pygame.K_DOWN:
                        player2.speedy = 0

        # Atualizando a posição dos sprites
        all_sprites.update()

        #atualiza a tela
        window.fill(BLACK)
        window.blit(assets['background'], (0, 0))
        all_sprites.draw(window)

        # Desenhando o score
        text_surface = font.render("{}   {}".format(Points[0], Points[1]),
                                   True, (0, 255, 0))
        text_rect = text_surface.get_rect()
        text_rect.midtop = (WIDTH / 2, 10)
        window.blit(text_surface, text_rect)

        #verifica se a quantidade de pontos para dar game over
        for pontos in Points:
            if pontos >= 3:
                state = GAMEOVER
                #reenicia todas as codições dos jogadores
                player1.speedy = 0
                player2.speedy = 0
                player1.rect.centery = HEIGHT / 2
                player2.rect.centery = HEIGHT / 2
        pygame.display.update()  # Mostra o novo frame para o jogador
    pygame.mixer.music.stop()  #para a musica
    return state
Пример #10
0
invisibility_duration = 0
crease_duration = 0
increase_duration = 0

bonuses = pygame.sprite.RenderPlain()
allblocks = pygame.sprite.RenderPlain()

# Create the player paddle object
player_casual = Player(80, 10)
player_crease = Player(40, 10)
player_increase = Player(120,10)

player = player_casual

# Create the ball
ball = Ball( (p_centerx, 590) )


blocks = [permeability_blocks, invisibility_blocks, crease_blocks,
   increase_blocks, other_blocks]

def draw_level(n):
   top = 80
   left = 100
   global blocks, allblocks
   if n == 1:
      for i in range(4):
         for j in range(15):
            1
            #block = Kafel(kafelek[i], left + j*(k_width+2), top)
            #blocks[i].add(block)
Пример #11
0
class Breakout(object):

    def __init__(self, screen, clock, res):

        self.res = res
        self.screen = screen
        self.clock = clock

        self.bg = pygame.image.load('bg.bmp')
        pygame.transform.scale(self.bg ,(self.res[0], self.res[1]))
        self.linethickness = rounder(self.res[0]/160)

        pygame.draw.line(self.bg, pygame.Color("white"),
            (self.res[0]*0.2375-self.linethickness, self.res[0]/16),
                (self.res[0]*0.2375-self.linethickness,self.res[1]), self.linethickness)

        pygame.draw.line(self.bg, pygame.Color("white"),
            (self.res[0]*0.7625+self.linethickness, self.res[0]/16),
                (self.res[0]*0.7625+self.linethickness, self.res[1]), self.linethickness)

        pygame.draw.line(self.bg, pygame.Color("white"),
            (self.res[0]*0.2375-self.linethickness,
                (self.res[0]/16 + self.linethickness*0.4)),
                    (self.res[0]*0.7625+self.linethickness,
                        (self.res[0]/16 + self.linethickness*0.4)), self.linethickness)

        self.screen.blit(self.bg, (0,0))
        pygame.display.flip()

        self.levelcount = 0

        self.racket = Racket('yellow', (self.res[0]*0.5, self.res[1]-40), self.res)

        self.score = Score(self.res)

        self.lives = Lives(self.res)

        self.currentpowerup = None
        self.powerupdrop = 60 * 15

        self.enteringname = False


    def run(self):

        self.ball = Ball("yellow", (self.res[0]*0.475, self.res[1]-45), self.racket,
                    self.levelLoader(self.levelcount), self.res)

        self.keymap = {
            pygame.K_SPACE: [self.ball.start, nop],
            pygame.K_LEFT: [self.racket.left, self.racket.right],
            pygame.K_RIGHT: [self.racket.right, self.racket.left]
            }

        self.isrunning = True

        self.sprites = pygame.sprite.RenderUpdates([self.score, self.lives, self.ball, self.racket])

        while self.isrunning:

            self.blockimages = pygame.sprite.RenderUpdates(self.blocks)

            self.managePowerups()

            self.blockimages.update()
            self.blockimages.draw(self.screen)

            self.sprites.update()
            self.sprites.draw(self.screen)

            pygame.display.flip()
            self.sprites.clear(self.screen, self.bg)
            self.blockimages.clear(self.screen, self.bg)


            self.events = pygame.event.get()
            for event in self.events:
                if (event.type == QUIT) or ((event.type == KEYUP) and (event.key == K_ESCAPE)):
                    menu(self.screen, self.clock, self.res)

                if (event.type == pygame.KEYDOWN) and (event.key in self.keymap):
                    self.keymap[event.key][0]()
                if (event.type == pygame.KEYUP) and (event.key in self.keymap):
                    self.keymap[event.key][1]()
                if (event.type == pygame.USEREVENT):
                    if event.event == 'score':
                        self.score.update(event.score)
                    elif event.event == 'lives':
                        self.lives.update(event.lives)
                        if self.lives.lives == 0:
                            screen_message("Game Over!", self.screen, self.res)
                            time.sleep(1)
                            self.screen.blit(self.bg, (0,0))
                            pygame.display.flip()
                            self.gameOver()
                    else:
                      print event

            if len(self.blocks) == 0 and self.levelcount < 4:
                screen_message("Level complete", self.screen, self.res)
                self.levelcount += 1
                time.sleep(1)
                self.screen.blit(self.bg, (0,0))
                pygame.display.flip()
                self.ball.reset()
                self.ball.blocks = self.levelLoader(self.levelcount)

            elif len(self.blocks) == 0 and self.levelcount == 4:
                screen_message("You win!!!", self.screen, self.res)
                time.sleep(1)
                self.screen.blit(self.bg, (0,0))
                pygame.display.flip()
                self.gameOver()

            self.clock.tick(60)


    def levelLoader(self, levelcount):

            self.racket.reset()

            screen_message("Level " + str(self.levelcount+1), self.screen, self.res)
            time.sleep(1)
            self.screen.blit(self.bg, (0,0))
            pygame.display.flip()

            levels = [
                [0, 4, 4, 10],
                [2, 5, 3, 11],
                [1, 5, 2, 12],
                [0, 6, 1, 13],
                [0, 6, 0, 14]
                #[0, 1, 0, 1],
                #[0, 1, 0, 1],
                #[0, 1, 0, 1],
                #[0, 1, 0, 1],
                #[0, 1, 0, 1]
            ]

            self.blocks = []
            for i in xrange(levels[self.levelcount][0], levels[self.levelcount][1]):
                for j in xrange(levels[self.levelcount][2], levels[self.levelcount][3]):
                    self.blocks.append(Block(1, (randint(5,240),randint(5,240),randint(5,240)),
                        (i,j), self.res))

            return self.blocks

    def managePowerups(self):

        if self.ball.dead and self.currentpowerup is not None:
            if self.currentpowerup.collected is True:
                self.currentpowerup.countdown = 0

        if self.currentpowerup is None:
            if not self.ball.dead:
                self.powerupdrop -= 1

                if self.powerupdrop <= 0:

                    droppercentages = [
                    (10, '1up'),
                    (0, 'slowball'),
                    (100, 'bigracket')
                    ]

                    choice = uniform(0, 100)
                    for chance, type in droppercentages:
                        if choice <= chance:
                            self.currentpowerup = Powerup(type, self.res)
                            self.sprites.add(self.currentpowerup)
                            break
            return

        if not self.currentpowerup.collected:

            if self.racket.rect.colliderect(self.currentpowerup.rect):
                if self.currentpowerup.type == 'bigracket':
                    self.racket.grow()
                elif self.currentpowerup.type == 'slowball':
                    self.ball.slowDown()
                elif self.currentpowerup.type == '1up':
                    self.lives.addLife()

                self.currentpowerup.collected = True
                self.sprites.remove(self.currentpowerup)

            else:
                alive = self.currentpowerup.update()
                if not alive:
                    self.sprites.remove(self.currentpowerup)
                    self.currentpowerup = None
                    self.powerupdrop = randint(60*5, 60*15)

        elif self.currentpowerup.countdown > 0:
            self.currentpowerup.countdown -= 1

        else:
            if self.currentpowerup is not None:

                if self.currentpowerup.type == 'bigracket':
                    self.racket.shrink()
                elif self.currentpowerup.type == 'slowball':
                    self.ball.speedUp()

                self.currentpowerup = None

                self.powerupdrop = randint(60*15, 60*25)

    def gameOver(self):

        highscores = self.parseHighScores()

        if self.score.score > int(highscores[-1][1]):
            screen_message("Enter Name:", self.screen, self.res)

            self.enteringname = True

            self.name = NameSprite(self.res, (self.res[0]/2, self.res[1]/3), rounder(self.res[0]*0.1))
            self.namesprite = pygame.sprite.RenderUpdates(self.name)

            while self.enteringname:

                for event in pygame.event.get():
                    if event.key == pygame.K_BACKSPACE:
                        self.name.removeLetter()
                    elif event.key == pygame.K_RETURN:
                        self.nameEntered()
                    elif event.type == pygame.KEYDOWN:
                        try:
                            char = chr(event.key)
                            if str(char) in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_':
                                 self.name.addLetter(char)
                        except:
                            pass

                    self.namesprite.update()
                    self.namesprite.draw(self.screen)
                    pygame.display.flip()
                    self.namesprite.clear(self.screen, self.bg)
        else:
            self.showHighScores(highscores)

    def nameEntered(self):
        username = self.name.text

        self.screen.blit(self.bg, (0,0))
        pygame.display.flip

        highscores = self.parseHighScores()

        newscores = []

        for name, score in highscores:
            if self.score.score > int(score):
                newscores.append((username, str(self.score.score)))
                self.score.score = 0
            newscores.append((name, score))
        newscores = newscores[0:10]

        highscorefile = 'highscores.txt'
        f = open(highscorefile, 'w')
        for name, score in newscores:
            f.write("%s: %s\n" % (name, score))
        f.close()

        self.showHighScores(newscores)

    def parseHighScores(self):
        highscorefile = 'highscores.txt'
        if os.path.isfile(highscorefile):
            f = open(highscorefile, 'r')
            lines = f.readlines()
            scores = []

            for line in lines:
                scores.append( line.strip().split(':') )
            return scores
        else:
            f = open (highscorefile, 'w')
            f.write("""JJJ:0000
III:0000
HHH:0000
GGG:0000
FFF:0000
EEE:0000
DDD:0000
CCC:0000
BBB:0000
AAA:0000""")
            f.close()
            return self.parseHighScores()

    def showHighScores(self, scores):

        font = pygame.font.Font(None, rounder(self.res[0]*0.05))
        color = pygame.Color("white")

        for i in range(len(scores)):
            name, score = scores[i]
            nameimage = font.render(name, True, color)
            namerect = nameimage.get_rect()
            namerect.left = rounder(self.res[0]*0.3)
            namerect.centery = rounder(self.res[0]/8)+(i*(namerect.height + rounder(self.res[0]/40)))
            self.screen.blit(nameimage, namerect)

            scoreimage = font.render(score, True, color)
            scorerect = scoreimage.get_rect()
            scorerect.right = rounder(self.res[0]*0.7)
            scorerect.centery = namerect.centery
            self.screen.blit(scoreimage, scorerect)

        pygame.display.flip()
        time.sleep(3)
        menu(self.screen, self.clock, self.res)
Пример #12
0
    def run(self):

        self.ball = Ball("yellow", (self.res[0]*0.475, self.res[1]-45), self.racket,
                    self.levelLoader(self.levelcount), self.res)

        self.keymap = {
            pygame.K_SPACE: [self.ball.start, nop],
            pygame.K_LEFT: [self.racket.left, self.racket.right],
            pygame.K_RIGHT: [self.racket.right, self.racket.left]
            }

        self.isrunning = True

        self.sprites = pygame.sprite.RenderUpdates([self.score, self.lives, self.ball, self.racket])

        while self.isrunning:

            self.blockimages = pygame.sprite.RenderUpdates(self.blocks)

            self.managePowerups()

            self.blockimages.update()
            self.blockimages.draw(self.screen)

            self.sprites.update()
            self.sprites.draw(self.screen)

            pygame.display.flip()
            self.sprites.clear(self.screen, self.bg)
            self.blockimages.clear(self.screen, self.bg)


            self.events = pygame.event.get()
            for event in self.events:
                if (event.type == QUIT) or ((event.type == KEYUP) and (event.key == K_ESCAPE)):
                    menu(self.screen, self.clock, self.res)

                if (event.type == pygame.KEYDOWN) and (event.key in self.keymap):
                    self.keymap[event.key][0]()
                if (event.type == pygame.KEYUP) and (event.key in self.keymap):
                    self.keymap[event.key][1]()
                if (event.type == pygame.USEREVENT):
                    if event.event == 'score':
                        self.score.update(event.score)
                    elif event.event == 'lives':
                        self.lives.update(event.lives)
                        if self.lives.lives == 0:
                            screen_message("Game Over!", self.screen, self.res)
                            time.sleep(1)
                            self.screen.blit(self.bg, (0,0))
                            pygame.display.flip()
                            self.gameOver()
                    else:
                      print event

            if len(self.blocks) == 0 and self.levelcount < 4:
                screen_message("Level complete", self.screen, self.res)
                self.levelcount += 1
                time.sleep(1)
                self.screen.blit(self.bg, (0,0))
                pygame.display.flip()
                self.ball.reset()
                self.ball.blocks = self.levelLoader(self.levelcount)

            elif len(self.blocks) == 0 and self.levelcount == 4:
                screen_message("You win!!!", self.screen, self.res)
                time.sleep(1)
                self.screen.blit(self.bg, (0,0))
                pygame.display.flip()
                self.gameOver()

            self.clock.tick(60)
Пример #13
0
def game_screen(window):
    # Variável para o ajuste de velocidade
    clock = pygame.time.Clock()

    # Armazenando assets
    assets = load_assets()

    # Criação de grupos de sprites (cria grupos diferentes para cada cor de bloco)
    all_balls = pygame.sprite.Group()
    all_sprites = pygame.sprite.Group()
    all_r_blocks = pygame.sprite.Group()
    all_b_blocks = pygame.sprite.Group()
    all_g_blocks = pygame.sprite.Group()
    all_y_blocks = pygame.sprite.Group()

    groups = {}
    groups['all_balls'] = all_balls
    groups['all_sprites'] = all_sprites
    groups['all_r_blocks'] = all_r_blocks
    groups['all_b_blocks'] = all_b_blocks
    groups['all_g_blocks'] = all_g_blocks
    groups['all_y_blocks'] = all_y_blocks

    # Criando elementos do jogo:

    # Bola (é inserida num grupo de bolas para a execução da colisão com o 'bat')
    ball = Ball(assets)
    all_sprites.add(ball)
    all_balls.add(ball)
    # Bat
    player = Bat(assets)
    all_sprites.add(player)

    # Blocos (c--> coluna, l--> linha)
    for c in range(1, 13):
        for l in range(1, 3):
            block = Block(assets, BLOCK_IMG_RED, l, c)
            all_sprites.add(block)
            all_r_blocks.add(block)
        for l in range(3, 5):
            block = Block(assets, BLOCK_IMG_BLU, l, c)
            all_sprites.add(block)
            all_b_blocks.add(block)
        for l in range(5, 7):
            block = Block(assets, BLOCK_IMG_GRN, l, c)
            all_sprites.add(block)
            all_g_blocks.add(block)
        for l in range(7, 9):
            block = Block(assets, BLOCK_IMG_YLW, l, c)
            all_sprites.add(block)
            all_y_blocks.add(block)

    INIT = 0
    GAME = 1
    QUIT = 2

    state = GAME

    # Dicionário de eventos do teclado
    keys_down = {}

    # Pontuação e vidas
    score = 0
    lives = 3

    # ===== Loop principal =====
    # pygame.mixer.music.play(loops=-1)
    while state != QUIT:
        clock.tick(FPS)

        # ----- Trata eventos
        for event in pygame.event.get():
            # ----- Verifica consequências
            if event.type == pygame.QUIT:
                state = QUIT
            # Só verifica o teclado se está no estado de jogo
            if state == GAME:
                # Verifica se apertou alguma tecla
                if event.type == pygame.KEYDOWN:
                    # Dependendo da tecla, altera a velocidade
                    keys_down[event.key] = True
                    if event.key == pygame.K_LEFT:
                        player.speedx -= 15
                    if event.key == pygame.K_RIGHT:
                        player.speedx += 15
                # Verifica se soltou alguma tecla
                if event.type == pygame.KEYUP:
                    # Dependendo da tecla, altera a velocidade
                    if event.key in keys_down and keys_down[event.key]:
                        if event.key == pygame.K_LEFT:
                            player.speedx += 15
                        if event.key == pygame.K_RIGHT:
                            player.speedx -= 15

        # Atualiza estado do jogo
        all_sprites.update()

        if state == GAME:

            # ----- Colisões:

            # Colisão bola-bat
            if pygame.sprite.spritecollide(player, all_balls, False,
                                           pygame.sprite.collide_mask):
                assets[BAT_SND].play()
                ball.speedy *= -1

            # Colisões bola-bloco

            # Bola - Bloco vermelho
            block_hits = pygame.sprite.spritecollide(
                ball, all_r_blocks, True, pygame.sprite.collide_mask)
            for block in block_hits:
                assets[BLOCK_SND_1].play()
                ball.speedy *= -1
                score += 35
            # Bola - Bloco azul
            block_hits = pygame.sprite.spritecollide(
                ball, all_b_blocks, True, pygame.sprite.collide_mask)
            for block in block_hits:
                assets[BLOCK_SND_1].play()
                ball.speedy *= -1
                score += 25
            # Bola - Bloco verde
            block_hits = pygame.sprite.spritecollide(
                ball, all_g_blocks, True, pygame.sprite.collide_mask)
            for block in block_hits:
                assets[BLOCK_SND_1].play()
                ball.speedy *= -1
                score += 15
            # Bola - Bloco amarelo
            block_hits = pygame.sprite.spritecollide(
                ball, all_y_blocks, True, pygame.sprite.collide_mask)
            for block in block_hits:
                assets[BLOCK_SND_1].play()
                ball.speedy *= -1
                score += 5

            # Se o topo da bola passar do limite da tela (se ela cair):
            if ball.rect.top > SH:
                ball.kill()
                lives -= 1
                # Aguardo de 2 segundos
                pygame.time.delay(2000)

                # Se não houver mais vidas disponíveis, o jogo acaba
                if lives == 0:
                    state = END
                else:
                    # Caso contrário, a bola será redesenhada na tela
                    state = GAME
                    ball = Ball(assets)
                    all_sprites.add(ball)
                    all_balls.add(ball)

        # ----- Gera saídas
        window.fill(BLACK)
        window.blit(assets[BACKGROUND], (0, 0))
        # Desenhando todos os sprites
        all_sprites.draw(window)

        # Desenhando o score
        text_surface = assets[GAME_FNT].render('SCORE :{} '.format(score),
                                               True, WHITE)
        text_rect = text_surface.get_rect(x=230, y=570)
        window.blit(text_surface, text_rect)

        # Desenhando as vidas
        text_surface = assets[GAME_FNT].render('LIVES :{} '.format(lives),
                                               True, WHITE)
        text_rect = text_surface.get_rect(x=10, y=570)
        window.blit(text_surface, text_rect)

        # Mostra o novo frame para o jogador
        pygame.display.update()

    return state
Пример #14
0
class TestBall(unittest.TestCase):
    def setUp(self):
        self.racket = Racket(constants.SCREEN_MARGIN, 10)
        self.racket.dimension["height"] = 70
        self.racket2 = Racket(constants.SCREEN_WIDTH - constants.SCREEN_MARGIN - 10, 10)
        self.racket2.dimension["height"] = 70

        self.ball = Ball()
        self.ball.direction["y"] = 1
        self.ball.direction["x"] = 1
        self.ball.speeds["x"] = 1
        self.ball.speeds["y"] = 1

    def test_collision_w_racket_1(self):
        x_pos = self.racket.position["x"] + self.racket.dimension["width"]
        self.ball.position["x"] = x_pos
        self.ball.position["y"] = 30
        self.ball.direction["x"] = -1
        self.check_ball_pos_update_rkt1(x_pos)

    def check_ball_pos_update_rkt1(self, x_pos):
        self.ball.update_position(self.racket, self.racket2)
        self.assertEqual(1, self.ball.direction["x"])
        self.assertEqual(x_pos + self.ball.speeds["x"], self.ball.position["x"])

    def test_partial_collision_w_racket_1(self):
        """Tests when the ball is partially hits the top of racket 1"""
        x_pos = self.racket.position["x"] + self.racket.dimension["width"]
        self.ball.position["x"] = x_pos
        self.racket.position["y"] = 50
        self.ball.position["y"] = 45
        self.ball.direction["x"] = -1
        self.check_ball_pos_update_rkt1(x_pos)

    def test_collision_w_racket1_depending_on_speed(self):
        """We have a problem with ball.speed > 1. The position increment can
        avoid the exact collision. We have to introduce a tolerance"""
        self.ball.speeds["x"] = 2
        x_pos = self.racket.position["x"] + self.racket.dimension["width"] - 1
        self.ball.position["x"] = x_pos
        self.ball.position["y"] = 30
        self.ball.direction["x"] = -1
        self.check_ball_pos_update_rkt1(x_pos)

    def test_collision_w_racket_2(self):
        x_pos = self.racket2.position["x"] - self.ball.dimension["width"]
        self.ball.position["x"] = x_pos
        self.ball.position["y"] = 30
        self.ball.update_position(self.racket, self.racket2)
        self.assertEqual(-1, self.ball.direction["x"])
        self.assertEqual(x_pos - 1, self.ball.position["x"])

    def test_partial_collision_w_racket_2(self):
        x_pos = self.racket2.position["x"] - self.ball.dimension["width"]
        self.ball.position["x"] = x_pos
        self.racket2.position["y"] = 50
        self.ball.position["y"] = 45
        self.ball.update_position(self.racket, self.racket2)
        self.assertEqual(-1, self.ball.direction["x"])
        self.assertEqual(x_pos - 1, self.ball.position["x"])

    def test_collision_w_racket2_depending_on_speed(self):
        """We have a problem with ball.speed > 1. The position increment can
        avoid the exact collision. We have to introduce a tolerance"""
        self.ball.speeds["x"] = 2
        x_pos = self.racket2.position["x"] - self.ball.dimension["width"] + 1
        self.ball.position["x"] = x_pos
        self.ball.position["y"] = 30
        self.ball.direction["x"] = 1
        self.ball.update_position(self.racket, self.racket2)
        self.assertEqual(-1, self.ball.direction["x"])
        self.assertEqual(x_pos - self.ball.speeds["x"], self.ball.position["x"])

    def test_collision_on_top(self):
        y_pos = constants.SCREEN_MARGIN - 1
        self.ball.position["y"] = y_pos
        self.ball.direction["y"] = -1
        self.ball.update_position(self.racket, self.racket2)
        self.assertEqual(1, self.ball.direction["y"])
        self.assertEqual(y_pos + 1, self.ball.position["y"])

    def test_collision_on_bottom(self):
        y_pos = constants.SCREEN_HEIGHT
        y_pos -= constants.SCREEN_MARGIN
        y_pos -= self.ball.dimension["height"]
        y_pos += 1
        self.ball.position["y"] = y_pos
        self.ball.direction["y"] = 1
        self.ball.update_position(self.racket, self.racket2)
        self.assertEqual(-1, self.ball.direction["y"])
        self.assertEqual(y_pos - 1, self.ball.position["y"])

    def test_reupdate_position(self):
        self.ball.position["x"] = 42
        self.ball.position["y"] = 69
        self.ball.direction["x"] = -1
        self.ball.speeds["x"] = 2
        self.ball.speeds["y"] = 4

        self.ball.reset_position()
        self.assertEqual(constants.SCREEN_WIDTH / 2 - 5, self.ball.position["x"])
        self.assertEqual(constants.SCREEN_HEIGHT / 2 - 5, self.ball.position["y"])
        self.assertEqual(1, self.ball.direction["x"])
        self.assertEqual(1, self.ball.direction["y"])
        self.assertEqual(config.BALL_SPEED, self.ball.speeds["x"])
        self.assertEqual(config.BALL_SPEED, self.ball.speeds["y"])

    def test_ball_vert_speed_after_impact_r1(self):
        x_pos = self.racket.position["x"] + self.racket.dimension["width"]
        self.ball.position["x"] = x_pos
        self.ball.direction["x"] = -1
        self.ball.position["y"] = 30
        self.racket.acceleration = 3
        self.ball.speeds["y"] = 1
        self.ball.update_position(self.racket, self.racket2)

        actual = self.ball.speeds["y"]
        self.assertEqual(3, actual)

    def test_ball_vert_speed_after_impact_r2(self):
        x_pos = self.racket2.position["x"] - self.ball.dimension["width"]
        self.ball.position["x"] = x_pos
        self.ball.position["y"] = 30
        self.racket2.acceleration = 3
        self.ball.speeds["y"] = 1
        self.ball.update_position(self.racket, self.racket2)

        actual = self.ball.speeds["y"]
        self.assertEqual(3, actual)