Exemple #1
0
def main():
    '''This function defines the 'mainline logic' for our pyPong game.'''
    # DISPLAY
    pygame.display.set_caption("Thunder")
    screen = pygame.display.set_mode((480, 800))
    
    # ENTITIES
    # Background initialization
    background = pygame.image.load('resources/image/background.png').convert()
    screen.blit(background, (0, 0))
    #Images loading
    game_over = pygame.image.load('resources/image/gameover.png').convert()
    plane_img =pygame.image.load('resources/image/shoot.png')    
    # Config rect for bullets
    bullet_rect = pygame.Rect(1004, 987, 9, 21)
    bullet_img = plane_img.subsurface(bullet_rect)
    # Player Config
    player_rect = []
    # Player Sprite area
    player_rect.append(pygame.Rect(0, 99, 102, 126))  
    player_rect.append(pygame.Rect(165, 360, 102, 126))
    # Player explosion sprite area
    player_rect.append(pygame.Rect(165, 234, 102, 126))
    player_rect.append(pygame.Rect(330, 624, 102, 126))
    player_rect.append(pygame.Rect(330, 498, 102, 126))
    player_rect.append(pygame.Rect(432, 624, 102, 126))
    player_pos = [200, 600]
    # Sprite for player plane
    player = pySprites.Player(plane_img, player_rect, player_pos,screen)    
    # Config Rect for enemy plane
    enemy1_rect = pygame.Rect(534, 612, 57, 43)
    # Sprite for enemy plane
    enemies1 = pygame.sprite.Group()
    shield_pos = [random.randint(0, background.get_width() - enemy1_rect.width), 0]
    shield = pySprites.Shield(shield_pos)
    # Save down plane for explosion
    enemies_down = pygame.sprite.Group()
    #bullets sprites
    bullets = pygame.sprite.Group()
    # Sprite for score keeper
    score_keeper = pySprites.ScoreKeeper(screen)
    allSprites = pygame.sprite.OrderedUpdates(enemies1,enemies_down,shield,score_keeper,bullets,player)
    
    #initialize setting
    shoot_frequency = 25
    enemy_frequency = 50
    #keep track of frame and current score
    frame=0
    score = 0    
    
    # Background Music and Sound Effects
    bullet_sound = pygame.mixer.Sound('resources/sound/bullet.wav')
    enemy1_down_sound = pygame.mixer.Sound('resources/sound/enemy1_down.wav')
    game_over_sound = pygame.mixer.Sound('resources/sound/game_over.wav')
    bullet_sound.set_volume(0.3)
    enemy1_down_sound.set_volume(0.3)
    game_over_sound.set_volume(0.3)
    pygame.mixer.music.load('resources/sound/game_music.wav')
    pygame.mixer.music.play(-1, 0.0)
    pygame.mixer.music.set_volume(0.25)

    # ASSIGN 
    clock = pygame.time.Clock()
    keepGoing = True
 
    # Hide the mouse pointer
    pygame.mouse.set_visible(False)
 
    # LOOP
    while keepGoing:
     
        # TIME, 60 FPS for smoother play
        clock.tick(60)
     
        # EVENT HANDLING: Player uses keyboard, left arrow/A for left, right 
        #arrow/D for right, up/W for up, down/S for down

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                keepGoing = False
        if not player.is_hit:
            if pygame.key.get_pressed()[pygame.K_w] or pygame.key.get_pressed()[pygame.K_UP]:
                player.moveUp()
            if pygame.key.get_pressed()[pygame.K_s] or pygame.key.get_pressed()[pygame.K_DOWN]:
                player.moveDown()
            if pygame.key.get_pressed()[pygame.K_a] or pygame.key.get_pressed()[pygame.K_LEFT]:
                player.moveLeft()
            if pygame.key.get_pressed()[pygame.K_d] or pygame.key.get_pressed()[pygame.K_RIGHT]:
                player.moveRight()                    
        
        frame += 1
        score=score_keeper.get_score()            
        # Fire bullets 
        if frame % shoot_frequency == 0:
            bullet_sound.play()
            bullet = pySprites.Bullet(bullet_img,player.rect.midtop)
            bullets.add(bullet)            
        
        #if score if more than 10000 increase the speed
        #more than 20000 increase speed again and increase shoot frequency,
        #more than 30000 increase spped again and increase shoot frequency again
        if score >10000:
            enemy_frequency=40
            shoot_frequency=20
        if score >20000:
            enemy_frequency=25
            shoot_frequency=15
        if score >30000:
            enemy_frequency=20
            shoot_frequency=13 
        #generate shield   
        if frame % 1000 == 0:
            shield.reset()
        #generate enemy plane
        if frame % enemy_frequency == 0:
            enemy1_pos = [random.randint(0, background.get_width() - enemy1_rect.width), 0]
            enemy1 = pySprites.Enemy(enemy1_pos)
            enemies1.add(enemy1)
                    
        #detect if bullet is out of screen, if it is, remove the bullet
        for bullet in bullets:
            if bullet.rect.bottom < 0:
                bullets.remove(bullet)
        
        for enemy in enemies1:
            #detect if the player is hit or out of screen, if it is, deduct one life and removes the plane
            if pygame.sprite.collide_circle(enemy, player) or enemy.rect.top > background.get_height():
                enemies_down.add(enemy)
                enemies1.remove(enemy)
                score_keeper.deduct_life()
                player.is_hit=1
        if score_keeper.dead():
            player.is_hit=1
            pygame.mixer.music.fadeout(2000)
            if player.finish==1:
                keepGoing=False

        if shield.rect.colliderect(player):
            score_keeper.add_life() 
            shield.hit=1
        # detect if bullet hits the plane, if so then plus 1000 score and removes the plane
        enemies1_down = pygame.sprite.groupcollide(enemies1, bullets, 1, 1)
        for enemy_down in enemies1_down:
            enemies_down.add(enemy_down)
            score_keeper.player_scored(1000)            

        for enemy_down in enemies_down:
            if enemy_down.index == 0:
                enemy1_down_sound.play()
                enemy_down.enemy_down()
            if enemy_down.index >= len(enemy_down.images):
                enemies_down.remove(enemy_down)
                continue
        allSprites = pygame.sprite.OrderedUpdates(enemies1,enemies_down,shield,score_keeper,bullets,player)
        # REFRESH SCREEN
        screen.blit(background, (0, 0))
        allSprites.clear(screen,background)
        allSprites.update()
        allSprites.draw(screen)       
        pygame.display.flip()
    
    # Display "Game Over" graphic and unhide the mouse pointer
    game_over_sound.play()
    font = pygame.font.Font(None, 48)
    text = font.render('Score: '+ str(score_keeper.get_score()), True, (255, 0, 0))
    text_rect = text.get_rect()
    text_rect.centerx = screen.get_rect().centerx
    text_rect.centery = screen.get_rect().centery + 24
    screen.blit(game_over, (0, 0))
    screen.blit(text, text_rect)    
    pygame.display.flip()
    pygame.mouse.set_visible(True)
    time.sleep(5)
    pygame.quit()
