コード例 #1
0
def game_screen(window):
    # Variável para o ajuste de velocidade
    clock = pygame.time.Clock()

    assets = load_assets()

    # Criando um grupo de meteoros
    all_sprites = pygame.sprite.Group()
    all_meteors = pygame.sprite.Group()
    all_bullets = pygame.sprite.Group()
    groups = {}
    groups['all_sprites'] = all_sprites
    groups['all_meteors'] = all_meteors
    groups['all_bullets'] = all_bullets

    # Criando o jogador
    player = Ship(groups, assets)
    all_sprites.add(player)
    # Criando os meteoros
    for i in range(8):
        meteor = Meteor(assets)
        all_sprites.add(meteor)
        all_meteors.add(meteor)

    DONE = 0
    PLAYING = 1
    EXPLODING = 2
    state = PLAYING

    keys_down = {}
    score = 0
    lives = 3

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

        # ----- 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.
                    keys_down[event.key] = True
                    if event.key == pygame.K_LEFT:
                        player.speedx -= 8
                    if event.key == pygame.K_RIGHT:
                        player.speedx += 8
                    if event.key == pygame.K_SPACE:
                        player.shoot()
                # 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 += 8
                        if event.key == pygame.K_RIGHT:
                            player.speedx -= 8

        # ----- Atualiza estado do jogo
        # Atualizando a posição dos meteoros
        all_sprites.update()

        if state == PLAYING:
            # Verifica se houve colisão entre tiro e meteoro
            hits = pygame.sprite.groupcollide(all_meteors, all_bullets, True, True, pygame.sprite.collide_mask)
            for meteor in hits: # As chaves são os elementos do primeiro grupo (meteoros) que colidiram com alguma bala
                # O meteoro e destruido e precisa ser recriado
                assets[DESTROY_SOUND].play()
                m = Meteor(assets)
                all_sprites.add(m)
                all_meteors.add(m)

                # No lugar do meteoro antigo, adicionar uma explosão.
                explosao = Explosion(meteor.rect.center, assets)
                all_sprites.add(explosao)

                # Ganhou pontos!
                score += 100
                if score % 1000 == 0:
                    lives += 1

            # Verifica se houve colisão entre nave e meteoro
            hits = pygame.sprite.spritecollide(player, all_meteors, True, pygame.sprite.collide_mask)
            if len(hits) > 0:
                # Toca o som da colisão
                assets[BOOM_SOUND].play()
                player.kill()
                lives -= 1
                explosao = Explosion(player.rect.center, assets)
                all_sprites.add(explosao)
                state = EXPLODING
                keys_down = {}
                explosion_tick = pygame.time.get_ticks()
                explosion_duration = explosao.frame_ticks * len(explosao.explosion_anim) + 400
        elif state == EXPLODING:
            now = pygame.time.get_ticks()
            if now - explosion_tick > explosion_duration:
                if lives == 0:
                    state = DONE
                else:
                    state = PLAYING
                    player = Ship(groups, assets)
                    all_sprites.add(player)

        # ----- Gera saídas
        window.fill(BLACK)  # Preenche com a cor branca
        window.blit(assets[BACKGROUND], (0, 0))
        # Desenhando meteoros
        all_sprites.draw(window)

        # Desenhando o score
        text_surface = assets[SCORE_FONT].render("{:08d}".format(score), True, YELLOW)
        text_rect = text_surface.get_rect()
        text_rect.midtop = (WIDTH / 2,  10)
        window.blit(text_surface, text_rect)

        # Desenhando as vidas
        text_surface = assets[SCORE_FONT].render(chr(9829) * lives, True, RED)
        text_rect = text_surface.get_rect()
        text_rect.bottomleft = (10, HEIGHT - 10)
        window.blit(text_surface, text_rect)

        pygame.display.update()  # Mostra o novo frame para o jogador
コード例 #2
0
def main():
    # Initialize everything
    pygame.mixer.pre_init(11025, -16, 2, 512)
    pygame.init()
    screen = pygame.display.set_mode((500, 500))
    pygame.display.set_caption('Shooting Game')
    pygame.mouse.set_visible(0)

# Create the background which will scroll and loop over a set of different
# size stars
    background = pygame.Surface((500, 2000))
    background = background.convert()
    background.fill((0, 0, 0))
    backgroundLoc = 1500
    finalStars = deque()
    for y in range(0, 1500, 30):
        size = random.randint(2, 5)
        x = random.randint(0, 500 - size)
        if y <= 500:
            finalStars.appendleft((x, y + 1500, size))
        pygame.draw.rect(
            background, (255, 255, 0), pygame.Rect(x, y, size, size))
    while finalStars:
        x, y, size = finalStars.pop()
        pygame.draw.rect(
            background, (255, 255, 0), pygame.Rect(x, y, size, size))

# Display the background
    screen.blit(background, (0, 0))
    pygame.display.flip()