Exemple #2
0
def main():
    '''This function defines the 'mainline logic' for our pyPong game.'''

    # D - DISPLAY
    screen = pygame.display.set_mode((640, 480))
    pygame.display.set_caption("pyPong! v1.0")

    # E - ENTITIES
    #background = pygame.Surface(screen.get_size())
    #background = background.convert()
    #background.fill((255, 255, 255))
    background = pygame.image.load("beach.jpg").convert()
    screen.blit(background, (0, 0))
    pygame.mixer.music.load("pirate.ogg")
    pygame.mixer.music.set_volume(0.6)
    pygame.mixer.music.play(-1)

    boing = pygame.mixer.Sound("shotgun.wav")
    boing.set_volume(0.8)

    canon = pygame.mixer.Sound("canon.wav")
    canon.set_volume(1.0)
    mySystemFont = pygame.font.SysFont("Arial", 60)
    label1 = mySystemFont.render("GAME OVER!", True, (255, 255, 0))
    # Initialize Joystick objects.
    joysticks = []
    for joystick_no in range(pygame.joystick.get_count()):
        stick = pygame.joystick.Joystick(joystick_no)
        stick.init()
        joysticks.append(stick)

    # Sprites for: ScoreKeeper label, End Zones, Ball, and Players
    scoreKeeper = pySprites.ScoreKeeper()
    ball = pySprites.Ball(screen)
    player1 = pySprites.Player(screen, 1)
    player1Endzone = pySprites.EndZone(screen, 0)
    player2 = pySprites.Player(screen, 2)
    player2Endzone = pySprites.EndZone(screen, 639)
    allSprites = pygame.sprite.OrderedUpdates(scoreKeeper, player1Endzone, \
                                     player2Endzone, ball, player1, player2)

    # A - ACTION
    # A - ASSIGN
    clock = pygame.time.Clock()
    keepGoing = True

    # Hide the mouse pointer
    pygame.mouse.set_visible(False)

    # L - LOOP
    while keepGoing:

        # TIME
        clock.tick(30)

        # E - EVENT HANDLING: Player 1 uses joystick, Player 2 uses arrow keys
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                keepGoing = False
            #elif event.type == pygame.JOYHATMOTION:
            #   player1.changeDirection(event.value)
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    player2.changeDirection((0, 1))
                if event.key == pygame.K_DOWN:
                    player2.changeDirection((0, -1))
                if event.key == pygame.K_w:
                    player1.changeDirection((0, 1))
                if event.key == pygame.K_s:
                    player1.changeDirection((0, -1))

        # Check if player 1 scores (i.e., ball hits player 2 endzone)
        if ball.rect.colliderect(player2Endzone):
            boing.play()
            scoreKeeper.player1Scored()
            ball.changeDirection()

        # Check if player 2 scores (i.e., ball hits player 1 endzone)
        if ball.rect.colliderect(player1Endzone):
            boing.play()
            scoreKeeper.player2Scored()
            ball.changeDirection()

        # Check for game over (if a player gets 3 points)
        if scoreKeeper.winner():
            screen.blit(label1, (30, 255))
            keepGoing = False

        # Check if ball hits Player 1 or 2
        # If so, change direction, and speed up the ball a little
        if ball.rect.colliderect(player1.rect) or\
            ball.rect.colliderect(player2.rect):
            canon.play()
            ball.changeDirection()

        # R - REFRESH SCREEN
        allSprites.clear(screen, background)
        allSprites.update()
        allSprites.draw(screen)
        pygame.display.flip()

    # Unhide the mouse pointer
    pygame.mouse.set_visible(True)

    # Close the game window
    pygame.time.delay(3000)
    pygame.quit()
Exemple #3
0
def game(screen):
    """
    This is the main game. it sets up all of the aliens and wall and player objects. 
    """
    # display 
    background = pygame.image.load("./background stuff/honeycomb wall2.jpg")
    background.convert()
    screen.blit(background, (0, 0))  

    # entities   
    points = 0 
    barriers = []
    invadersList = []
    image_num = [1,1,2,2,3]
    image_num2 = [1,1,1,2,2,3]
    image_num3 = [1,1,1,2,2,2,3]
    boss_active = False 
    level_2 = False
    level_3 = False

    # makes barriers
    barrier_y = 630
    for barrierNum in range(4):
        for barrierRow in range(7):
            for barrierCol in range(13):
                barriers.append(pySprites.Barrier((barrierNum *250) + (barrierCol * 10) + 100, barrier_y))
            barrier_y -= 10
        barrier_y = 630

    # makes the first wave of invaders 
    invader_y = 280
    for row in range(5):
        for column in range(11):
            image = image_num[row]
            invadersList.append(pySprites.Invader(((column + 1)*37), invader_y, screen.get_width()-(((9) - column)*37) , (column*37), (row+1)*10 , 5,7, image))
        invader_y -= 30
    
    player_shoot = pygame.mixer.Sound("./sounds/shoot.wav")
    player_shoot.set_volume(0.3)
    
    alien_shoot = pygame.mixer.Sound("./sounds/shoot2.wav")
    alien_shoot.set_volume(0.3)
    
    invader_death = pygame.mixer.Sound("./sounds/invaderkilled.wav")
    invader_death.set_volume(0.3)
    
    player_death = pygame.mixer.Sound("./sounds/playerkilled.wav")
    player_death.set_volume(0.3)
    
    player = pySprites.Player(screen)
    barriers = pygame.sprite.OrderedUpdates(barriers)
    bullets = pygame.sprite.OrderedUpdates()
    enemyBullets = pygame.sprite.OrderedUpdates()
    invaders = pygame.sprite.OrderedUpdates(invadersList)
    bullet = pySprites.Bullet(player.rect.centerx , player.rect.top + 9, -25, True)
    boss_health = pySprites.Boss_health()
    zone = pySprites.Zone(80)
    # test
    test_bullet = pygame.sprite.OrderedUpdates()
    
    life = pySprites.Life()
    score = pySprites.Score(points)
    allSprites = pygame.sprite.OrderedUpdates(zone, score, life, bullet, barriers, invaders, player)    
        
    # alter / assign
    keepGoing = True 
    clock = pygame.time.Clock()

    # loop
    while keepGoing:
        # time
        clock.tick(30)
        # events
        key = pygame.key.get_pressed()
        
        # checks for keys pressed
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return False, score.get_score(), life.get_life()
            
        if key[pygame.K_SPACE] and not bullet.get_control():
            bullet.set_control(True)
            bullet.reset(player.rect.centerx , player.rect.centery - 5)
            player_shoot.play()
            
        if key[pygame.K_LEFT]:
            player.go_left()
            if not bullet.get_control():
                bullet.go_left()
                
        if key[pygame.K_RIGHT]:
            player.go_right()
            if not bullet.get_control():
                bullet.go_right()
        
        if key[pygame.K_ESCAPE]:
            return False, score.get_score(), life.get_life()

        # test 
        if key[pygame.K_z]:
            test = pySprites.Bullet(player.rect.centerx, player.rect.centery, - 15 , True)
            test.set_control(True)
            test_bullet.add(test)
            allSprites.add(test_bullet)
                
        for op in invaders:
            if random.randrange(1500) == 9:
                bullet1 = pySprites.Bullet(op.rect.centerx, op.rect.centery, 15, False)
                bullet1.set_control(True)
                enemyBullets.add(bullet1)
                allSprites.add(enemyBullets)
                alien_shoot.play()
 
        # enemy bullet to player collition
        playerHit = pygame.sprite.spritecollide(player, enemyBullets, False)
        if playerHit:
            for x in playerHit:
                player_death.play()
                bullet.force_set((640, -10))
                bullet.set_control(True)
                player.set_value(True)
                x.kill()
            life.set_life()
            bullet.set_control(False)

        if life.get_life() <= 0 and not player.get_value():
            return True ,score.get_score(), life.get_life()        
    
        # player bullet to invader collition
        invaderHit = pygame.sprite.spritecollide(bullet, invaders, False)
        if invaderHit:
            for x in invaderHit:
                invader_death.play()
                bullet.reset(player.rect.centerx , player.rect.centery - 5)
                bullet.set_control(False)
                point = x.get_point()
                score.set_score(point)
                x.kill()
    
        #test
        for a in test_bullet:
            for b in invaders:
                if a.rect.colliderect(b.rect):
                    a.kill()
                    b.kill()
            
        # barrier to invader collition        
        for barrier in barriers:
            for invader in invaders:
                if barrier.rect.colliderect(invader.rect):
                    barrier.kill()
                
        # enemy bullet to barrier collition
        for enemybullet in enemyBullets:
            for barrier in barriers:
                if enemybullet.rect.colliderect(barrier.rect):
                    enemybullet.kill()
                    barrier.kill()
        
        # invader to player collition
        for invade in invaders:
            if player.rect.colliderect(invade.rect):
                life.instance_lose()
                return True, score.get_score(), life.get_life()
                    
        # player bullet to barrier collition
        for barrier in barriers:
            if bullet.rect.colliderect(barrier.rect):
                barrier.kill()
                bullet.reset(player.rect.centerx , player.rect.centery - 5)
                bullet.set_control(False)
            
        if bullet.rect.colliderect(zone.rect):
            bullet.set_control(False)
            bullet.reset(player.rect.centerx, player.rect.centery -5)
            
        # makes the second wave of invaders
        if len(invaders) == 0 and not boss_active and not level_2 and not level_3:
            invadersList = []
            y = 290
            for row in range(6):
                for column in range(13):
                    image = image_num2[row]
                    invadersList.append(pySprites.Invader(((column + 1)*37), y, screen.get_width()-(((11) - column)*37) , (column*37), (row+1)*10 , 6,8, image))
                y -= 30 
            invaders.add(invadersList)
            allSprites.add(invaders)
            level_2 = True
        
        # makes the thrid wave of invadeders
        if len(invaders) == 0 and not boss_active and level_2 and not level_3:
            invadersList = []
            y = 300
            for row in range(7):
                for column in range(15):
                    image = image_num3[row]
                    invadersList.append(pySprites.Invader(((column + 1)*37), y, screen.get_width()-(((13) - column)*37) , (column*37), (row+1)*10 , 7,9, image))
                y -= 30 
            invaders.add(invadersList)
            allSprites.add(invaders)
            level_3 = True        
        
        # makes the boss 
        if len(invaders) == 0 and not boss_active and level_2 and level_3:
            boss = pySprites.Invader(screen.get_width() /2, 180, screen.get_width(), 0, 500, 8,13, 10)
            allSprites.add(boss, boss_health)
            boss_active = True
            
        if boss_active and len(invaders) == 0:
            # makes the boss shoot 
            if random.randrange(30) == 9:
                bullet1 = pySprites.Bullet(boss.rect.centerx, boss.rect.centery, 15, False)
                bullet1.set_control(True)
                bullet2 = pySprites.Bullet(boss.rect.left, boss.rect.centery, 15, False)
                bullet2.set_control(True)
                bullet3 = pySprites.Bullet(boss.rect.right, boss.rect.centery, 15, False)
                bullet3.set_control(True)
                enemyBullets.add(bullet1, bullet2, bullet3)
                allSprites.add(enemyBullets)
        
            # boss collition
            if boss.rect.colliderect(bullet.rect):
                bullet.reset(player.rect.centerx, player.rect.centery -5)
                bullet.set_control(False)
                boss_health.resize()
                boss_health.set_health()
            
            # checks boss health
            if boss_health.get_health() < 0:
                invader_death.play()
                points = boss.get_point()
                score.set_score(points)
                boss.kill()
                boss_active = False
                
            if len(invaders) == 0 and not boss_active and level_2 and level_3:
                return True, score.get_score(), life.get_life()

        # refresh
        allSprites.clear(screen, background)
        allSprites.update()
        allSprites.draw(screen)   
        pygame.display.flip()