# Prepare game objects
    speed = 1.5
    MasterSprite.speed = speed
    alienPeriod = 60 / speed
    clockTime = 60  # maximum FPS
    clock = pygame.time.Clock()
    ship = Ship()                                       #sprites의 ship 클래스를 넣는다
    initialAlienTypes = (Siney,Oneeye, Spikey,Eye)
    powerupTypes = (BombPowerup, ShieldPowerup)

    # Sprite groups
    alldrawings = pygame.sprite.Group()
    allsprites = pygame.sprite.RenderPlain((ship,))
    MasterSprite.allsprites = allsprites
    Alien.pool = pygame.sprite.Group(
        [alien() for alien in initialAlienTypes for _ in range(5)])
    Alien.active = pygame.sprite.Group()
    Missile.pool = pygame.sprite.Group([Missile() for _ in range(10)])
    Missile.active = pygame.sprite.Group()
    Explosion.pool = pygame.sprite.Group([Explosion() for _ in range(10)])
    Explosion.active = pygame.sprite.Group()
    bombs = pygame.sprite.Group()
    powerups = pygame.sprite.Group()

    # Sounds
    missile_sound = load_sound('missile.ogg')
    bomb_sound = load_sound('bomb.ogg')
    alien_explode_sound = load_sound('alien_explode.ogg')
    ship_explode_sound = load_sound('ship_explode.ogg')
    load_music('music_loop.ogg')

    alienPeriod = clockTime // 2
    curTime = 0
    aliensThisWave, aliensLeftThisWave, Alien.numOffScreen = 10, 10, 10
    wave = 1
    bombsHeld = 3
    score = 0
    missilesFired = 0
    powerupTime = 10 * clockTime
    powerupTimeLeft = powerupTime
    betweenWaveTime = 3 * clockTime
    betweenWaveCount = betweenWaveTime
    font = pygame.font.Font(None, 36)

    inMenu = True
    hiScores = Database.getScores()
    highScoreTexts = [font.render("NAME", 1, RED),
                      font.render("SCORE", 1, RED),
                      font.render("ACCURACY", 1, RED)]
    highScorePos = [highScoreTexts[0].get_rect(
                      topleft=screen.get_rect().inflate(-100, -100).topleft),
                    highScoreTexts[1].get_rect(
                      midtop=screen.get_rect().inflate(-100, -100).midtop),
                    highScoreTexts[2].get_rect(
                      topright=screen.get_rect().inflate(-100, -100).topright)]
    for hs in hiScores:
        highScoreTexts.extend([font.render(str(hs[x]), 1, BLUE)
                               for x in range(3)])
        highScorePos.extend([highScoreTexts[x].get_rect(
            topleft=highScorePos[x].bottomleft) for x in range(-3, 0)])

    
    main_dir = os.path.split(os.path.abspath(__file__))[0]
    data_dir = os.path.join(main_dir, 'data')
    fullname1 = os.path.join(data_dir, 'ship.png')
    fullname2 = os.path.join(data_dir, 'ship2.png')
    fullname3 = os.path.join(data_dir, 'ship3.png')
    fullname4 = os.path.join(data_dir, 'ship4.png')
    image1 = pygame.image.load(fullname1)
    image2 = pygame.image.load(fullname2)
    image3 = pygame.image.load(fullname3)
    image4 = pygame.image.load(fullname4)

    #imageload = [font.render("FIRST SELECT SHIP",1, RED),
     #            font.render("SECOND SELECT SHIP",1,RED),
     #            font.render("THIRD SELECT SHIP",1,RED)
     #           ]
    #imagePos = [(imageload[0].get_rect(topleft=screen.get_rect().inflate(-100, -100).midbottom)),
    #            (imageload[1].get_rect(topleft=screen.get_rect().inflate(-100, -100).midtop)),
     #           (imageload[2].get_rect(topleft=screen.get_rect().inflate(-100, -100).topright))
     #           ]

   
    title, titleRect = load_image('title.png')
    titleRect.midtop = screen.get_rect().inflate(0, -200).midtop
    startText = font.render('START GAME', 1, BLUE)
    startPos = startText.get_rect(midtop=titleRect.inflate(0, 100).midbottom)
    hiScoreText = font.render('HIGH SCORES', 1, BLUE)
    hiScorePos = hiScoreText.get_rect(topleft=startPos.bottomleft)
    fxText = font.render('SOUND FX ', 1, BLUE)
    fxPos = fxText.get_rect(topleft=hiScorePos.bottomleft)
    fxOnText = font.render('ON', 1, RED)
    fxOffText = font.render('OFF', 1, RED)
    fxOnPos = fxOnText.get_rect(topleft=fxPos.topright)
    fxOffPos = fxOffText.get_rect(topleft=fxPos.topright)
    musicText = font.render('MUSIC', 1, BLUE)
    musicPos = fxText.get_rect(topleft=fxPos.bottomleft)
    musicOnText = font.render('ON', 1, RED)
    musicOffText = font.render('OFF', 1, RED)
    musicOnPos = musicOnText.get_rect(topleft=musicPos.topright)
    musicOffPos = musicOffText.get_rect(topleft=musicPos.topright)
    quitText = font.render('QUIT', 1, BLUE)
    quitPos = quitText.get_rect(topleft=musicPos.bottomleft)
    selectText = font.render('*', 1, BLUE)
    selectPos = selectText.get_rect(topright=startPos.topleft)
    menuDict = {1: startPos, 2: hiScorePos, 3: fxPos, 4: musicPos, 5: quitPos}
    selection = 1
    showHiScores = False
    soundFX = Database.getSound()
    music = Database.getSound(music=True)
    if music and pygame.mixer:
        pygame.mixer.music.play(loops=-1)


    
    title1, titleRect1 = load_image('title.png')
    titleRect1.midtop = screen.get_rect().inflate(0, -200).midtop
    image1 = pygame.image.load(fullname1)
    startPos1 = image1.get_rect(midtop=titleRect1.inflate(0, 100).midbottom)
    image2 = pygame.image.load(fullname2)
    hiScorePos1 = image2.get_rect(topleft=startPos1.bottomleft)
    image3 = pygame.image.load(fullname3)
    fxPos1 = image3.get_rect(topleft=hiScorePos1.bottomleft)
    image4 = pygame.image.load(fullname4)
    fxOnPos1 = image4.get_rect(topleft=fxPos1.bottomleft)

    selectText1 = font.render('*', 1, BLUE)
    selectPos1 = selectText.get_rect(topright=startPos1.topleft)
    menuDict1 = {1: startPos1, 2: hiScorePos1, 3: fxPos1, 4: fxOnPos1}
    selection1 = 1

    
    is_end = True
    while inMenu:
        clock.tick(clockTime)
            

        screen.blit(
            background, (0, 0), area=pygame.Rect(
                0, backgroundLoc, 500, 500))
        backgroundLoc -= speed
        if backgroundLoc - speed <= speed:
            backgroundLoc = 1500

        for event in pygame.event.get():
            if (event.type == pygame.QUIT):
                return
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_RETURN):
                if showHiScores:
                    showHiScores = False
                elif selection == 1:
                    while is_end:
                        clock.tick(clockTime)
                        screen.blit(
                            background, (0, 0), area=pygame.Rect(
                                0, backgroundLoc, 500, 500))
                        backgroundLoc -= speed
                        if backgroundLoc - speed <= speed:
                            backgroundLoc = 1500

                        for event1 in pygame.event.get():
                            if (event1.type == pygame.QUIT):
                                return
                            elif(event1.type == pygame.KEYDOWN
                                 and event1.key == pygame.K_RETURN):
                                if selection1 ==1:
                                    abcd = 'ship.png'
                                    ship.abc(abcd)
                                    is_end = False
                                    inMenu = False 
                                    ship.initializeKeys()
                                    
                                elif selection1 ==2:
                                    abcd = 'ship2.png'
                                    ship.abc(abcd)
                                    is_end = False
                                    inMenu = False 
                                    ship.initializeKeys()
                                    
                                elif selection1 ==3:
                                    abcd = 'ship3.png'
                                    ship.abc(abcd)
                                    is_end = False
                                    inMenu = False 
                                    ship.initializeKeys()
                                    
                                elif selection1 ==4:
                                    abcd = 'ship4.png'
                                    ship.abc(abcd)
                                    is_end = False
                                    inMenu = False 
                                    ship.initializeKeys()
                                    
                            elif (event1.type == pygame.KEYDOWN
                                  and event1.key == pygame.K_w
                                  and selection1 > 1):
                                selection1 -= 1
                            elif (event1.type == pygame.KEYDOWN
                                  and event1.key == pygame.K_s
                                  and selection1 < len(menuDict1)):
                                selection1 += 1
                        selectPos1 = selectText1.get_rect(topright=menuDict1[selection1].topleft)
                        textOverlays1 = zip([image1, image2, image3, image4,selectText1],
                                       [startPos1, hiScorePos1, fxPos1, fxOnPos1,selectPos1])
                        screen.blit(title, titleRect)
                        for txt1, pos1 in textOverlays1:
                            screen.blit(txt1, pos1)
                        pygame.display.flip()
                               
                elif selection == 2:
                    showHiScores = True
                elif selection == 3:
                    soundFX = not soundFX
                    if soundFX:
                        missile_sound.play()
                    Database.setSound(int(soundFX))
                elif selection == 4 and pygame.mixer:
                    music = not music
                    if music:
                        pygame.mixer.music.play(loops=-1)
                    else:
                        pygame.mixer.music.stop()
                    Database.setSound(int(music), music=True)
                elif selection == 5:
                    return
                elif selection ==6:
                    return
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_w
                  and selection > 1
                  and not showHiScores):
                selection -= 1
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_s
                  and selection < len(menuDict)
                  and not showHiScores):
                selection += 1

        selectPos = selectText.get_rect(topright=menuDict[selection].topleft)
        

        if showHiScores:
            textOverlays = zip(highScoreTexts, highScorePos)
       
        else:
            textOverlays = zip([startText, hiScoreText, fxText,
                                musicText, quitText, selectText,
                                fxOnText if soundFX else fxOffText,
                                musicOnText if music else musicOffText],
                               [startPos, hiScorePos, fxPos,
                                musicPos, quitPos, selectPos,
                                fxOnPos if soundFX else fxOffPos,
                                musicOnPos if music else musicOffPos])
            screen.blit(title, titleRect)
        for txt, pos in textOverlays:
            screen.blit(txt, pos)
        pygame.display.flip()

            

       

    while ship.alive:
        clock.tick(clockTime)

        if aliensLeftThisWave >= 20:
            powerupTimeLeft -= 1
        if powerupTimeLeft <= 0:
            powerupTimeLeft = powerupTime
            random.choice(powerupTypes)().add(powerups, allsprites)

    # Event Handling
        for event in pygame.event.get():
            if (event.type == pygame.QUIT
                or event.type == pygame.KEYDOWN
                    and event.key == pygame.K_ESCAPE):
                return
            elif (event.type == pygame.KEYDOWN
                  and event.key in direction.keys()):
                ship.horiz += direction[event.key][0] * speed
                ship.vert += direction[event.key][1] * speed
            elif (event.type == pygame.KEYUP
                  and event.key in direction.keys()):
                ship.horiz -= direction[event.key][0] * speed
                ship.vert -= direction[event.key][1] * speed
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_SPACE):
                Missile.position(ship.rect.midtop)
                missilesFired += 1
                if soundFX:
                    missile_sound.play()
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_b):
                if bombsHeld > 0:
                    bombsHeld -= 1
                    newBomb = ship.bomb()
                    newBomb.add(bombs, alldrawings)
                    if soundFX:
                        bomb_sound.play()

    # Collision Detection
        # Aliens
        for alien in Alien.active:
            for bomb in bombs:
                if pygame.sprite.collide_circle(
                        bomb, alien) and alien in Alien.active:
                    alien.table()
                    Explosion.position(alien.rect.center)
                    missilesFired += 1
                    aliensLeftThisWave -= 1
                    score += 1
                    if soundFX:
                        alien_explode_sound.play()
            for missile in Missile.active:
                if pygame.sprite.collide_rect(
                        missile, alien) and alien in Alien.active:
                    alien.table()
                    missile.table()
                    Explosion.position(alien.rect.center)
                    aliensLeftThisWave -= 1
                    score += 1
                    if soundFX:
                        alien_explode_sound.play()
            if pygame.sprite.collide_rect(alien, ship):
                if ship.shieldUp:
                    alien.table()
                    Explosion.position(alien.rect.center)
                    aliensLeftThisWave -= 1
                    score += 1
                    missilesFired += 1
                    ship.shieldUp = False
                else:
                    ship.alive = False
                    ship.remove(allsprites)
                    Explosion.position(ship.rect.center)
                    if soundFX:
                        ship_explode_sound.play()

        # PowerUps
        for powerup in powerups:
            if pygame.sprite.collide_circle(powerup, ship):
                if powerup.pType == 'bomb':
                    bombsHeld += 1
                elif powerup.pType == 'shield':
                    ship.shieldUp = True
                powerup.kill()
            elif powerup.rect.top > powerup.area.bottom:
                powerup.kill()

    # Update Aliens
        if curTime <= 0 and aliensLeftThisWave > 0:
            Alien.position()
            curTime = alienPeriod
        elif curTime > 0:
            curTime -= 1

    # Update text overlays
        waveText = font.render("Wave: " + str(wave), 1, BLUE)
        leftText = font.render("Aliens Left: " + str(aliensLeftThisWave),
                               1, BLUE)
        scoreText = font.render("Score: " + str(score), 1, BLUE)
        bombText = font.render("Bombs: " + str(bombsHeld), 1, BLUE)

        wavePos = waveText.get_rect(topleft=screen.get_rect().topleft)
        leftPos = leftText.get_rect(midtop=screen.get_rect().midtop)
        scorePos = scoreText.get_rect(topright=screen.get_rect().topright)
        bombPos = bombText.get_rect(bottomleft=screen.get_rect().bottomleft)

        text = [waveText, leftText, scoreText, bombText]
        textposition = [wavePos, leftPos, scorePos, bombPos]

    # Detertmine when to move to next wave
        if aliensLeftThisWave <= 0:
            if betweenWaveCount > 0:
                betweenWaveCount -= 1
                nextWaveText = font.render(
                    'Wave ' + str(wave + 1) + ' in', 1, BLUE)
                nextWaveNum = font.render(
                    str((betweenWaveCount // clockTime) + 1), 1, BLUE)
                text.extend([nextWaveText, nextWaveNum])
                nextWavePos = nextWaveText.get_rect(
                    center=screen.get_rect().center)
                nextWaveNumPos = nextWaveNum.get_rect(
                    midtop=nextWavePos.midbottom)
                textposition.extend([nextWavePos, nextWaveNumPos])
                if wave % 4 == 0:
                    speedUpText = font.render('SPEED UP!', 1, RED)
                    speedUpPos = speedUpText.get_rect(
                        midtop=nextWaveNumPos.midbottom)
                    text.append(speedUpText)
                    textposition.append(speedUpPos)
            elif betweenWaveCount == 0:
                if wave % 4 == 0:
                    speed += 0.5
                    MasterSprite.speed = speed
                    ship.initializeKeys()
                    aliensThisWave = 10
                    aliensLeftThisWave = Alien.numOffScreen = aliensThisWave
                else:
                    aliensThisWave *= 2
                    aliensLeftThisWave = Alien.numOffScreen = aliensThisWave
                if wave == 1:
                    Alien.pool.add([Fasty() for _ in range(5)])
                    Alien.pool.add([F() for _ in range(5)])#새로운 외계인 F 1페이즈 출현
                if wave == 2:
                    Alien.pool.add([Roundy() for _ in range(5)])
                    Alien.pool.add([Oak() for _ in range(5)])#오크 2페이즈 출현
                if wave == 3:
                    Alien.pool.add([Crawly() for _ in range(5)])
                wave += 1
                betweenWaveCount = betweenWaveTime

        textOverlays = zip(text, textposition)

    # Update and draw all sprites and text
        screen.blit(
            background, (0, 0), area=pygame.Rect(
                0, backgroundLoc, 500, 500))
        backgroundLoc -= speed
        if backgroundLoc - speed <= speed:
            backgroundLoc = 1500
        allsprites.update()
        allsprites.draw(screen)
        alldrawings.update()
        for txt, pos in textOverlays:
            screen.blit(txt, pos)
        pygame.display.flip()

    accuracy = round(score / missilesFired, 4) if missilesFired > 0 else 0.0
    isHiScore = len(hiScores) < Database.numScores or score > hiScores[-1][1]
    name = ''
    nameBuffer = []

    while True:
        clock.tick(clockTime)

    # Event Handling
        for event in pygame.event.get():
            if (event.type == pygame.QUIT
                or not isHiScore
                and event.type == pygame.KEYDOWN
                    and event.key == pygame.K_ESCAPE):
                return False
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_RETURN
                  and not isHiScore):
                return True
            elif (event.type == pygame.KEYDOWN
                  and event.key in Keyboard.keys.keys()
                  and len(nameBuffer) < 8):
                nameBuffer.append(Keyboard.keys[event.key])
                name = ''.join(nameBuffer)
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_BACKSPACE
                  and len(nameBuffer) > 0):
                nameBuffer.pop()
                name = ''.join(nameBuffer)
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_RETURN
                  and len(name) > 0):
                Database.setScore(hiScores, (name, score, accuracy))
                return True

        if isHiScore:
            hiScoreText = font.render('HIGH SCORE!', 1, RED)
            hiScorePos = hiScoreText.get_rect(
                midbottom=screen.get_rect().center)
            scoreText = font.render(str(score), 1, BLUE)
            scorePos = scoreText.get_rect(midtop=hiScorePos.midbottom)
            enterNameText = font.render('ENTER YOUR NAME:', 1, RED)
            enterNamePos = enterNameText.get_rect(midtop=scorePos.midbottom)
            nameText = font.render(name, 1, BLUE)
            namePos = nameText.get_rect(midtop=enterNamePos.midbottom)
            textOverlay = zip([hiScoreText, scoreText,
                               enterNameText, nameText],
                              [hiScorePos, scorePos,
                               enterNamePos, namePos])
        else:
            gameOverText = font.render('GAME OVER', 1, BLUE)
            gameOverPos = gameOverText.get_rect(
                center=screen.get_rect().center)
            scoreText = font.render('SCORE: {}'.format(score), 1, BLUE)
            scorePos = scoreText.get_rect(midtop=gameOverPos.midbottom)
            textOverlay = zip([gameOverText, scoreText],
                              [gameOverPos, scorePos])

    # Update and draw all sprites
        screen.blit(
            background, (0, 0), area=pygame.Rect(
                0, backgroundLoc, 500, 500))
        backgroundLoc -= speed
        if backgroundLoc - speed <= 0:
            backgroundLoc = 1500
        allsprites.update()
        allsprites.draw(screen)
        alldrawings.update()
        for txt, pos in textOverlay:
            screen.blit(txt, pos)
        pygame.display.flip()
コード例 #3
0
def game():
    EXPLODING = 2
    RUNNING   = 1
    QUIT      = 0
    
    state = RUNNING
    side  = STILL

    assets = load_assets()

    all_sprites   = pygame.sprite.Group()
    all_enemies   = pygame.sprite.Group()
    all_bullets   = pygame.sprite.Group()
    all_platforms = pygame.sprite.Group()

    groups = {}

    groups['all_sprites']   = all_sprites
    groups['all_meteors']   = all_enemies
    groups['all_bullets']   = all_bullets
    groups['all_platforms'] = all_platforms

    camera    = Camera(assets)
    player    = Hero(groups, assets, side)
    enemy     = Enemy(assets)
    platform1 = Platform(assets, 700, 650)
    
    all_sprites.add(camera)
    all_sprites.add(player)
    all_sprites.add(platform1)

    score             = 0
    lives             = 15
    number_of_enemies = 2
    keys_down         = {}

    for i in range(number_of_enemies):
        enemy = Enemy(assets)
        all_sprites.add(enemy)
        all_enemies.add(enemy)
    
    while state != QUIT:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                state = QUIT

            if event.type == pygame.KEYDOWN:
                keys_down[event.key] = True
                
                if event.key == pygame.K_ESCAPE:
                    pause()

                if event.key == pygame.K_UP or event.key == pygame.K_w:
                    player.jump()

                if event.key == pygame.K_LEFT or event.key == pygame.K_a:
                    camera.speedx    += 2
                    enemy.speedx     += 2
                    if camera.rect.left <= 0 or camera.rect.right >= window_width:
                        platform1.speedx += 2
                    else:
                        platform1.speed = 0
                    player.side = Bullet.side = LEFT

                if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                    camera.speedx    -= 2
                    enemy.speedx     -= 2
                    if camera.rect.left <= 0 or camera.rect.right >= window_width:
                        platform1.speedx -= 2
                    else:
                        platform1.speed = 0
                    player.side = Bullet.side = RIGHT
                    
                if event.key == pygame.K_SPACE:
                    player.shoot()

            if event.type == pygame.KEYUP:
                if event.key in keys_down and keys_down[event.key]:
                    if event.key == pygame.K_LEFT or event.key == pygame.K_a:
                        camera.speedx    -= 2
                        enemy.speedx     -= 2
                        if camera.rect.left <= 0 or camera.rect.right >= window_width:
                            platform1.speedx -= 2
                        else:
                            platform1.speed = 0
                        player.side = Bullet.side = LEFT

                    if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                        camera.speedx    += 2
                        enemy.speedx     += 2
                        if camera.rect.left <= 0 or camera.rect.right >= window_width:
                            platform1.speedx += 2
                        else:
                            platform1.speed = 0
                        player.side = Bullet.side = RIGHT

        all_sprites.update()

        if state == RUNNING:
            hits = pygame.sprite.groupcollide(all_enemies, all_bullets, True, True, pygame.sprite.collide_mask)
            for enemy in hits:
                assets['destroy_sound'].play()
                e = Enemy(assets)
                all_sprites.add(e)
                all_enemies.add(e)

                explosion = Explosion(enemy.rect.center, assets)
                all_sprites.add(explosion)

                score += 100
                if score % 1000 == 0:
                    lives += 1

            hits = pygame.sprite.spritecollide(player, all_enemies, True, pygame.sprite.collide_mask)
            if len(hits) > 0:
                assets['boom_sound'].play()
                player.kill()
                lives    -= 1
                explosion = Explosion(player.rect.center, assets)
                all_sprites.add(explosion)
                state     = EXPLODING
                keys_down = {}
                explosion_tick     = pygame.time.get_ticks()
                explosion_duration = explosion.frame_ticks * len(explosion.explosion_anim) + 50

            hits = pygame.sprite.spritecollide(player, all_platforms, False, pygame.sprite.collide_mask)
            if hits:
                player.speedy = 0
                player.rect.pos.y = hits[0].rect.top
                keys_down = {}

        elif state == EXPLODING:
            now           = pygame.time.get_ticks()
            camera.speedx = 0
            platform1.speedx = 0
            keys_down     = {}
            if now - explosion_tick > explosion_duration:
                if lives == 0:
                    game_over()
                else:
                    state  = RUNNING
                    player = Hero(groups, assets, side)
                    enemy  = Enemy(assets)
                    all_sprites.add(player)
                    all_sprites.add(enemy)
                    all_enemies.add(enemy)

        all_sprites.draw(window)

        text_surface     = assets['score_font'].render('{:08d}'.format(score), True, WHITE)
        text_rect        = text_surface.get_rect()
        text_rect.midtop = (window_width / 2, 10)
        window.blit(text_surface, text_rect)

        text_surface      = assets['score_font'].render(chr(9829) * lives, True, INSPER_RED)
        text_rect         = text_surface.get_rect()
        text_rect.topleft = (10, 10)
        window.blit(text_surface, text_rect)

        pygame.display.update()
        clock.tick(FPS)

    pygame.quit()
    pygame.mixer.quit()