def game():
    '''This function defines the main game for Space Invaders, it takes no 
    parameters, and returns nothing, which causes the main function to exit
    meaning the game has ended. '''  
    # DISPLAY
    screen = pygame.display.set_mode((640, 480))
    pygame.display.set_caption("Space Invaders by AYUSH")
     
    # ENTITIES
    background = pygame.Surface(screen.get_size())
    
    #ALIENS CREATION
    y_coordinate = 200
    alien_list = []
    
    #A row of aliens are created and appended to two lists, one list that contains 
    #groups of the aliens based on its row, and one that contains all the aliens together
    for alien_row in range (5):
        alien = 0
        points = (alien_row+1)*10
        for x_coordinate in range(0,550,50):
            alien = pySprites.Alien(screen,alien_row,(79+x_coordinate,y_coordinate), points)
            alien_list.append(alien)
        y_coordinate -= 30

    #Sound Effects    
    laser_sound = pygame.mixer.Sound("sounds/lasersound.wav")
    laser_sound.set_volume(0.8)
    alien_sound = pygame.mixer.Sound("sounds/aliensound.wav")
    alien_sound.set_volume(0.8)
    alien_pop = pygame.mixer.Sound("sounds/alienpop.wav")
    alien_pop.set_volume(0.7)
    bonussound = pygame.mixer.Sound("sounds/bonussound.wav")
    bonussound.set_volume(0.8)
    gameover_music = pygame.mixer.Sound("sounds/gameover.wav")
    gameover_music.set_volume(0.8)
          
    #SPRITES
    gameover = pygame.image.load("images/gameover.png")
    bonusmissile = pySprites.Missile(screen)
    wall = wallcreate(screen)
    bonusalien = pySprites.BonusAlien(screen)
    player = pySprites.Player(screen)
    scorekeeper = pySprites.ScoreKeeper(screen)
    liveskeeper = pySprites.LifeKeeper(screen)
    background_image = pySprites.Background(screen)
    endzoneleft = pySprites.EndZone(screen,0)
    endzoneright = pySprites.EndZone(screen,639)
    endzonebottom = pySprites.EndZone(screen,0,True)
    laser = pySprites.Laser(screen)
    endzoneSprites = pygame.sprite.Group(endzoneright,endzoneleft)
    playergroup = pygame.sprite.Group(player)
    alienSprites = pygame.sprite.Group(alien_list)
    alienlasers = pygame.sprite.Group()    
    extra_lives = pygame.sprite.Group()
    speedboostGroup = pygame.sprite.Group()
    bottomlayer = [background_image,scorekeeper,liveskeeper,endzoneSprites,endzonebottom]
    toplayer = [player,alienSprites,bonusalien,laser,alienlasers,wall,extra_lives,speedboostGroup,bonusmissile]
    allSprites = pygame.sprite.OrderedUpdates(bottomlayer,toplayer)

    
    # ASSIGN 
    keepGoing = True
    clock = pygame.time.Clock()
    bonusaliendead = False
    alienshoot_speed = 27
    heartspawn = False
    damagedelay = 0
    
    # Hide the mouse pointer
    pygame.mouse.set_visible(False)
 
    # LOOP
    while keepGoing:
        
        # TIME
        clock.tick(30)
        
        # EVENT HANDLING
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                scorekeeper.set_highscore()
                keepGoing = False

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and laser.rect.bottom < 0:
                    laser_sound.play()
                    laser.reset((player.rect.centerx,player.rect.top))
                    
        #Movement based on user pressing or holding right or left keys
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            player.go_left()
        elif keys[pygame.K_RIGHT]:
            player.go_right()
            
        if (liveskeeper.life_status() <= 0) or (len(alienSprites) == 0):
            scorekeeper.set_highscore()
            keepGoing = False    
                    
        if (random.randrange(200) == 0) and (bonusalien.rect.left > 800) and (not bonusaliendead):
            bonusalien.reset()
        
        #If the player laser collides with the bonus alien then the bonus alien's 
        #death animation is played and is killed
        if laser.rect.colliderect(bonusalien) and (not bonusaliendead):
            scorekeeper.add_score(40)
            bonusalien.death()
            laser.remove()
            bonusaliendead = True
            
        #For each wall pixel a random number is generated, if the number is 0,
        #and the alien is in +- 10 pixels of range of the wall pixel then a missile is dropped
        for wallpixel in wall:
            bonus_missile = random.randrange(400)
            if bonus_missile == 0 and bonusalien.rect.centerx in range(wallpixel.rect.centerx-10,wallpixel.rect.centerx+10):
                bonusmissile.reset((bonusalien.rect.centerx,bonusalien.rect.bottom))
                bonussound.play()
                
        #if the bonus alien's missile collides with a wall chunks of it are removed
        if pygame.sprite.spritecollide(bonusmissile, wall, True):
            damagedelay += 1
            #By delaying the time the laser is removed it allows it to progress further
            #into the walls
            if damagedelay == 6:
                bonusmissile.remove()
                damagedelay = 0
        
        for aliens in alienSprites:
            shoot = random.randrange(alienshoot_speed*16)
            shoot_random = random.randrange(alienshoot_speed*700)  
            #If randrange is equal to 1 and the aliens are in range of the players x coordinate they shoot 
            if shoot == 1 and aliens.rect.centerx in range (player.rect.centerx-20,player.rect.centerx+20):
                    alien_laser = pySprites.AlienLaser(screen,(aliens.rect.centerx,aliens.rect.bottom))
                    alienlasers.add(alien_laser)
                    alien_sound.play()
                    allSprites = pygame.sprite.OrderedUpdates(bottomlayer,toplayer)
                    
            #If randrange is equal to 1 the alien shoots this is to make it have
            #there are two separate scenarios to have it seem kind of random
            #and at the same time make it difficult for the player
            if shoot_random == 1:
                    alien_laser = pySprites.AlienLaser(screen,(aliens.rect.centerx,aliens.rect.bottom))
                    alienlasers.add(alien_laser)
                    alien_sound.play()
                    allSprites = pygame.sprite.OrderedUpdates(bottomlayer,toplayer)
                    

        #When an alien collides with the endzones they all change direction and move down 3 pixels
        alien_bottomwall = pygame.sprite.spritecollide(endzonebottom,alienSprites,False)
        for endzones in endzoneSprites:
            alien_wallcollision = pygame.sprite.spritecollide(endzones,alienSprites,False)
            if alien_wallcollision != []:
                for aliens in alienSprites:
                    if alien_bottomwall == []:
                        aliens.switch_direction()
                        aliens.go_down()
                        aliens.speed_up()
                        alienshoot_speed = aliens.get_speed()     
                    else:
                        aliens.switch_direction()
                        
        #If alien lasers collide with the player, the player loses a live and the
        #laser is killed
        for alien_laser in alienlasers:
            player_hit = pygame.sprite.spritecollide(alien_laser, playergroup, False)
            if player_hit != []:
                alien_laser.kill()
                liveskeeper.remove_life() 
        
        #To check for collision between a piece of the wall and the laser        
        for alien_laser in alienlasers:
            wall_hit = pygame.sprite.spritecollide(alien_laser,wall,False)
            if wall_hit !=[]:
                alien_laser.kill()
                for wallpieces in wall_hit:
                    wallpieces.kill()

                
        #If the player laser collides with an alien, the alien is killed, points are
        #added to the score and the laser is removed  
        alien_collided = pygame.sprite.spritecollide(laser, alienSprites, False)
        for aliens in alien_collided :
            scorekeeper.add_score(aliens.get_points())
            
            #This creates an extralife powerup based on a 5% chance when an alien is killed
            if random.randrange(15) == 0:
                heartspawn = True
                heart = pySprites.Heart(screen,aliens.rect.center)
                extra_lives.add(heart)
                allSprites = pygame.sprite.OrderedUpdates(bottomlayer,toplayer)
                
            #This creates a speedboost powerup by a random 5% chance, and ensures
            #that a extralife and speedboost don't come from the same one alien
            if (random.randrange(15) == 0) and (not heartspawn):
                speedboost = pySprites.SpeedBoost(screen,aliens.rect.center)
                speedboostGroup.add(speedboost)
                allSprites = pygame.sprite.OrderedUpdates(bottomlayer,toplayer)
            heartspawn = False
            alien_pop.play()
            aliens.death()
            laser.remove()
        
        #If the player collides with the heart they recieve an additional life
        if pygame.sprite.spritecollide(player, extra_lives, True):
            liveskeeper.add_life()
        
        #If the player collides with the speedboost powerup they recieve a temporary
        #movespeed increase and are able to shoot faster for about 5seconds
        if pygame.sprite.spritecollide(player, speedboostGroup, True):
            player.speed_up()
            laser.speed_up()
            
        
        #If the players lasers collide with the walls, the piece of the wall is 
        #killed and the laser is removed not killed
        wall_collided = pygame.sprite.spritecollide(laser,wall,False)
        for wallpieces in wall_collided:
            laser.remove()
            wallpieces.kill()
               
        # Refresh Screen
        allSprites.clear(screen, background)
        allSprites.update()
        allSprites.draw(screen)       
        pygame.display.flip() 
        
    screen.blit(gameover, (0, 0))
    gameover_music.play()
    pygame.display.flip()       
    return   