コード例 #4
0
def main():

    #mindwaveDataPointReader = MindwaveDataPointReader()
    #mindwaveDataPointReader.start()
    #if not (mindwaveDataPointReader.isConnected()):
    #print((textwrap.dedent("""\
    #Exiting because the program could not connect
    #to the Mindwave Mobile device.""").replace("\n", " ")))
    #sys.exit()

    # Initialize everything
    pygame.mixer.pre_init(11025, -16, 2, 512)
    pygame.init()
    screen = pygame.display.set_mode((500, 500))
    pygame.display.set_caption('Shooting Game')
    pygame.mouse.set_visible(0)

    # Create the background which will scroll and loop over a set of different
    # size stars
    background = pygame.Surface((500, 2000))
    background = background.convert()
    background.fill((0, 0, 0))
    backgroundLoc = 1500
    finalStars = deque()
    for y in range(0, 1500, 30):
        size = random.randint(2, 5)
        x = random.randint(0, 500 - size)
        if y <= 500:
            finalStars.appendleft((x, y + 1500, size))
        pygame.draw.rect(background, (255, 255, 0),
                         pygame.Rect(x, y, size, size))
    while finalStars:
        x, y, size = finalStars.pop()
        pygame.draw.rect(background, (255, 255, 0),
                         pygame.Rect(x, y, size, size))