Exemple #5
0
def main():
    '''This function defines the main game'''
      
    # DISPLAY
    pygame.display.set_caption("Super High School Level Dodger! v0.1")
    screen = pygame.display.set_mode((640, 480))
    
    # ENTITIES

    # Instantiate music and sound effects
    
    # Background music
    pygame.mixer.music.load('sound/background.mp3')
    pygame.mixer.music.set_volume(0.3)

    # Sound effect when a bomb explodes
    explosionSound = pygame.mixer.Sound("sound/explosion.wav")
    explosionSound.set_volume(0.1)
    
    # Sound effect when the player gets hit by an object
    hitSound = pygame.mixer.Sound("sound/hit.wav")
    hitSound.set_volume(0.5)
    
    # Sound effect when the player gets hit by a stain
    stainHitSound = pygame.mixer.Sound("sound/stainHit.wav")
    stainHitSound.set_volume(0.8)
    
    # Sound effect when the player gets a life-up
    lifeUpSound = pygame.mixer.Sound("sound/lifeUp.wav")
    lifeUpSound.set_volume(0.5)
    
    # Sound effect when the game starts
    startUpSound = pygame.mixer.Sound("sound/startUp.wav")
    startUpSound.set_volume(0.5)
    
    # Sound effect when the game ends
    gameOverSound = pygame.mixer.Sound("sound/gameOver.wav")
    gameOverSound.set_volume(0.5)
    
    # Instantiate the font used for the game
    font = pygame.font.Font("goodbyeDespair.ttf", 30)
    
    # Instantiates the background
    background = pygame.image.load('images/background.png')
    background = background.convert()
    screen.blit(background, (0, 0))
       
    # Instantiate the ground
    ground = pySprites.Ground(screen)
    
    # Instantiate the player
    player = pySprites.Player(screen, ground.returnTopGround())    
    
    # Instantiate the lakitu
    lakitu = pySprites.Lakitu(screen)
    
    # Instantiate a power up
    powerUp = pySprites.PowerUp(screen)
    powerUp.safeSpace()
    # Instantiate the live counter
    liveCounter = pySprites.LiveCounter()
    
    # Instantiate the score keeper
    scoreKeeper = pySprites.ScoreKeeper(screen)    
    
    # Creates list to temporarily store meteors for a row
    tempMeteorRow = []
    
    # Two rows of meteors
    for meteorRow in range(2):
        # Eight meteors per row
        for meteorCol in range(8):
            tempMeteorRow.append(pySprites.Meteor(meteorRow, meteorCol))
            
        # Seperates meteors into groups based on row number
        if meteorRow == 0:
            firstMeteorGroup = pygame.sprite.Group(tempMeteorRow)
        elif meteorRow == 1:
            secondMeteorGroup = pygame.sprite.Group(tempMeteorRow)
        
        # Empty the tempMeteorRow list
        del tempMeteorRow[:]
            
    # Instantiate a sprite group to hold all the meteors
    meteorGroup = pygame.sprite.Group(firstMeteorGroup)
            
    # Instantiate a sprite group to hold all the stains
    stainGroup = pygame.sprite.Group()

    # Instantiate a sprite group to hold all the puddles
    puddleGroup = pygame.sprite.Group()
    
    # Instantiate a sprite group to hold all the bombs
    bombGroup = pygame.sprite.Group()
    
    # Instantiate a sprite group to hold all the explosions
    explosionGroup = pygame.sprite.Group()
    
    # Instantiate a sprite group to hold the power up
    powerUpGroup = pygame.sprite.Group(powerUp)
    
    # Instantiate a sprite group holding all the sprites
    allSprites = pygame.sprite.OrderedUpdates(player, ground, lakitu, stainGroup, puddleGroup, bombGroup, powerUpGroup, explosionGroup, meteorGroup, liveCounter, scoreKeeper)
    
    # ASSIGN 
    clock = pygame.time.Clock()
    keepGoing = True
    
    # This variable keeps track if the player is moving to the left
    player_left = False
    
    # This variable keeps track if the player is moving to the right
    player_right = False
    
    # This variable keeps track if a meteor still needs to be created
    minimumMeteor = random.randrange(0,2)
    
    # This variable keeps track if there still needs to be an empty space between meteors
    minimumHole = True
    
    # This variable keeps track if a stain is currently slowing down the player
    stainSlowed = False

    # This variable will be used later for keeping track of the time since last collision
    collisonTime = 0
    
    # This variable will be used later for keeping track how long since the lakitu has thrown an oil stain
    thrownTime = 0
    
    # This variable will keep track how long it would take for the lakitu to throw an oil stain randomly
    throwDelay = random.randrange(1000,6000,1000)
    
    # This variable will keep track how long the stain effect should be 
    stainCollisionTime = 0
       
    # Hide the mouse pointer
    pygame.mouse.set_visible(False)
    
    # LOOP
    while keepGoing:
     
        # TIME
        clock.tick(30)
        # EVENT HANDLING: Player uses arrow keys, left control button and left shift button
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                keepGoing = False
                gameOver = font.render("Game Over!", 1, (255, 255, 255))
                screen.blit(gameOver, (242,230))                 
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    player_left = True
                if event.key == pygame.K_RIGHT:
                    player_right = True
                if event.key == pygame.K_LCTRL:
                    player.useMop()
                if event.key == pygame.K_LSHIFT:
                    player.useAxe()
                if event.key == pygame.K_SPACE and player.getStand():
                    player.jump()
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    player_left = False
                    player_right = False
                    
        # Go left if variable is set to True
        if player_left:
            player.go_left()
        
        # Go right if variable is set to True    
        if player_right:
            player.go_right()
        
        # Jump if variable is set to True    
        if player.getJump():
            player.jumpFall(5)
        
        # Make the lakitu start the throw animation if time has passed the throwDelay variable
        if pygame.time.get_ticks() - thrownTime > throwDelay:
            lakitu.setThrown(True)
            throwDelay = random.randrange(1000,6000,1000)
            
            # Reset the thrownTime clock
            thrownTime = pygame.time.get_ticks()
            
        # Make the lakitu throw a stain at its 16th sprite image
        if lakitu.getAnimationFrame() == 16:
            stains = pySprites.Stain(lakitu.getCoords())
            stainGroup.add(stains)
            allSprites = pygame.sprite.OrderedUpdates(player, ground, lakitu, stainGroup, puddleGroup, bombGroup, powerUpGroup, explosionGroup, meteorGroup, liveCounter, scoreKeeper)
            screen.blit(background,(0,0))
            
        # Check if any stains have collided with the ground
        stainGround = pygame.sprite.spritecollide(ground, stainGroup, False)
        
        # Create a puddle for each stain that hits the ground and kill the stain
        for eachStain in stainGround:
            puddle = pySprites.Puddle(screen, eachStain.getCoords())
            eachStain.kill()
            puddleGroup.add(puddle)
            allSprites = pygame.sprite.OrderedUpdates(player, ground, lakitu, stainGroup, puddleGroup, bombGroup, powerUpGroup, explosionGroup, meteorGroup, liveCounter, scoreKeeper)
            screen.blit(background,(0,0))
            
        # Check if any stains have collided with the player
        stainHit = pygame.sprite.spritecollide(player, stainGroup, False)
        
        # Slow down the player temporarily if the player hits the stain
        for eachStain in stainHit:
            player.slow(0.35)
            stainHitSound.play()
            eachStain.kill()
            stainSlowed = True
            
            # Reset the stainCollisionTime clock
            stainCollisionTime = pygame.time.get_ticks()

        # Check if a power up has collided with the ground
        powerUpGround = pygame.sprite.spritecollide(ground, powerUpGroup, False)
        
        # Make each power up land
        for eachPowerUp in powerUpGround:
            eachPowerUp.land()
        
        # If the player collides with a power up, gain a life and reset the power up    
        powerUpPlayer = pygame.sprite.spritecollide(player, powerUpGroup, False)
        for powerUp in powerUpPlayer:
            powerUp.safeSpace()
            lifeUpSound.play()
            scoreKeeper.addScore(100)
            liveCounter.gainLife()
            
        # Check if any meteors from the first row collided with the ground
        if pygame.sprite.spritecollide(ground, firstMeteorGroup, False):
            for row in firstMeteorGroup:
                # At least have one meteor present
                if minimumMeteor:
                    row.setRespawn(True)
                    minimumMeteor = False
                else:
                    # At least have one empty space present
                    if minimumHole:
                        row.setRespawn(False)
                        minimumHole = False
                # Reset the positions of the meteor row
                row.reset()
            # Set all variables back to true
            minimumMeteor = True
            minimumHole = True
        
        # Check if the second meteors from the second row collided with the ground 
        hittedGround = pygame.sprite.spritecollide(ground, secondMeteorGroup, False)
        
        for meteor in hittedGround:
            # Reset the positions of the meteor row
            meteor.reset()
                
        # Check if player has collided with the a puddle
        mopHit = pygame.sprite.spritecollide(player, puddleGroup, False)
        
        if mopHit:
            # Slow the player half speed if not currently slowed down
            if not(stainSlowed):
                player.slow(0.5)
            for eachMopHit in mopHit:
                # If the player is currently using the mop, kill the puddle and break out of the loop
                if player.getMop():
                    scoreKeeper.addScore(25)
                    eachMopHit.kill()
                    break

        # Check if a bomb has collided with the ground
        bombGround = pygame.sprite.spritecollide(ground, bombGroup, False)
        
        # For each bomb that collided with the ground
        for bombs in bombGround:
            # Start the ticking bomb                     
            bombs.land(ground.returnTopGround())
            # If the bomb is about to explode, create an explosion and reset bomb
            if bombs.getAnimationFrame() == 4:
                explosion = pySprites.Explosion(screen, bombs.getCoords(), bombs.getBombType())
                bombs.safeSpace()
                explosionGroup.add(explosion)
                explosionSound.play()
                allSprites = pygame.sprite.OrderedUpdates(player, ground, lakitu, stainGroup, puddleGroup, bombGroup, powerUpGroup, explosionGroup, meteorGroup, liveCounter, scoreKeeper)
                screen.blit(background,(0,0))                
     
        # Check if player has collided with the a bomb
        bombHit = pygame.sprite.spritecollide(player, bombGroup, False)
        
        if bombHit:
            for eachBombHit in bombHit:
                # If the player is currently using the axe, kill the bomb and break out of the loop
                if player.getAxe():
                    eachBombHit.safeSpace()
                    scoreKeeper.addScore(50)
                    break
                
        for aBomb in bombGroup:
            if (random.randrange(200)) == 1 and aBomb.getSafeSpace() == True:
                aBomb.reset()
                
        for aPowerUp in powerUpGroup:
            if (random.randrange(1000)) == 1 and aPowerUp.getSafeSpace() == True:
                aPowerUp.reset()
        # Check if player collided with any explosions
        if pygame.sprite.spritecollide(player, explosionGroup, False) and not(player.getInvincible()):
            # Set player to be invincible and lose a life
            player.setInvincible(True)
            hitSound.play()
            liveCounter.loseLife(2)
            
            # Reset the collisionTime clock
            collisonTime = pygame.time.get_ticks()
            
        # Check if player collided with any meteor
        if pygame.sprite.spritecollide(player, meteorGroup, False) and not(player.getInvincible()):
            # Set player to be invincible and lose a life
            player.setInvincible(True)
            hitSound.play()
            liveCounter.loseLife(1)
            
            # Reset the collisionTime clock
            collisonTime = pygame.time.get_ticks()
        
        # Takes three seconds before you are no longer invisible
        if pygame.time.get_ticks() - collisonTime > 3000:
            player.setInvincible(False)
            
        # Takes three seconds before a stain effect wears off
        if pygame.time.get_ticks() - stainCollisionTime > 3000 and not(mopHit):
            player.slow(1)
            stainSlowed = False
        
        # Create a bomb every time the score is divisible by 2000, 5 bombs maximum
        if scoreKeeper.getScore() % 1500 == 0 and scoreKeeper.getScore() < 10000:
                bomb = pySprites.Bomb(screen, random.randrange(0,5))
                bombGroup.add(bomb)
                allSprites = pygame.sprite.OrderedUpdates(player, ground, lakitu, stainGroup, puddleGroup, bombGroup, powerUpGroup, explosionGroup, meteorGroup, liveCounter, scoreKeeper)
                screen.blit(background,(0,0)) 
        
        # Second meteor group is spawned when the score reaches 7500        
        if scoreKeeper.getScore() == 5000:
            meteorGroup.add(secondMeteorGroup)
            allSprites = pygame.sprite.OrderedUpdates(player, ground, lakitu, stainGroup, puddleGroup, bombGroup, powerUpGroup, explosionGroup, meteorGroup, liveCounter, scoreKeeper)
            screen.blit(background,(0,0))
        
        # Show the start-up screen once
        if scoreKeeper.getScore() == 0:
            gameStart = font.render("Ready?", 1, (255, 255, 255))
            screen.blit(gameStart, (265,230))  
        if scoreKeeper.getScore() == 1:            
            startUpSound.play()
            pygame.time.delay(6000)
            pygame.mixer.music.play(-1)
                      
        # Add the score by 1 each time the loop instantiates    
        scoreKeeper.addScore(1)
        
        # Blit the Game-over screen if lives are zero
        if liveCounter.getLife() <= 0:
            keepGoing = False
            gameOver = font.render("Game Over!", 1, (255, 255, 255))
            screen.blit(gameOver, (242,230))    
            
        # REFRESH SCREEN
        allSprites.clear(screen, background)
        allSprites.update()
        allSprites.draw(screen)
        pygame.display.flip()
          
    # Unhide the mouse pointer     
    pygame.mouse.set_visible(True)
 
    # Play the GameOver music and go back to the start menu
    pygame.mixer.music.fadeout(0)
    gameOverSound.play()
    pygame.time.delay(7000)
    startMenu()     
Exemple #6
0
def main():
    '''This function defines the 'mainline logic' for our pyPong game.'''

    # DISPLAY
    pygame.display.set_caption("pyPong! v1.0")

    # ENTITIES
    background = pygame.Surface(screen.get_size())
    background = background.convert()
    background.fill((255, 255, 255))
    screen.blit(background, (0, 0))

    # Sprites for: ScoreKeeper label, End Zones, Ball, and Players
    score_keeper = pySprites.ScoreKeeper()
    ball = pySprites.Ball(screen)
    player1 = pySprites.Player(screen, 1)
    player1_endzone = pySprites.EndZone(screen, 0)
    player2 = pySprites.Player(screen, 2)
    player2_endzone = pySprites.EndZone(screen, 639)
    allSprites = pygame.sprite.Group(score_keeper, player1_endzone, \
                                     player2_endzone, ball, player1, player2)
    # ASSIGN
    clock = pygame.time.Clock()
    keepGoing = True

    # Hide the mouse pointer
    pygame.mouse.set_visible(False)

    # LOOP
    while keepGoing:

        # TIME
        clock.tick(30)

        # EVENT HANDLING: Player 1 uses joystick, Player 2 uses arrow keys
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                keepGoing = False
            elif event.type == pygame.JOYHATMOTION:
                player1.change_direction(event.value)
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    player2.change_direction((0, 1))
                if event.key == pygame.K_DOWN:
                    player2.change_direction((0, -1))

        # Check if player 1 scores (i.e., ball hits player 2 endzone)
        if ball.rect.colliderect(player2_endzone):
            score_keeper.player1_scored()
            ball.change_direction()

        # Check if player 2 scores (i.e., ball hits player 1 endzone)
        if ball.rect.colliderect(player1_endzone):
            score_keeper.player2_scored()
            ball.change_direction()

        # Check for game over (if a player gets 3 points)
        if score_keeper.winner():
            keepGoing = False

        # Check if ball hits Player 1 or 2
        # If so, change direction, and speed up the ball a little
        if ball.rect.colliderect(player1.rect) or\
           ball.rect.colliderect(player2.rect):
            ball.change_direction()

        # REFRESH SCREEN
        allSprites.clear(screen, background)
        allSprites.update()
        allSprites.draw(screen)
        pygame.display.flip()

    # Unhide the mouse pointer
    pygame.mouse.set_visible(True)

    # Close the game window
    pygame.quit()