# Display the background
    screen.blit(background, (0, 0))
    pygame.display.flip()

    # Prepare game objects
    speed = 1.5
    MasterSprite.speed = speed
    alienPeriod = 60 / speed
    clockTime = 60  # maximum FPS
    clock = pygame.time.Clock()
    ship = Ship()
    initialAlienTypes = (Siney, Spikey)
    powerupTypes = (BombPowerup, ShieldPowerup)

    # Sprite groups
    alldrawings = pygame.sprite.Group()
    allsprites = pygame.sprite.RenderPlain((ship, ))
    MasterSprite.allsprites = allsprites
    Alien.pool = pygame.sprite.Group(
        [alien() for alien in initialAlienTypes for _ in range(5)])
    Alien.active = pygame.sprite.Group()
    Missile.pool = pygame.sprite.Group([Missile() for _ in range(10)])
    Missile.active = pygame.sprite.Group()
    Explosion.pool = pygame.sprite.Group([Explosion() for _ in range(10)])
    Explosion.active = pygame.sprite.Group()
    bombs = pygame.sprite.Group()
    powerups = pygame.sprite.Group()

    # Sounds
    missile_sound = load_sound('missile.ogg')
    bomb_sound = load_sound('bomb.ogg')
    alien_explode_sound = load_sound('alien_explode.ogg')
    ship_explode_sound = load_sound('ship_explode.ogg')
    load_music('music_loop.ogg')

    alienPeriod = clockTime // 2
    curTime = 0
    aliensThisWave, aliensLeftThisWave, Alien.numOffScreen = 10, 10, 10
    wave = 1
    bombsHeld = 3
    score = 0
    missilesFired = 0
    powerupTime = 10 * clockTime
    powerupTimeLeft = powerupTime
    betweenWaveTime = 3 * clockTime
    betweenWaveCount = betweenWaveTime
    font = pygame.font.Font(None, 36)

    inMenu = True
    hiScores = Database.getScores()
    highScoreTexts = [
        font.render("NAME", 1, RED),
        font.render("SCORE", 1, RED),
        font.render("ACCURACY", 1, RED)
    ]
    highScorePos = [
        highScoreTexts[0].get_rect(
            topleft=screen.get_rect().inflate(-100, -100).topleft),
        highScoreTexts[1].get_rect(
            midtop=screen.get_rect().inflate(-100, -100).midtop),
        highScoreTexts[2].get_rect(
            topright=screen.get_rect().inflate(-100, -100).topright)
    ]
    for hs in hiScores:
        highScoreTexts.extend(
            [font.render(str(hs[x]), 1, BLUE) for x in range(3)])
        highScorePos.extend([
            highScoreTexts[x].get_rect(topleft=highScorePos[x].bottomleft)
            for x in range(-3, 0)
        ])

    title, titleRect = load_image('title.png')
    titleRect.midtop = screen.get_rect().inflate(0, -200).midtop

    startText = font.render('START GAME', 1, BLUE)
    startPos = startText.get_rect(midtop=titleRect.inflate(0, 100).midbottom)
    hiScoreText = font.render('HIGH SCORES', 1, BLUE)
    hiScorePos = hiScoreText.get_rect(topleft=startPos.bottomleft)
    fxText = font.render('SOUND FX ', 1, BLUE)
    fxPos = fxText.get_rect(topleft=hiScorePos.bottomleft)
    fxOnText = font.render('ON', 1, RED)
    fxOffText = font.render('OFF', 1, RED)
    fxOnPos = fxOnText.get_rect(topleft=fxPos.topright)
    fxOffPos = fxOffText.get_rect(topleft=fxPos.topright)
    musicText = font.render('MUSIC', 1, BLUE)
    musicPos = fxText.get_rect(topleft=fxPos.bottomleft)
    musicOnText = font.render('ON', 1, RED)
    musicOffText = font.render('OFF', 1, RED)
    musicOnPos = musicOnText.get_rect(topleft=musicPos.topright)
    musicOffPos = musicOffText.get_rect(topleft=musicPos.topright)
    quitText = font.render('QUIT', 1, BLUE)
    quitPos = quitText.get_rect(topleft=musicPos.bottomleft)
    selectText = font.render('*', 1, BLUE)
    selectPos = selectText.get_rect(topright=startPos.topleft)
    menuDict = {1: startPos, 2: hiScorePos, 3: fxPos, 4: musicPos, 5: quitPos}
    selection = 1
    showHiScores = False
    soundFX = Database.getSound()
    music = Database.getSound(music=True)
    if music and pygame.mixer:
        pygame.mixer.music.play(loops=-1)

    while inMenu:
        clock.tick(clockTime)

        screen.blit(background, (0, 0),
                    area=pygame.Rect(0, backgroundLoc, 500, 500))
        backgroundLoc -= speed
        if backgroundLoc - speed <= speed:
            backgroundLoc = 1500

        for event in pygame.event.get():
            if (event.type == pygame.QUIT):
                return
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_RETURN):
                if showHiScores:
                    showHiScores = False
                elif selection == 1:
                    inMenu = False
                    ship.initializeKeys()
                elif selection == 2:
                    showHiScores = True
                elif selection == 3:
                    soundFX = not soundFX
                    if soundFX:
                        missile_sound.play()
                    Database.setSound(int(soundFX))
                elif selection == 4 and pygame.mixer:
                    music = not music
                    if music:
                        pygame.mixer.music.play(loops=-1)
                    else:
                        pygame.mixer.music.stop()
                    Database.setSound(int(music), music=True)
                elif selection == 5:
                    return
            elif (event.type == pygame.KEYDOWN and event.key == pygame.K_w
                  and selection > 1 and not showHiScores):
                selection -= 1
            elif (event.type == pygame.KEYDOWN and event.key == pygame.K_s
                  and selection < len(menuDict) and not showHiScores):
                selection += 1

        selectPos = selectText.get_rect(topright=menuDict[selection].topleft)

        if showHiScores:
            textOverlays = zip(highScoreTexts, highScorePos)
        else:
            textOverlays = zip([
                startText, hiScoreText, fxText, musicText, quitText,
                selectText, fxOnText if soundFX else fxOffText,
                musicOnText if music else musicOffText
            ], [
                startPos, hiScorePos, fxPos, musicPos, quitPos, selectPos,
                fxOnPos if soundFX else fxOffPos,
                musicOnPos if music else musicOffPos
            ])
            screen.blit(title, titleRect)
        for txt, pos in textOverlays:
            screen.blit(txt, pos)
        pygame.display.flip()

    medVal = 0
    attVal = 0
    while medVal == 0 and attVal == 0:
        dataPoint = mindwaveDataPointReader.readNextDataPoint()
        if (not dataPoint.__class__ is RawDataPoint):
            if dataPoint.__class__.__name__ == 'MeditationDataPoint':
                medVal = dataPoint.meditationValue
                print("Meditaion Value: ", medVal)
            elif dataPoint.__class__.__name__ == 'AttentionDataPoint':
                attVal = dataPoint.attentionValue
                print("Attention Value: ", attVal)

    while ship.alive:
        clock.tick(clockTime)

        dataPoint = mindwaveDataPointReader.readNextDataPoint()
        if (not dataPoint.__class__ is RawDataPoint):
            if dataPoint.__class__.__name__ == 'MeditationDataPoint':
                medVal = dataPoint.meditationValue
                print("Meditaion Value: ", medVal)
            elif dataPoint.__class__.__name__ == 'AttentionDataPoint':
                attVal = dataPoint.attentionValue
                print("Attention Value: ", attVal)

        if aliensLeftThisWave >= 20:
            powerupTimeLeft -= 1
        if powerupTimeLeft <= 0:
            powerupTimeLeft = powerupTime
            random.choice(powerupTypes)().add(powerups, allsprites)

    # Event Handling
        for event in pygame.event.get():
            if (event.type == pygame.QUIT or event.type == pygame.KEYDOWN
                    and event.key == pygame.K_ESCAPE):
                return
            elif (event.type == pygame.KEYDOWN
                  and event.key in direction.keys()):
                ship.horiz += direction[event.key][0] * speed  #*medVal
                ship.vert += direction[event.key][1] * speed  #*medVal
            elif (event.type == pygame.KEYUP
                  and event.key in direction.keys()):
                ship.horiz -= direction[event.key][0] * speed  #*medVal
                ship.vert -= direction[event.key][1] * speed  #*medVal
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_SPACE):
                Missile.position(ship.rect.midtop)
                missilesFired += 1
                if soundFX:
                    missile_sound.play()
            elif (event.type == pygame.KEYDOWN and event.key == pygame.K_b):
                if bombsHeld > 0:
                    bombsHeld -= 1
                    newBomb = ship.bomb()
                    newBomb.add(bombs, alldrawings)
                    if soundFX:
                        bomb_sound.play()

    # Collision Detection
    # Aliens
        for alien in Alien.active:
            for bomb in bombs:
                if pygame.sprite.collide_circle(
                        bomb, alien) and alien in Alien.active:
                    alien.table()
                    Explosion.position(alien.rect.center)
                    missilesFired += 1
                    aliensLeftThisWave -= 1
                    score += 1
                    if soundFX:
                        alien_explode_sound.play()
            for missile in Missile.active:
                if pygame.sprite.collide_rect(missile,
                                              alien) and alien in Alien.active:
                    alien.table()

                    #Peiercing bullets
                    if medVal < 40:
                        missile.table()
                    Explosion.position(alien.rect.center)
                    aliensLeftThisWave -= 1
                    score += 1
                    if soundFX:
                        alien_explode_sound.play()
            if pygame.sprite.collide_rect(alien, ship):
                if ship.shieldUp:
                    alien.table()
                    Explosion.position(alien.rect.center)
                    aliensLeftThisWave -= 1
                    score += 1
                    missilesFired += 1
                    ship.shieldUp = False
                else:
                    ship.alive = False
                    ship.remove(allsprites)
                    Explosion.position(ship.rect.center)
                    if soundFX:
                        ship_explode_sound.play()

        # PowerUps
        for powerup in powerups:
            if pygame.sprite.collide_circle(powerup, ship):
                if powerup.pType == 'bomb':
                    bombsHeld += 1
                elif powerup.pType == 'shield':
                    ship.shieldUp = True
                powerup.kill()
            elif powerup.rect.top > powerup.area.bottom:
                powerup.kill()

    # Update Aliens
        if curTime <= 0 and aliensLeftThisWave > 0:
            Alien.position()
            curTime = alienPeriod
        elif curTime > 0:
            curTime -= 1

    # Update text overlays
        waveText = font.render("Wave: " + str(wave), 1, BLUE)
        leftText = font.render("Aliens Left: " + str(aliensLeftThisWave), 1,
                               BLUE)
        scoreText = font.render("Score: " + str(score), 1, BLUE)

        dataText = font.render("(A): " + str(attVal) + " (M): " + str(medVal),
                               1, RED)
        bombText = font.render("Bombs: " + str(bombsHeld), 1, BLUE)

        wavePos = waveText.get_rect(topleft=screen.get_rect().topleft)
        leftPos = leftText.get_rect(midtop=screen.get_rect().midtop)
        scorePos = scoreText.get_rect(topright=screen.get_rect().topright)
        bombPos = bombText.get_rect(bottomleft=screen.get_rect().bottomleft)
        dataPos = dataText.get_rect(bottomright=screen.get_rect().bottomright)

        text = [waveText, leftText, scoreText, bombText, dataText]
        textposition = [wavePos, leftPos, scorePos, bombPos, dataPos]

        # Detertmine when to move to next wave
        if aliensLeftThisWave <= 0:
            if betweenWaveCount > 0:
                betweenWaveCount -= 1
                nextWaveText = font.render('Wave ' + str(wave + 1) + ' in', 1,
                                           BLUE)
                nextWaveNum = font.render(
                    str((betweenWaveCount // clockTime) + 1), 1, BLUE)
                text.extend([nextWaveText, nextWaveNum])
                nextWavePos = nextWaveText.get_rect(
                    center=screen.get_rect().center)
                nextWaveNumPos = nextWaveNum.get_rect(
                    midtop=nextWavePos.midbottom)
                textposition.extend([nextWavePos, nextWaveNumPos])
                if wave % 4 == 0:
                    speedUpText = font.render('SPEED UP!', 1, RED)
                    speedUpPos = speedUpText.get_rect(
                        midtop=nextWaveNumPos.midbottom)
                    text.append(speedUpText)
                    textposition.append(speedUpPos)
            elif betweenWaveCount == 0:
                if wave % 4 == 0:
                    speed += 0.5
                    MasterSprite.speed = speed
                    ship.initializeKeys()
                    aliensThisWave = 10
                    aliensLeftThisWave = Alien.numOffScreen = aliensThisWave
                else:
                    aliensThisWave *= 2
                    aliensLeftThisWave = Alien.numOffScreen = aliensThisWave
                if wave == 1:
                    Alien.pool.add([Fasty() for _ in range(5)])
                if wave == 2:
                    Alien.pool.add([Roundy() for _ in range(5)])
                if wave == 3:
                    Alien.pool.add([Crawly() for _ in range(5)])
                wave += 1
                betweenWaveCount = betweenWaveTime

        textOverlays = zip(text, textposition)

        # Update and draw all sprites and text
        screen.blit(background, (0, 0),
                    area=pygame.Rect(0, backgroundLoc, 500, 500))
        backgroundLoc -= speed
        if backgroundLoc - speed <= speed:
            backgroundLoc = 1500
        allsprites.update()
        allsprites.draw(screen)
        alldrawings.update()
        for txt, pos in textOverlays:
            screen.blit(txt, pos)
        pygame.display.flip()

    accuracy = round(score / missilesFired, 4) if missilesFired > 0 else 0.0
    isHiScore = len(hiScores) < Database.numScores or score > hiScores[-1][1]
    name = ''
    nameBuffer = []

    while True:
        clock.tick(clockTime)

        # Event Handling
        for event in pygame.event.get():
            if (event.type == pygame.QUIT
                    or not isHiScore and event.type == pygame.KEYDOWN
                    and event.key == pygame.K_ESCAPE):
                return False
            elif (event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN
                  and not isHiScore):
                return True
            elif (event.type == pygame.KEYDOWN
                  and event.key in Keyboard.keys.keys()
                  and len(nameBuffer) < 8):
                nameBuffer.append(Keyboard.keys[event.key])
                name = ''.join(nameBuffer)
            elif (event.type == pygame.KEYDOWN
                  and event.key == pygame.K_BACKSPACE and len(nameBuffer) > 0):
                nameBuffer.pop()
                name = ''.join(nameBuffer)
            elif (event.type == pygame.KEYDOWN and event.key == pygame.K_RETURN
                  and len(name) > 0):
                Database.setScore(hiScores, (name, score, accuracy))
                return True

        if isHiScore:
            hiScoreText = font.render('HIGH SCORE!', 1, RED)
            hiScorePos = hiScoreText.get_rect(
                midbottom=screen.get_rect().center)
            scoreText = font.render(str(score), 1, BLUE)
            scorePos = scoreText.get_rect(midtop=hiScorePos.midbottom)
            enterNameText = font.render('ENTER YOUR NAME:', 1, RED)
            enterNamePos = enterNameText.get_rect(midtop=scorePos.midbottom)
            nameText = font.render(name, 1, BLUE)
            namePos = nameText.get_rect(midtop=enterNamePos.midbottom)
            textOverlay = zip(
                [hiScoreText, scoreText, enterNameText, nameText],
                [hiScorePos, scorePos, enterNamePos, namePos])
        else:
            gameOverText = font.render('GAME OVER', 1, BLUE)
            gameOverPos = gameOverText.get_rect(
                center=screen.get_rect().center)
            scoreText = font.render('SCORE: {}'.format(score), 1, BLUE)
            scorePos = scoreText.get_rect(midtop=gameOverPos.midbottom)
            textOverlay = zip([gameOverText, scoreText],
                              [gameOverPos, scorePos])

    # Update and draw all sprites
        screen.blit(background, (0, 0),
                    area=pygame.Rect(0, backgroundLoc, 500, 500))
        backgroundLoc -= speed
        if backgroundLoc - speed <= 0:
            backgroundLoc = 1500
        allsprites.update()
        allsprites.draw(screen)
        alldrawings.update()
        for txt, pos in textOverlay:
            screen.blit(txt, pos)
        pygame.display.flip()
コード例 #5
0
                if missile:
                    sprites.append(missile)
    # update screen according to changes
    screen.fill(BLACK)
    sprites = [sprite.update(user, sprites=sprites)
               for sprite in sprites]  # apply update() to all sprites
    if not ship.display:
        ship = Ship(screen)
        sprites.append(ship)
        solid_sprites.append(ship)

    updated_solids = []
    # remove dead solids from their list and explode them
    for sprite in solid_sprites:
        if sprite.dead:
            if isinstance(sprite, Enemy):
                particles = Explosion(screen,
                                      Sprite._get_center(
                                          sprite.coordinates)).explode()
                enemies = Spawner(screen, 1).spawn()
                sprites = [*sprites, *particles]
                sprites = [*sprites, *enemies]
                updated_solids = [*updated_solids, *enemies]
        else:
            updated_solids.append(sprite)
    solid_sprites = updated_solids
    # remove non displayable sprites from update list
    sprites = [sprite for sprite in sprites if sprite.display]
    sleep_fps(t0)  # control FPS
    pygame.display.update()
コード例 #6
0
def game_screen(window):
    clock = pygame.time.Clock()

    assets = load_assets()

    # Criando um grupo de inimigos
    all_sprites = pygame.sprite.Group()
    all_enemies = pygame.sprite.Group()
    all_bullets = pygame.sprite.Group()
    groups = {}
    groups['all_sprites'] = all_sprites
    groups['all_enemies'] = all_enemies
    groups['all_bullets'] = all_bullets

    # Criando o jogador
    player = Hero(groups, assets)
    all_sprites.add(player)

    # Status
    DONE = 0
    PLAYING = 1
    EXPLODING = 2
    status = PLAYING

    keys_down = {}
    score = 0
    lives = 5

    # Criando os inimigos
    for j in range(4):
        enemy = Enemy(assets)
        all_sprites.add(enemy)
        all_enemies.add(enemy)

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

        # ----- Trata eventos
        for event in pygame.event.get():
            # ----- Verifica consequências
            if event.type == pygame.QUIT:
                status = DONE
            # Verifica teclado modo de jogo
            if status == PLAYING:
                # Verifica se apertou alguma tecla
                if event.type == pygame.KEYDOWN:

                    keys_down[event.key] = True
                    if event.key == pygame.K_LEFT:
                        player.speedx -= 10

                    if event.key == pygame.K_RIGHT:
                        player.speedx += 10

                    if event.key == pygame.K_SPACE:
                        player.shoot()

                    if event.key == pygame.K_UP:
                        player.jump()

                # Verifica se soltou alguma tecla
                if event.type == pygame.KEYUP:
                    if event.key in keys_down and keys_down[event.key]:
                        if event.key == pygame.K_LEFT:
                            player.speedx += 10
                        if event.key == pygame.K_RIGHT:
                            player.speedx -= 10

        # ----- Atualiza o estado do jogo
        all_sprites.update()

        if status == PLAYING:

            hits = pygame.sprite.groupcollide(all_enemies, all_bullets, True,
                                              True)
            for hit in hits:
                # Inimigo morto precisa de recriação
                assets[BOOM_SOUND].play()
                assets[ENEMY_DEATH_SOUND].play()
                m = Enemy(assets)
                all_sprites.add(m)
                all_enemies.add(m)

                # No lugar do inimigo antigo, adicionar uma explosão
                explosao = Explosion(hit.rect.center, assets)
                all_sprites.add(explosao)

                # Pontos recebidos pela eliminação do inimigo
                score += 100
                if score % 1000 == 0:
                    lives += 1

            hits = pygame.sprite.spritecollide(player, all_enemies, True)
            if len(hits) > 0:
                # Som da colisão
                assets[HERO_DAMAGE_SOUND].play()
                assets[ENEMY_DEATH_SOUND].play()
                player.kill()
                lives -= 1
                explosao = Explosion(player.rect.center, assets)
                all_sprites.add(explosao)
                status = EXPLODING
                keys_down = {}
                explosion_tick = pygame.time.get_ticks()
                explosion_duration = explosao.frame_ticks * len(
                    explosao.explosion_anim)

        elif status == EXPLODING:
            now = pygame.time.get_ticks()
            if now - explosion_tick > explosion_duration:
                if lives == 0:
                    assets[GAME_OVER_SOUND].play()
                    time.sleep(5)
                    status = DONE
                else:
                    status = PLAYING
                    player = Hero(groups, assets)
                    all_sprites.add(player)
                    enemy = Enemy(assets)
                    all_sprites.add(enemy)
                    all_enemies.add(enemy)

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

        # Desenhando o score
        text_surface = assets['score_font'].render('{:08d}'.format(score),
                                                   True, (255, 255, 0))
        text_rect = text_surface.get_rect()
        text_rect.midtop = (WIDTH / 2, 10)
        window.blit(text_surface, text_rect)

        # Desenhando as vidas
        text_surface = assets['score_font'].render(
            chr(9829) * lives, True, (255, 0, 0))
        text_rect = text_surface.get_rect()
        text_rect.bottomleft = (10, HEIGHT - 10)
        window.blit(text_surface, text_rect)

        pygame.display.update()  # Mostra um novo frame
コード例 #7
0
def main():
    pygame.init()

    pygame.display.set_caption('pyAlien')

    display_rect = Rect(0, 0, 640, 480)
    display = pygame.display.set_mode(display_rect.size)

    asset_loader = AssetLoader()

    background = build_background(asset_loader, display_rect)
    display.blit(background, (0, 0))

    # Initialize sprite groups
    aliens = pygame.sprite.Group()
    all = pygame.sprite.RenderUpdates()
    bombs = pygame.sprite.Group()
    bullets = pygame.sprite.Group()
    last_alien = pygame.sprite.GroupSingle()

    # Initialize sprite classes
    Alien.init(asset_loader, [all, aliens, last_alien])
    Bomb.init(asset_loader, [all, bombs])
    Bullet.init(asset_loader, [all, bullets])
    Explosion.init(asset_loader, [all])
    Player.init(asset_loader, [all])

    start_music(asset_loader)

    player = Player(display_rect.midbottom)

    clock = pygame.time.Clock()
    frame = 0

    while player.alive():
        frame += 1
        key_state = pygame.key.get_pressed()

        fps_multiplier = 2 if key_state[K_BACKQUOTE] and key_state[
            K_LCTRL] else 1
        clock.tick(fps_multiplier * fps)

        for event in pygame.event.get():
            if event.type == QUIT:
                return
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    return
                elif event.key == K_SPACE:
                    if key_state[K_LCTRL]:
                        [alien.explode() for alien in aliens]
                    elif len(bullets) < Player.max_shots:
                        player.shoot()

        # Clear game object images before next frame
        all.clear(display, background)

        # Handle player movement
        move = key_state[K_RIGHT] - key_state[K_LEFT]
        player.move(move, display_rect)

        # Update game objects
        all.update(display_rect)

        # Check for collisions between aliens and bullets
        for bullet in pygame.sprite.groupcollide(bullets, aliens, False, True):
            bullet.explode()

        # Check for collisions between player and bombs
        for bomb in pygame.sprite.spritecollide(player, bombs, False):
            bomb.explode()
            player.explode()

        # Check for collisions between player and aliens
        for alien in pygame.sprite.spritecollide(player, aliens, False):
            alien.explode()
            player.explode()

        # Last alien to potentially drop bomb
        if chance(Alien.bomb_percentage_chance) and last_alien.sprite:
            last_alien.sprite.shoot()

        # Potentially spawn new alien
        repeat(frame, Alien.frames_between_spawn,
               lambda: Alien.spawn_with_chance(display_rect))

        # Increase game difficulty over time
        repeat(frame, frames_between_difficulty_increase, increase_difficulty)

        # Draw updated game objects
        all_rects = all.draw(display)

        # Render new display
        pygame.display.update(all_rects)