Пример #1
0
def main():
    """ Main Program """

    pygame.init()

    # Set the height and width of the screen
    size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT]
    screen = pygame.display.set_mode(size)

    pygame.display.set_caption("MoyBen the Wedding")

    # Create the player
    player = Player()

    # Create all the levels
    level_list = []
    level_list.append(levels.Level_00(player))
    level_list.append(levels.Level_01(player))
    level_list.append(levels.Level_02(player))
    level_list.append(levels.Level_03(player))

    level_list.append(levels.Level_05(player))

    # Set the current level
    current_level_no = 0
    current_level = level_list[current_level_no]
    current_level.play_background_music()

    active_sprite_list = pygame.sprite.Group()
    player.level = current_level

    player.rect.x = 640
    player.rect.y = constants.SCREEN_HEIGHT - player.rect.height  #+ -2000
    active_sprite_list.add(player)

    #Loop until the user clicks the close button.
    done = False
    meowcounter = 0
    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()

    speechbubbles.preload_font()

    meowsounds = [
        pygame.mixer.Sound("meow00.ogg"),
        pygame.mixer.Sound("meow01.ogg")
    ]

    pygame.mixer.set_reserved(1)
    meow_channel = pygame.mixer.Channel(0)  # reserved
    meow_channel.set_endevent(events.EVENT_SOUNDEND_MEOW)

    # -------- Main Program Loop -----------
    while not done:
        for event in pygame.event.get():  # User did something

            if event.type == pygame.QUIT:  # If user clicked close
                done = True  # Flag that we are done so we exit this loop

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    player.go_left()
                if event.key == pygame.K_RIGHT:
                    player.go_right()
                if event.key == pygame.K_UP:
                    player.jump()
                if event.key == pygame.K_ESCAPE:
                    done = True  # Flag that we are done so we exit this loop
                if event.key == pygame.K_SPACE:
                    #  MEOW
                    meowcounter += 1
                    meowcounter = meowcounter % len(meowsounds)
                    if pygame.mixer.get_init():
                        sound = meowsounds[meowcounter]
                        meow_channel.play(sound)

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT:
                    player.stop()
                if event.key == pygame.K_RIGHT:
                    player.stop()

            events.global_eventmanager.notify(event)

        # Update the player.
        active_sprite_list.update()

        # Update items in the level
        current_level.update()
        #print player.rect.x, player.rect.y

        # If the player gets near the right side, shift the world left (-x)
        if player.rect.x >= 500:
            diff = player.rect.x - 500
            player.rect.x = 500
            current_level.shift_world_x(-diff)

        # If the player gets near the left side, shift the world right (+x)
        if player.rect.x <= 120 and player.rect.x - current_level.world_shift > 120:
            diff = 120 - player.rect.x
            player.rect.x = 120
            current_level.shift_world_x(diff)

        # Move camera down, if not on the floor yet
        if player.rect.y > 500 and player.rect.y - current_level.world_shift_y < current_level.level_limit_y + player.rect.height:
            diff = player.rect.y - 500
            player.rect.y = 500
            current_level.shift_world_y(-diff)

        # Move camera up
        if player.rect.y <= 120 and player.rect.y - current_level.world_shift_y > 120:
            diff = 120 - player.rect.y
            player.rect.y = 120
            current_level.shift_world_y(diff)

        # If the player gets to the end of the level, go to the next level
        current_position = player.rect.x + current_level.world_shift
        if current_position < current_level.level_limit:
            player.rect.x = 120
            if current_level_no < len(level_list) - 1:
                current_level_no += 1
                current_level = level_list[current_level_no]
                current_level.play_background_music()
                player.level = current_level

        # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
        current_level.draw(screen)

        active_sprite_list.draw(screen)

        # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

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

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

    # Be IDLE friendly. If you forget this line, the program will 'hang'
    # on exit.
    pygame.quit()
Пример #2
0
def main():
    """ Main Program """
    pygame.init()

    pygame.mixer.music.load("Assets/Sound/backgroundSound2.mp3")
    # pygame.mixer.music.play(3)

    # Set the height and width of the screen
    size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT]
    screen = pygame.display.set_mode(size)

    pygame.display.set_caption("JANFOX")

    # Create the player
    player = Player()

    # Create all the levels
    level_list = [
        levels.Level_02(player),
        levels.Level_03(player),
        levels.Level_01(player)
    ]

    # Set the current level
    current_level_no = 0
    current_level = level_list[current_level_no]

    active_sprite_list = pygame.sprite.Group()
    player.level = current_level

    player.rect.x = 240
    player.rect.y = constants.SCREEN_HEIGHT - player.rect.height
    player.go_right()
    active_sprite_list.add(player)

    # Loop until the user clicks the close button.
    done = False

    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()

    # -------- Main Program Loop -----------
    while not done:
        for event in pygame.event.get():  # User did something
            if event.type == pygame.QUIT:  # If user clicked close
                done = True  # Flag that we are done so we exit this loop

            if not player.isDead:
                # if event.type == pygame.USEREVENT:
                #     print('Command 2 {}'.format(event.action))

                if event.type == pygame.USEREVENT:
                    if event.command == constants.C_LEFT:
                        player.go_left()
                    if event.command == constants.C_RIGHT:
                        player.go_right()
                    if event.command == constants.C_JUMP:
                        player.jump()
                    if event.command == constants.C_PAUSE:
                        pausa()
                    if event.command == constants.C_STOP:
                        player.stop()

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_LEFT:
                        player.go_left()
                    if event.key == pygame.K_RIGHT:
                        player.go_right()
                    if event.key == pygame.K_UP:
                        player.jump()
                    if event.key == pygame.K_ESCAPE:
                        pausa()

                if event.type == pygame.KEYUP:
                    # if event.key == pygame.K_LEFT and player.change_x < 0:
                    #     player.stop()
                    # if event.key == pygame.K_RIGHT and player.change_x > 0:
                    #     player.stop()
                    if event.key == pygame.K_ESCAPE:
                        pausa()

        # Update the player.
        active_sprite_list.update()

        # Update items in the level
        current_level.update()

        # If the player gets near the right side, shift the world left (-x)
        if player.rect.x >= 500:
            diff = player.rect.x - 500
            player.rect.x = 500
            current_level.shift_world(-diff)

        # If the player gets near the left side, shift the world right (+x)
        if player.rect.x <= 120:
            diff = 120 - player.rect.x
            player.rect.x = 120
            current_level.shift_world(diff)

        # If the player gets to the end of the level, go to the next level
        current_position = player.rect.x + current_level.world_shift
        if current_position < current_level.level_limit:
            if current_level_no < len(level_list) - 1:
                player.rect.x = 100
                current_level_no += 1

                current_level = level_list[current_level_no]
                player.level = current_level
                player.velocity *= 1.25
            elif current_level_no == len(
                    level_list) - 1 and not player.victory:
                # victory
                player.victory = True
                GameOverVictory(player.score, "VICTORY", None)

        # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
        current_level.draw(screen)
        active_sprite_list.draw(screen)

        # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
        showScore(screen, player.score, 450, 15)
        showHealthBar(screen, player.health, 10, 10)
        showLifes(screen, player.lifes, 910, 10)

        # Validate lifes or GameOver
        if player.lifes == 0:
            foxImg = pygame.image.load(
                'Assets/Sprites/personage/Fox/Dead/Dead(10).png')
            GameOverVictory(player.score, "HAS PERDIDO", foxImg)

        # Validate victory
        if player.victory:
            foxImg = pygame.image.load(
                'Assets/Sprites/personage/Fox/Fall/Fall(4).png')
            GameOverVictory(player.score, "HAS GANADO", foxImg)

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

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

    # Be IDLE friendly. If you forget this line, the program will 'hang'
    # on exit.
    pygame.quit()
Пример #3
0
def main():
    """ Main Program """
    pygame.init()

    # Set the height and width of the screen
    size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT]
    screen = pygame.display.set_mode(size)
    font = pygame.font.Font(None, 25)
    pygame.display.set_caption("Slime Shuffle")

    # Limit to 60 frames per second
    frame_count = 0
    frame_rate = 60
    start_time = 60
    # Create the player
    player = Player()

    # Create all the levels
    level_list = []
    level_list.append(levels.Level_01(player))
    level_list.append(levels.Level_02(player))
    level_list.append(levels.Level_03(player))
    #level_list.append(levels.Level_04(player))
    #level_list.append(levels.Level_05(player))

    # Set the current level
    current_level_no = 0
    current_level = level_list[current_level_no]

    active_sprite_list = pygame.sprite.Group()
    player.level = current_level

    player.rect.x = 340
    player.rect.y = constants.SCREEN_HEIGHT - player.rect.height
    active_sprite_list.add(player)

    # Loop until the user clicks the close button.
    done = False

    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()

    #Plays BGM
    pygame.mixer.music.load('music/Memoraphile - Spooky Dungeon.wav')
    pygame.mixer.music.play(loops=-1)

    # -------- Main Program Loop -----------
    while not done:
        total_seconds = start_time - (frame_count // frame_rate)
        if total_seconds < 0:
            total_seconds = 0
            game_over()

        # Divide by 60 to get total minutes
        minutes = total_seconds // 60

        # Use modulus (remainder) to get seconds
        seconds = total_seconds % 60

        # Use python string formatting to format in leading zeros
        output_string = "Time left: {0:02}:{1:02}".format(minutes, seconds)

        # Blit to the screen
        text = font.render(output_string, True, constants.White)
        screen.blit(text, [50, 50])

        # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
        frame_count += 1

        # Limit frames per second
        clock.tick(frame_rate)

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

        for event in pygame.event.get():  # User did something
            if event.type == pygame.QUIT:  # If user clicked close
                done = True  # Flag that we are done so we exit this loop

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    player.go_left()
                if event.key == pygame.K_RIGHT:
                    player.go_right()
                if event.key == pygame.K_UP:
                    player.jump()
                if event.key == pygame.K_SPACE:
                    player.drop()
                if event.key == pygame.K_ESCAPE:
                    victory_screen()

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT and player.change_x < 0:
                    player.stop()
                if event.key == pygame.K_RIGHT and player.change_x > 0:
                    player.stop()

        # Update the player.
        active_sprite_list.update()

        # Update items in the level
        current_level.update()

        # If the player gets near the right side, shift the world left (-x)
        if player.rect.right >= 500:
            diff = player.rect.right - 500
            player.rect.right = 500
            current_level.shift_world(-diff)

        # If the player gets near the left side, shift the world right (+x)
        if player.rect.left <= 120:
            diff = 120 - player.rect.left
            player.rect.left = 120
            current_level.shift_world(diff)

        # If the player gets to the end of the level, go to the next level
        current_position = player.rect.x + current_level.world_shift
        if current_position < current_level.level_limit:
            player.rect.x = 120
            if current_level_no < len(level_list) - 1:
                current_level_no += 1
                current_level = level_list[current_level_no]
                player.level = current_level

        # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
        current_level.draw(screen)
        active_sprite_list.draw(screen)
        screen.blit(text, [50, 50])
        # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

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

    # Be IDLE friendly. If you forget this line, the program will 'hang'
    # on exit.
    pygame.quit()
Пример #4
0
def main():
    """ Main Program

    First initializes pygame and pygame.mixer

    variables:
        size: The size of the window
        screen: Sets the display for the game
        player: The player object
        title: The title itself
        butOne: The start button
        butTwo: Load game (didn't implement)
        hubLevel: Where the player begins and is able to choose other levels
        golBossLev: The golem boss
        skeBossLev: The skeleton boss
        magBosLev: The magma boss
        level_list: Holds the levels in a list
        TwoBut: Holds the starting buttons
        menuSelect: determins which button is currently selected
        cover: Used for transitions
        backTitle: background for the title
        current_level_no: The number of the current level the player is in
        current_level: The current level the player is in
        active_sprite_list: Used to hold the player sprite
        slash: Holds the melee sprite
        bullets: Holds the bullet sprites
        beampew: Holds the laser sprite
        begin: Holds sprites needed for the titlescreen
        beginBack: Holds the background for the title
        transition: Holds the sprite that covers the screen during transition
        winMes: Holds the win message
        hugLeft: True if player is moving left so they can cling to the wall
        hugRight: True if player is moving right so they can cling to the wall
        done: True if player wants to quit and exit the game
        toIntro: True when player leaves the titlescreen to the game or quit the application
        count2: Used to determine how long the melee attack will stay on screen
        attack: True if player wants to melee attack
        linger: Allows the melee attack to stay on screen
        laser: True if player wants to laser attack
        clock: Used to manage how fast the screen updates
        canSelect: Allows player to select the starting buttons
        ToNextPart: True when player presses the start button to get to the game
        canMove = Allows player to move in game
        canUpdate = Allows game to update most assets
        canChange = Allows player to change level
        fading = True if the game is in the process of a transition
        aboutToFade = True when the player hits a point to begin transition
        worldChosen = The level the player chose
        xLimR = Limits level layout to the right
        xLimL = Limits level layout to the left



    Functions:
        Reset: resets the levels after player loses or lears it

    While loops:
        First loop: The title loop
        Second loop: The main game loop


    """
    pygame.init()
    pygame.mixer.init()


    # Set the height and width of the screen
    size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT]
    screen = pygame.display.set_mode(size)

    #Sets the title
    pygame.display.set_caption("Doki Doki Island!")

    # Create the player
    player = Player()

    #Creates the title screen
    title = Title.Start()
    butOne = But1.Start()
    butTwo = But2.Start()

    # Create all the levels
    hubLevel = levels.Level_00(player, screen)
    hubLevel2 = levels.Level_01(player, screen)
    hubLevel3 = levels.Level_01(player, screen)
    golBossLev = levels.Level_04(player, screen)
    skeBossLev = levels.Level_03(player, screen)
    magBossLev = levels.Level_05(player, screen)

    # Appends the levels to the list
    level_list = []
    level_list.append(hubLevel)
    level_list.append(hubLevel2)
    level_list.append(hubLevel3)
    '''level_list.append(golBossLev)'''
    '''level_list.append(skeBossLev)'''
    '''level_list.append(magBossLev)'''

    # To hold the title buttons
    Twobut = []
    menuSelect = 0

    #Used during transitions, fades screen black
    cover = black.Fade(screen)

    #Sets the background in the title screen
    backTitle = backgroundTitle.Start()

    # Set the current level
    current_level_no = 0
    current_level = level_list[current_level_no]

    # All relevant groups for sprites to be used in the game
    active_sprite_list = pygame.sprite.Group()
    slash = pygame.sprite.Group()
    bullets = pygame.sprite.Group()
    beampew = pygame.sprite.Group()
    begin = pygame.sprite.Group()
    beginBack = pygame.sprite.Group()
    transition = pygame.sprite.Group()
    winMes = pygame.sprite.Group()


    # Starts the player off in the hub level
    player.level = current_level
    player.bullets = bullets

    # this is to place the character
    player.rect.x = 200
    player.rect.y = 350
    active_sprite_list.add(player)

    #Adds these to their relevant groups
    begin.add(title)
    beginBack.add(backTitle)
    transition.add(cover)


    #Used when player hugs a wall
    hugLeft = False;
    hugRight = False;

    # Loop until the user clicks the close button.
    done = False
    toIntro = False


    count2 = 0
    attack = False
    linger = False
    laser = False

    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()

    #Loads the first music file, the title screen music
    """pygame.mixer.music.load('RabiRabiMain.ogg')
    pygame.mixer.music.play(-1, 0.0)
    """

    # Used when selecting the buttons on title screen
    canSelect = False
    toNextPart = False

    #----- Title screen -------
    while not toIntro:

        for event in pygame.event.get():  # User did something
            if event.type == pygame.QUIT:  # If user clicked close
                done = True
                toIntro = True

            if event.type == pygame.KEYDOWN and canSelect:
                if event.key == pygame.K_LEFT:

                    #When use press left key, it selects the left button
                    if menuSelect == 1:
                        menuSelect = 0
                        butOne.highlighted = True
                        butTwo.highlighted = False

                if event.key == pygame.K_RIGHT:

                    #When use press right key, it selects the right button
                    if menuSelect == 0:
                        menuSelect = 1
                        butTwo.highlighted = True
                        butOne.highlighted = False

                if event.key == pygame.K_SPACE:
                    #When use press space key, it selects the button
                    if menuSelect == 1:
                        print('1')

                    if menuSelect == 0:

                        butOne.selected = True

            if event.type == pygame.KEYUP and canSelect:
                if event.key == pygame.K_SPACE:
                    #When player releases space key, then the button chosen will do its action
                    if menuSelect == 1:
                        #Meant for a load file button, but didn't get around to it
                        print('lol')

                    if menuSelect == 0:
                        butOne.selected = False
                        #fade out black, then to main game
                        cover.inout = True
                        cover.go = True
                        toNextPart = True
                        canSelect = False
                        #pygame.mixer.music.fadeout(1000)


        screen.fill(constants.BLUE)


        #Updates and draws the relevant groups for the title screen
        beginBack.update()
        begin.update()
        transition.update()

        beginBack.draw(screen)
        begin.draw(screen)
        transition.draw(screen)

        #Intially, 'cover' will be black. This is to stop the transition once the title screen can be seen
        if cover.time < 0 and cover.go:
            cover.go = False
            cover.time = 0


        #After the title finishes bouncing, the two buttons are added
        if title.change_y == 0 and len(begin) <= 1:
            begin.add(butOne)
            begin.add(butTwo)
            Twobut.append(butOne)
            Twobut.append(butTwo)


        #This to intially highlight the first button once the buttons stop moving
        if butOne.change_y >= 0 and butTwo.change_y >= 0 and not canSelect:
            butOne.highlighted = True
            canSelect = True

        #When the uer chooses an option, the screen will fade and break from the loop, then onto the game
        if toNextPart and cover.inout and cover.time >= 255:
            toIntro = True




        clock.tick(60)
        pygame.display.flip()





    #Variables used for various functions in the game
    canMove = True
    canUpdate = True
    canChange = False
    fading = False
    aboutToFade = True
    worldChosen = 0
    previousWorld = 0
    bossLev = False
    hubLev = True

    xLimR = True
    xLimL = True


    #Resets the levels so the player can play them again if they go back to the specific level
    def reset(player, screen, level_list, worldChosen):

        print(current_level.getOriX())

        if worldChosen == 0:

            current_level.resetHub(current_level.level_x_limit, current_level.level_y_limit)


        elif worldChosen == 1:

            current_level.resetHub(current_level.level_x_limit, current_level.level_y_limit)
            player.rect.x = 600


        elif worldChosen == 3:
            #hubLevel = levels.Level_00(player, screen)
            golBossLev = levels.Level_04(player, screen)

            if len(level_list) < 4:
                level_list.append(golBossLev)
            #level_list[0] = hubLevel
            else:
                level_list[3] = golBossLev




        player.rect.x = 200
        player.rect.y = 350






    # -------- Main Game Loop -----------
    while not done:

        for event in pygame.event.get():  # User did something
            if event.type == pygame.QUIT:  # If user clicked close
                done = True  # Flag that we are done so we exit this loop

            if event.type == pygame.KEYDOWN and not player.hurt:
                if event.key == pygame.K_LEFT:
                #Moves the player left
                    if canMove:

                        player.go_left()
                        hugLeft = True
                        hugRight = False
                        player.direction = 'l'
                if event.key == pygame.K_RIGHT:
                #Moves the player right
                    if canMove:
                        player.go_right()
                        hugRight = True
                        hugLeft = False
                        player.direction = 'r'

                if event.key == pygame.K_UP:
                #Makes player jump
                    if canMove:
                        player.jump(hugRight, hugLeft)

                if event.key == pygame.K_DOWN:
                #Makes player crouch
                    if canMove:
                        player.crouch()

                if event.key == pygame.K_y:
                #Allows player to melee attack
                    if canMove:
                        attack = True
                if event.key == pygame.K_w:
                #Allows player to shoot
                    if canMove:
                        shot = Shooter(player)
                        shot.level = current_level
                        bullets.add(shot)

                if event.key == pygame.K_i:
                #Allows player to fire the laser
                    if canMove:
                        laser = True

                if event.key == pygame.K_o:
                #Allows player to fire the wave shot
                    if canMove:
                        waveshot = Wave(player, 1)
                        waveshot2 = Wave(player, -1)
                        bullets.add(waveshot)
                        bullets.add(waveshot2)


            if event.type == pygame.KEYUP and not player.hurt:
                #When player releases left key, stops moving
                if event.key == pygame.K_LEFT and player.change_x < 0:
                    player.stop()
                    hugLeft = False
                if event.key == pygame.K_RIGHT and player.change_x > 0:
                #When player releases right key, stops moving
                    player.stop()
                    hugRight = False

                '''if event.key == pygame.K_DOWN:
                #When player releases down key, makes player stand up
                    if canMove:
                        player.stand()'''
                if event.key == pygame.K_i:
                    beampew.empty()


        #checks what level the player is in and if music isn't pkaying at the moment and plays the appropriate song
        """
        if current_level_no == 0 and not pygame.mixer.music.get_busy():
            pygame.mixer.music.load('RabiRabiHub.ogg')
            pygame.mixer.music.play(-1, 0.0)
        elif current_level_no == 1 and not pygame.mixer.music.get_busy():
            pygame.mixer.music.load('RabiRabiRavine.ogg')
            pygame.mixer.music.play(-1, 0.0)
        elif current_level_no == 2 and not pygame.mixer.music.get_busy():
            pygame.mixer.music.load('RabiRabiPandora.ogg')
            pygame.mixer.music.play(-1, 0.0)
        elif current_level_no == 3 and not pygame.mixer.music.get_busy():
            pygame.mixer.music.load('RabiRabiVolcano.ogg')
            pygame.mixer.music.play(-1, 0.0)
        """



        #When player wins, creates the 'clear' that falls down from the top
        if player.winner:
            player.winner = False
            win = winning.win()
            winMes.add(win)
            bullets.empty()
            beampew.empty()

        #When the 'clear' is gone, it begins transition
        if len(winMes) > 0:
            for winThi in winMes:
                if winThi.rect.y >= constants.SCREEN_HEIGHT:
                    winMes.empty()
                    aboutToFade = True
                    worldChosen = previousWorld


        #If player is dead, begin transition
        if player.dead:
            aboutToFade = True
            worldChosen = previousWorld

        #Sets the variables before transitioning
        if aboutToFade and not fading:
            cover.go = True
            canMove = False
            canUpdate = False
            fading = True
            if cover.inout:
                cover.inout = False
            else:
                cover.inout = True
            #pygame.mixer.music.fadeout(800)



        #If true, allows to update the relevant game assets
        if canUpdate:
            active_sprite_list.update(hugRight, hugLeft)
            current_level.update()
            bullets.update(bullets)
            beampew.update(player)
            winMes.update()

            """

            if attack == True:
                swipe = Hammer(player)
                slash.add(swipe)
                linger = True

            if linger == True:
                slash.update()
                count2 += 1

            if count2 == 5:
                slash.empty()
                count2 = 0
                linger = False

            if laser == True:
                beam = Laser(player)
                beampew.add(beam)
                laser = False

            """



        #Used to determine if player is close to an edge of a level
        toTheRight = player.rect.x + current_level.world_shift
        toTheLeft = player.rect.x + current_level.left_x

        #Sets the relevant variables when player reaches an edge from the right or the left
        if toTheRight < current_level.level_x_limit:
            xLimR = False

        if toTheLeft <= 450:
            xLimL = False




        # If the player gets near the right side, shift the world left (-x)
        # Wont shift if in boss level
        if player.rect.x >= 550 and not player.bossChange and xLimR:
            diff = player.rect.x - 550
            player.rect.x = 550
            current_level.shift_world(-diff)
            xLimL = True

        # If the player gets near the left side, shift the world right (+x)
        # Wont shift if in boss level
        if player.rect.x <= 450 and not player.bossChange and xLimL:
            diff = 450 - player.rect.x
            player.rect.x = 450
            current_level.shift_world(diff)
            xLimR = True

        # if player is jumping up, shift the world up when appropriate
        # Wont shift if in boss level
        if player.rect.y <= 150 and not player.bossChange:
            diff = 150 - player.rect.y
            player.rect.y = 150
            current_level.shift_worldY(diff)

        # if player is falling, shift world down when appropriate
        # Wont shift if in boss level
        if player.rect.y >= 500 and not player.bossChange:
            diff = player.rect.y - 500
            player.rect.y = 500
            current_level.shift_worldY(-diff)


        # When a player chose a portal, will transport player to appropriate level
        playerChose = pygame.sprite.spritecollide(player, current_level.platform_choose, False)
        if len(playerChose) > 0 and not aboutToFade:
            aboutToFade = True
            for chosen in playerChose:
                worldChosen = chosen.choice
                if worldChosen < 2:
                    previousWorld = worldChosen
                print(worldChosen)

        #if true, changes the level
        if canChange:
            canChange = False
            print(worldChosen)

            if worldChosen < 2:
                hubLev = True
                bossLev = False
            else:
                bossLev = True
                hubLev = False


            #Checks player's current level and then transports to the approprate level
            if bossLev:
                reset(player, screen, level_list, worldChosen)
                current_level_no = worldChosen
                current_level = level_list[current_level_no]


            elif hubLev:
                current_level_no = worldChosen
                current_level = level_list[current_level_no]
                reset(player, screen, level_list, worldChosen)



            player.level = current_level

            # Checks if player is in a boss level
            if bossLev:
                player.bossTime = True




        # Draws the sprites
        current_level.draw(screen)
        active_sprite_list.draw(screen)
        slash.draw(screen)
        bullets.draw(screen)
        beampew.draw(screen)
        winMes.draw(screen)


        #When the transition is fully finished, it sets the variables
        if cover.time <= 0 and not cover.inout and cover.go:
            cover.go = False
            fading = False
            aboutToFade = False
            canMove = True
            canUpdate = True


        #As the screen is fully black, sets the variables
        if cover.time >= 255 and cover.inout and cover.go:
            cover.inout = False
            canChange = True
            player.hp = 100
            player.dead = False
            player.bossTime = False

            #If the player's last level was a boss level, sets these variables
            if bossLev:
                player.bossTime = False
                player.bossChange = False
                player.normalChange = True
                player.hurtCounter = 0
                '''player.rect.y = 450'''
                active_sprite_list.update(hugRight, hugLeft)
                active_sprite_list.draw(screen)

            #If the player's last level was the hub level, sets these variables
            else:
                player.bossTime = True
                print("yo")
                active_sprite_list.update(hugRight, hugLeft)
                active_sprite_list.draw(screen)




        # if true, does the transition
        if fading:
            transition.update()
            transition.draw(screen)

        #For hammer, prevents multiple melee attacks in one spot
        #attack = False




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

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

    # Be IDLE friendly. If you forget this line, the program will 'hang'
    # on exit.
    pygame.quit()
Пример #5
0
def main():
    DEBUG = False
    """
    Global constants
    """

    # Colors
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)
    BLUE = (0, 0, 255)

    pygame.init()

    selectButton = 4

    Monitor = True
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(selectButton, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    if (Monitor):
        WIDTH = 1824
        HEIGHT = 984
        scale_x = (1824.0 / 800)
        scale_y = (984.0 / 480)
    else:
        WIDTH = 800
        HEIGHT = 480
        scale_x = 1
        scale_y = 1

    timerLength = 60

    selectionTime = 1.5

    white = (255, 255, 255)
    black = (0, 0, 0)
    red = (255, 0, 0)
    green = (0, 255, 0)
    blue = (0, 0, 255)
    yellow = (255, 255, 0)
    orange = (255, 165, 0)
    purple = (128, 0, 128)

    whiteBlock = pygame.image.load("whiteBlock.gif")
    whiteBlock = pygame.transform.scale(
        whiteBlock, (int(100 * scale_x), int(100 * scale_y)))
    blackBlock = pygame.image.load("blackBlock.gif")
    blackBlock = pygame.transform.scale(
        blackBlock, (int(100 * scale_x), int(100 * scale_y)))
    redBlock = pygame.image.load("redBlock.gif")
    redBlock = pygame.transform.scale(redBlock,
                                      (int(100 * scale_x), int(100 * scale_y)))
    greenBlock = pygame.image.load("greenBlock.gif")
    greenBlock = pygame.transform.scale(
        greenBlock, (int(100 * scale_x), int(100 * scale_y)))
    blueBlock = pygame.image.load("blueBlock.gif")
    blueBlock = pygame.transform.scale(
        blueBlock, (int(100 * scale_x), int(100 * scale_y)))
    yellowBlock = pygame.image.load("yellowBlock.gif")
    yellowBlock = pygame.transform.scale(
        yellowBlock, (int(100 * scale_x), int(100 * scale_y)))
    orangeBlock = pygame.image.load("orangeBlock.gif")
    orangeBlock = pygame.transform.scale(
        orangeBlock, (int(100 * scale_x), int(100 * scale_y)))
    purpleBlock = pygame.image.load("purpleBlock.gif")
    purpleBlock = pygame.transform.scale(
        purpleBlock, (int(100 * scale_x), int(100 * scale_y)))


    colors = [[whiteBlock,"white"], [blackBlock, "black"], [redBlock, "red"],\
          [greenBlock, "green"], [blueBlock, "blue"], [yellowBlock, "yellow"],\
          [orangeBlock, "orange"], [purpleBlock, "purple"]]

    Triangle = pygame.image.load("Triangle.gif")
    Triangle = pygame.transform.scale(Triangle,
                                      (int(100 * scale_x), int(100 * scale_y)))
    Star = pygame.image.load("Star.gif")
    Star = pygame.transform.scale(Star,
                                  (int(100 * scale_x), int(100 * scale_y)))
    Square = pygame.image.load("Square.gif")
    Square = pygame.transform.scale(Square,
                                    (int(100 * scale_x), int(100 * scale_y)))
    Rectangle = pygame.image.load("Rectangle.gif")
    Rectangle = pygame.transform.scale(
        Rectangle, (int(100 * scale_x), int(100 * scale_y)))
    Oval = pygame.image.load("Oval.gif")
    Oval = pygame.transform.scale(Oval,
                                  (int(100 * scale_x), int(100 * scale_y)))
    Circle = pygame.image.load("Circle.gif")
    Circle = pygame.transform.scale(Circle,
                                    (int(100 * scale_x), int(100 * scale_y)))
    Pentagon = pygame.image.load("Pentagon.gif")
    Pentagon = pygame.transform.scale(Pentagon,
                                      (int(100 * scale_x), int(100 * scale_y)))
    Hexagon = pygame.image.load("Hexagon.gif")
    Hexagon = pygame.transform.scale(Hexagon,
                                     (int(100 * scale_x), int(100 * scale_y)))

    shapes = [[Triangle, "triangle"], [Star, "star"], [Square, "square"],\
          [Rectangle, "rectangle"], [Oval, "oval"], [Circle, "circle"],\
          [Pentagon, "pentagon"], [Hexagon, "hexagon"]]

    menu_bg = pygame.image.load("MainMenu.gif")
    menu_bg = pygame.transform.scale(menu_bg, (WIDTH, HEIGHT))
    menu_bg_center = pygame.image.load("MainMenu-Center.gif")
    menu_bg_center = pygame.transform.scale(menu_bg_center, (WIDTH, HEIGHT))
    menu_bg_left = pygame.image.load("MainMenu-Left.gif")
    menu_bg_left = pygame.transform.scale(menu_bg_left, (WIDTH, HEIGHT))
    menu_bg_right = pygame.image.load("MainMenu-Right.gif")
    menu_bg_right = pygame.transform.scale(menu_bg_right, (WIDTH, HEIGHT))
    menu_bg_up = pygame.image.load("MainMenu-Up.gif")
    menu_bg_up = pygame.transform.scale(menu_bg_up, (WIDTH, HEIGHT))
    menu_bg_down = pygame.image.load("MainMenu-Down.gif")
    menu_bg_down = pygame.transform.scale(menu_bg_down, (WIDTH, HEIGHT))

    difficulty_bg = pygame.image.load("DifficultySelect.gif")
    difficulty_bg = pygame.transform.scale(difficulty_bg, (WIDTH, HEIGHT))
    easy_difficulty_bg = pygame.image.load("DifficultySelect-Easy.gif")
    easy_difficulty_bg = pygame.transform.scale(easy_difficulty_bg,
                                                (WIDTH, HEIGHT))
    medium_difficulty_bg = pygame.image.load("DifficultySelect-Medium.gif")
    medium_difficulty_bg = pygame.transform.scale(medium_difficulty_bg,
                                                  (WIDTH, HEIGHT))
    hard_difficulty_bg = pygame.image.load("DifficultySelect-Hard.gif")
    hard_difficulty_bg = pygame.transform.scale(hard_difficulty_bg,
                                                (WIDTH, HEIGHT))

    math_bg = pygame.image.load("MathDefault.gif")
    math_bg = pygame.transform.scale(math_bg, (WIDTH, HEIGHT))
    math_bg_left = pygame.image.load("MathLeft.gif")
    math_bg_left = pygame.transform.scale(math_bg_left, (WIDTH, HEIGHT))
    math_bg_right = pygame.image.load("MathRight.gif")
    math_bg_right = pygame.transform.scale(math_bg_right, (WIDTH, HEIGHT))

    game_bg = pygame.image.load("GameDefault.gif")
    game_bg = pygame.transform.scale(game_bg, (WIDTH, HEIGHT))
    game_bg_left = pygame.image.load("GameLeft.gif")
    game_bg_left = pygame.transform.scale(game_bg_left, (WIDTH, HEIGHT))
    game_bg_right = pygame.image.load("GameRight.gif")
    game_bg_right = pygame.transform.scale(game_bg_right, (WIDTH, HEIGHT))

    GameOver_bg = pygame.image.load("GameOver.gif")
    GameOver_bg = pygame.transform.scale(GameOver_bg, (WIDTH, HEIGHT))

    gameDisplay = pygame.display.set_mode((WIDTH, HEIGHT))
    #gameDisplay = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
    pygame.display.set_caption('Stand and Play!')

    pygame.mouse.set_visible(False)
    pygame.display.update()

    font = pygame.font.Font('/home/pi/.fonts/COURIER.TTF', 28)

    if (Monitor):
        font = pygame.font.Font('/home/pi/.fonts/COURIER.TTF', 72)
        largeFont = pygame.font.Font('/home/pi/.fonts/COURIER.TTF', 108)
    else:
        font = pygame.font.Font('/home/pi/.fonts/COURIER.TTF', 28)
        largeFont = pygame.font.Font('/home/pi/.fonts/COURIER.TTF', 48)

    #Platformer stuff
    player = Player()

    level_list = []
    level_list.append(levels.Level_00(player))
    level_list.append(levels.Level_01(player))
    level_list.append(levels.Level_02(player))
    level_list.append(levels.Level_03(player))
    level_list.append(levels.Level_04(player))
    level_list.append(levels.Level_05(player))
    level_list.append(levels.Level_06(player))
    level_list.append(levels.Level_07(player))
    level_list.append(levels.Level_08(player))

    current_level_no = 0
    current_level = level_list[current_level_no]

    active_sprite_list = pygame.sprite.Group()
    player.level = current_level

    player.rect.x = 340
    player.rect.y = HEIGHT - player.rect.height
    active_sprite_list.add(player)

    clock = pygame.time.Clock()

    pygame.mixer.init(44100, -16, 2, 2048)
    pygame.mixer.music.set_volume(0)
    pygame.mixer.music.load('TestMusic.wav')
    pygame.mixer.music.play(-1)
    running = True

    lean = "none"
    score = 0

    i = 0

    numbersNeeded = True
    falseSolutionNeeded = True
    solutionPosNeeded = True
    answerGiven = False
    timerStarted = False
    difficultySelected = False
    colorNeeded = True
    answersShown = False
    shapeNeeded = True

    start_ticks = pygame.time.get_ticks()

    selection = "none"
    previousTime = time()

    global gameOver
    global Platformer

    mainMenu = True
    Colors = False
    Shapes = False
    Math = False
    Platformer = False
    gameOver = False

    while (running):
        while (mainMenu):

            pygame.mixer.music.set_volume(0)

            numbersNeeded = True
            falseSolutionNeeded = True
            solutionPosNeeded = True
            answerGiven = False
            timerStarted = False
            difficultySelected = False
            colorNeeded = True
            answersShown = False
            shapeNeeded = True

            mainMenu = True
            Colors = False
            Shapes = False
            Math = False
            Platformer = False
            gameOver = False

            score = 0

            selection = "none"
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                    pygame.quit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        running = False
                        pygame.quit()
                    if (DEBUG):
                        if event.key == pygame.K_LEFT:
                            lean = "left"
                        elif event.key == pygame.K_RIGHT:
                            lean = "right"
                        elif event.key == pygame.K_UP:
                            lean = "forward"
                        elif event.key == pygame.K_DOWN:
                            lean = "back"
                        else:
                            lean = "none"

            if (not DEBUG):
                lean = rotationTest()

            # update background to highlight selection
            if (lean == "left"):
                gameDisplay.blit(menu_bg_left, (0, 0))
            elif (lean == "right"):
                gameDisplay.blit(menu_bg_right, (0, 0))
            elif (lean == "forward"):
                gameDisplay.blit(menu_bg_up, (0, 0))
            elif (lean == "back"):
                gameDisplay.blit(menu_bg_down, (0, 0))
            else:
                gameDisplay.blit(menu_bg_center, (0, 0))

            if (lean == "none"):
                previousTime = time()

            if (time() - previousTime >=
                    selectionTime) or (GPIO.input(selectButton) == False):
                if (lean == "left"):
                    selection = "left"
                elif (lean == "right"):
                    selection = "right"
                elif (lean == "back"):
                    selection = "back"
                elif (lean == "forward"):
                    selection = "forward"

                if (GPIO.input(selectButton) == False):
                    sleep(0.2)
            else:
                selection = "none"

            if (selection == "left"):
                mainMenu = False
                Colors = True
                Math = False
                Shapes = False
                Platformer = False
            elif (selection == "right"):
                mainMenu = False
                Colors = False
                Math = False
                Shapes = True
                Platformer = False
            elif (selection == "back"):
                mainMenu = False
                Colors = False
                Math = True
                Shapes = False
                Platformer = False
            elif (selection == "forward"):
                mainMenu = False
                Colors = False
                Math = False
                Shapes = False
                Platformer = True

            gameOver = False
            i = 0

            pygame.display.update()

        while (Math):
            if (i == 0):
                previousTime = time()
                i += 1
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                    pygame.quit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        running = False
                        pygame.quit()

            while (difficultySelected == False):

                lean = rotationTest()

                if (lean == "left"):
                    gameDisplay.blit(easy_difficulty_bg, (0, 0))
                elif (lean == "back"):
                    gameDisplay.blit(medium_difficulty_bg, (0, 0))
                elif (lean == "right"):
                    gameDisplay.blit(hard_difficulty_bg, (0, 0))
                else:
                    gameDisplay.blit(difficulty_bg, (0, 0))
                pygame.display.update()

                if (lean == "none") or (lean == "forward"):
                    previousTime = time()

                if (time() - previousTime >=
                        selectionTime) or (GPIO.input(selectButton) == False):
                    if (lean == "left"):
                        difficulty = "easy"
                        difficultySelected = True
                    elif (lean == "back"):
                        difficulty = "medium"
                        difficultySelected = True
                    elif (lean == "right"):
                        difficulty = "hard"
                        difficultySelected = True
                    else:
                        difficultySelected = False

                    if (GPIO.input(selectButton) == False):
                        sleep(0.2)

            if (timerStarted == False):
                start_ticks = pygame.time.get_ticks()
                timerStarted = True

            # get direction of lean
            lean = rotationTest()

            # update background to highlight selection
            if (lean == "left"):
                gameDisplay.blit(math_bg_left, (0, 0))
            elif (lean == "right"):
                gameDisplay.blit(math_bg_right, (0, 0))
            else:
                gameDisplay.blit(math_bg, (0, 0))

            # get random numbers for question/solution
            if (numbersNeeded):
                num1 = randint(1, 10)
                num2 = randint(1, 10)
                if (difficulty == "hard"):
                    num1 = randint(1, 5)
                    num2 = randint(1, 5)
                numbersNeeded = False

            # show difficulty on screen
            difficultyText = font.render(difficulty, True, white)
            difficultyRect = difficultyText.get_rect()
            if (difficulty == "medium"):
                difficultyRect.center = (int(325 * scale_x), int(35 * scale_y))
            else:
                difficultyRect.center = (int(300 * scale_x), int(35 * scale_y))
            gameDisplay.blit(difficultyText, difficultyRect)

            # generate countdown timer
            seconds = (pygame.time.get_ticks() - start_ticks) / 1000
            if (seconds <= timerLength):
                countdown = timerLength - seconds
            else:
                gameOver = True
                Math = False

                #math = False
            timerText = font.render(str(countdown), True, white)
            timerRect = timerText.get_rect()
            timerRect.center = (int(160 * scale_x), int(447 * scale_y))
            gameDisplay.blit(timerText, timerRect)

            # generate question text and solution based on difficulty if timer != 0
            if (countdown != 0):
                if (difficulty == "easy"):
                    questionText = largeFont.render(
                        "What is {} + {}?".format(num1, num2), True, black)
                    solution = num1 + num2
                elif (difficulty == "medium"):
                    questionText = largeFont.render(
                        "What is {} * {}?".format(num1, num2), True, black)
                    solution = num1 * num2
                elif (difficulty == "hard"):
                    questionText = largeFont.render(
                        "What is {} ^ {}?".format(num1, num2), True, black)
                    solution = num1**num2
                else:
                    questionText = largeFont.render("ERROR", True, black)

            # show question on screen
            questionRect = questionText.get_rect()
            questionRect.center = (WIDTH / 2, int(150 * scale_y))
            gameDisplay.blit(questionText, questionRect)

            # generate false solution
            if (falseSolutionNeeded):
                falseSolution = solution + (randint(-5, -1) or randint(1, 5))
                if (difficulty == "easy"):
                    while (falseSolution < 1):
                        falseSolution = solution + (randint(-5, -1)
                                                    or randint(1, 5))
                falseSolutionNeeded = False

            falseSolutionText = largeFont.render(str(falseSolution), True,
                                                 black)
            solutionText = largeFont.render(str(solution), True, black)

            # determine where correct answer goes
            if (solutionPosNeeded):
                solutionRect = solutionText.get_rect()
                falseSolutionRect = falseSolutionText.get_rect()
                solPos = randint(0, 1)
                if (solPos == 0):
                    solutionRect.center = (int(180 * scale_x),
                                           int(325 * scale_y))
                    falseSolutionRect.center = (int(620 * scale_x),
                                                int(325 * scale_y))
                    solutionPosition = "left"
                else:
                    solutionRect.center = (int(620 * scale_x),
                                           int(325 * scale_y))
                    falseSolutionRect.center = (int(180 * scale_x),
                                                int(325 * scale_y))
                    solutionPosition = "right"
                solutionPosNeeded = False

            gameDisplay.blit(solutionText, solutionRect)
            gameDisplay.blit(falseSolutionText, falseSolutionRect)

            # generate score
            scoreText = font.render(str(score), True, white)
            scoreRect = scoreText.get_rect()
            scoreRect.center = (int(650 * scale_x), int(444 * scale_y))
            gameDisplay.blit(scoreText, scoreRect)

            # get user selection
            if (lean == "none") or (lean == "forward") or (lean == "back"):
                previousTime = time()

            if (time() - previousTime >=
                    selectionTime) or (GPIO.input(selectButton) == False):
                if (lean == "left"):
                    selection = "left"
                elif (lean == "right"):
                    selection = "right"
                answerGiven = True

                if (lean == "forward") or (lean == "back") or (lean == "none"):
                    answerGiven = False

                if (GPIO.input(selectButton) == False):
                    sleep(0.2)
            else:
                selection = "none"

            # determine if user is correct
            if (answerGiven):
                if (selection == solutionPosition):
                    score += 1
                else:
                    score -= 1
                if (score <= 0):
                    score = 0
                answerGiven = False
                previousTime = time()

                numbersNeeded = True
                falseSolutionNeeded = True
                solutionPosNeeded = True

            pygame.display.update()

        while (Shapes):
            if (i == 0):
                previousTime = time()
                i += 1
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                    pygame.quit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        running = False
                        pygame.quit()

            if (timerStarted == False):
                start_ticks = pygame.time.get_ticks()
                timerStarted = True

            # get direction of lean
            lean = rotationTest()

            # update background to highlight selection
            if (lean == "left"):
                gameDisplay.blit(game_bg_left, (0, 0))
            elif (lean == "right"):
                gameDisplay.blit(game_bg_right, (0, 0))
            else:
                gameDisplay.blit(game_bg, (0, 0))

            # get random numbers for question/solution
            if (shapeNeeded):
                shape1 = randint(0, len(shapes) - 1)
                shape2 = randint(0, len(shapes) - 1)
                while (shape1 == shape2):
                    shape2 = randint(0, len(shapes) - 1)

                shapeNeeded = False

            # generate countdown timer
            seconds = (pygame.time.get_ticks() - start_ticks) / 1000
            if (seconds <= timerLength):
                countdown = timerLength - seconds
            else:
                questionText = largeFont.render("Game Over!", True, black)
                solution = ""
                falseSolution = ""

                gameOver = True
                Shapes = False

                #math = False
            timerText = font.render(str(countdown), True, white)
            timerRect = timerText.get_rect()
            timerRect.center = (int(160 * scale_x), int(447 * scale_y))
            gameDisplay.blit(timerText, timerRect)

            # generate question text and solution based on difficulty if timer != 0
            if (countdown != 0):
                if (shapes[shape1][1][0]
                        == "a") or (shapes[shape1][1][0] == "e") or (
                            shapes[shape1][1][0]
                            == "i") or (shapes[shape1][1][0]
                                        == "o") or (shapes[shape1][1][0]
                                                    == "u"):
                    questionText = font.render(
                        "Which shape is an {}?".format(shapes[shape1][1]),
                        True, black)
                else:
                    questionText = font.render(
                        "Which shape is a {}?".format(shapes[shape1][1]), True,
                        black)
            # show question on screen
            questionRect = questionText.get_rect()
            questionRect.center = (WIDTH / 2, int(150 * scale_y))
            gameDisplay.blit(questionText, questionRect)

            # determine where correct answer goes
            if (solutionPosNeeded):
                solPos = randint(0, 1)
                if (solPos == 0):
                    solutionCoordinates = (int(125 * scale_x),
                                           int(275 * scale_y))
                    falseSolutionCoordinates = (int(565 * scale_x),
                                                int(275 * scale_y))
                    solutionPosition = "left"
                else:
                    solutionCoordinates = (int(565 * scale_x),
                                           int(275 * scale_y))
                    falseSolutionCoordinates = (int(125 * scale_x),
                                                int(275 * scale_y))
                    solutionPosition = "right"
                solutionPosNeeded = False

            gameDisplay.blit(shapes[shape1][0], solutionCoordinates)
            gameDisplay.blit(shapes[shape2][0], falseSolutionCoordinates)

            # generate score
            scoreText = font.render(str(score), True, white)
            scoreRect = scoreText.get_rect()
            scoreRect.center = (int(650 * scale_x), int(444 * scale_y))
            gameDisplay.blit(scoreText, scoreRect)

            # get user selection
            if (lean == "none") or (lean == "forward") or (lean == "back"):
                previousTime = time()

            if (time() - previousTime >= 2) or (GPIO.input(selectButton)
                                                == False):
                if (lean == "left"):
                    selection = "left"
                elif (lean == "right"):
                    selection = "right"
                answerGiven = True

                if (lean == "forward") or (lean == "back") or (lean == "none"):
                    answerGiven = False

                if (GPIO.input(selectButton) == False):
                    sleep(0.2)
            else:
                selection = "none"

            # determine if user is correct
            if (answerGiven):
                if (selection == solutionPosition):
                    score += 1
                else:
                    score -= 1
                if (score <= 0):
                    score = 0
                answerGiven = False
                previousTime = time()

                shapeNeeded = True
                falseSolutionNeeded = True
                solutionPosNeeded = True
                answersShown = False

            pygame.display.update()

        while (Colors):
            if (i == 0):
                previousTime = time()
                i += 1
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                    pygame.quit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        running = False
                        pygame.quit()

            if (timerStarted == False):
                start_ticks = pygame.time.get_ticks()
                timerStarted = True

            # get direction of lean
            lean = rotationTest()

            # update background to highlight selection
            if (lean == "left"):
                gameDisplay.blit(game_bg_left, (0, 0))
            elif (lean == "right"):
                gameDisplay.blit(game_bg_right, (0, 0))
            else:
                gameDisplay.blit(game_bg, (0, 0))

            # get random numbers for question/solution
            if (colorNeeded):
                color1 = randint(0, len(colors) - 1)
                color2 = randint(0, len(colors) - 1)
                while (color1 == color2):
                    color2 = randint(0, len(colors) - 1)

                colorNeeded = False

            # generate countdown timer
            seconds = (pygame.time.get_ticks() - start_ticks) / 1000
            if (seconds <= timerLength):
                countdown = timerLength - seconds
            else:
                gameOver = True
                Colors = False

            timerText = font.render(str(countdown), True, white)
            timerRect = timerText.get_rect()
            timerRect.center = (160 * scale_x, 447 * scale_y)
            gameDisplay.blit(timerText, timerRect)

            # generate question text and solution based on difficulty if timer != 0
            if (countdown != 0):
                questionText = font.render(
                    "Which color is {}?".format(colors[color1][1]), True,
                    black)

            # show question on screen
            questionRect = questionText.get_rect()
            questionRect.center = (WIDTH / 2, int(150 * scale_y))
            gameDisplay.blit(questionText, questionRect)

            # determine where correct answer goes
            if (solutionPosNeeded):
                solPos = randint(0, 1)
                if (solPos == 0):
                    solutionCoordinates = (int(125 * scale_x),
                                           int(275 * scale_y))
                    falseSolutionCoordinates = (int(565 * scale_x),
                                                int(275 * scale_y))
                    solutionPosition = "left"
                else:
                    solutionCoordinates = (int(565 * scale_x),
                                           int(275 * scale_y))
                    falseSolutionCoordinates = (int(125 * scale_x),
                                                int(275 * scale_y))
                    solutionPosition = "right"
                solutionPosNeeded = False

            gameDisplay.blit(colors[color1][0], solutionCoordinates)
            gameDisplay.blit(colors[color2][0], falseSolutionCoordinates)

            # generate score
            scoreText = font.render(str(score), True, white)
            scoreRect = scoreText.get_rect()
            scoreRect.center = (int(650 * scale_x), int(444 * scale_y))
            gameDisplay.blit(scoreText, scoreRect)

            # get user selection
            if (lean == "none") or (lean == "forward") or (lean == "back"):
                previousTime = time()

            if (time() - previousTime >= 2) or (GPIO.input(selectButton)
                                                == False):
                if (lean == "left"):
                    selection = "left"
                elif (lean == "right"):
                    selection = "right"
                answerGiven = True

                if (lean == "forward") or (lean == "back") or (lean == "none"):
                    answerGiven = False

                if (GPIO.input(selectButton) == False):
                    sleep(0.2)
            else:
                selection = "none"

            # determine if user is correct
            if (answerGiven):
                if (selection == solutionPosition):
                    score += 1
                else:
                    score -= 1
                if (score <= 0):
                    score = 0
                answerGiven = False
                previousTime = time()

                colorNeeded = True
                falseSolutionNeeded = True
                solutionPosNeeded = True
                answersShown = False

            pygame.display.update()

        while (Platformer):
            pygame.mixer.music.set_volume(0.5)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                    pygame.quit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        running = False
                        pygame.quit()

                    if (DEBUG):
                        if event.key == pygame.K_LEFT:
                            lean = "left"
                        elif event.key == pygame.K_RIGHT:
                            lean = "right"
                        elif event.key == pygame.K_UP:
                            lean = "forward"
                        elif event.key == pygame.K_DOWN:
                            lean = "back"
                        else:
                            lean = "none"
            if not DEBUG:
                lean = rotationTest()

            if (lean == "left"):
                player.go_left()
            elif (lean == "right"):
                player.go_right()
            else:
                player.stop()

            if not DEBUG:
                if (GPIO.input(selectButton) == False):
                    player.jump()
                    sleep(0.1)
            else:
                if (lean == "forward"):
                    player.jump()
                    sleep(0.1)
            # Update the player.
            active_sprite_list.update()

            # Update items in the level
            current_level.update()

            # If the player gets near the right side, shift the world left (-x)
            if player.rect.x >= 800:
                diff = player.rect.x - 800
                player.rect.x = 800
                current_level.shift_world(-diff)

            # If the player gets near the left side, shift the world right (+x)
            if player.rect.x <= 120:
                diff = 120 - player.rect.x
                player.rect.x = 120
                current_level.shift_world(diff)

            # If the player gets to the end of the level, go to the next level
            current_position = player.rect.x + current_level.world_shift
            if current_position < current_level.level_limit:
                player.rect.x = 120
                if current_level_no < len(level_list) - 1:
                    current_level_no += 1
                    current_level = level_list[current_level_no]
                    player.level = current_level

            # Code to draw
            current_level.draw(gameDisplay)
            active_sprite_list.draw(gameDisplay)

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

            # Update the screen with what we've drawn
            pygame.display.flip()

        while (gameOver):
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                    pygame.quit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        running = False
                        pygame.quit()

            gameDisplay.blit(GameOver_bg, (0, 0))
            GameOverText = largeFont.render("Game Over!", True, black)
            GameOverRect = GameOverText.get_rect()
            GameOverRect.center = (WIDTH / 2, int(150 * scale_y))
            gameDisplay.blit(GameOverText, GameOverRect)

            GameOverScoreText = largeFont.render(
                "Your score was {}.".format(score), True, black)
            GameOverScoreRect = GameOverScoreText.get_rect()
            GameOverScoreRect.center = (WIDTH / 2, int(325 * scale_y))
            gameDisplay.blit(GameOverScoreText, GameOverScoreRect)

            ContinueText = font.render("Press a button to continue...", True,
                                       white)
            ContinueRect = ContinueText.get_rect()
            ContinueRect.center = (WIDTH / 2, int(450 * scale_y))
            gameDisplay.blit(ContinueText, ContinueRect)

            if (GPIO.input(selectButton) == False):
                sleep(0.5)
                selection = "none"
                previousTime = time()
                gameOver = False
                mainMenu = True

            pygame.display.update()
        Platformer = False
        Colors = False
        Shapes = False
        Math = False
        mainMenu = True
    def game():
        # -------- Main Program Loop -----------
        # Create the player
        player = Player()

        # Create all the levels
        level_list = []
        level_list.append(levels.Level_01(player))
        level_list.append(levels.Level_02(player))
        level_list.append(levels.Level_03(player))
        level_list.append(levels.Level_04(player))

        # Set the current level
        current_level_no = 0
        current_level = level_list[current_level_no]

        active_sprite_list = pygame.sprite.Group()
        player.level = current_level

        player.rect.x = 340
        player.rect.y = constants.SCREEN_HEIGHT - player.rect.height
        active_sprite_list.add(player)
        done = False
        while not done:
            for event in pygame.event.get():  # User did something

                if event.type == pygame.QUIT:  # If user clicked close
                    done = True  # Flag that we are done so we exit this loop

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        done = True
                    if event.key == pygame.K_LEFT:
                        player.go_left()
                    if event.key == pygame.K_RIGHT:
                        player.go_right()
                    if event.key == pygame.K_SPACE:
                        player.jump()
                    if event.key == pygame.K_UP:
                        player.jump()

                if event.type == pygame.KEYUP:
                    if event.key == pygame.K_LEFT and player.change_x < 0:
                        player.stop()
                    if event.key == pygame.K_RIGHT and player.change_x > 0:
                        player.stop()

            # Update the player.
            active_sprite_list.update()

            # Update items in the level
            current_level.update()

            # If the player gets near the right side, shift the world left (-x)
            if player.rect.x >= 500:
                diff = player.rect.x - 500
                player.rect.x = 500
                current_level.shift_world(-diff)

            # If the player gets near the left side, shift the world right (+x)
            if player.rect.x <= 120:
                diff = 120 - player.rect.x
                player.rect.x = 120
                current_level.shift_world(diff)

            # If the player gets to the end of the level, go to the next level
            current_position = player.rect.x + current_level.world_shift
            if current_position < current_level.level_limit:
                player.rect.x = 120
                if current_level_no < len(level_list) - 1:
                    current_level_no += 1
                    current_level = level_list[current_level_no]
                    player.level = current_level
                else:
                    done = True

            # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT

            current_level.draw(screen)
            active_sprite_list.draw(screen)

            # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

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

            # Go ahead and update the screen with what we've drawn.
            draw_text(screen, "Treats found: " + str(player.score), 40,
                      constants.SCREEN_WIDTH / 2, 10, constants.WHITE)

            pygame.display.flip()

        # Be IDLE friendly. If you forget this line, the program will 'hang'
        # on exit.
        end_screen(player.score)
Пример #7
0
def main():
    """ Main Program """
    pygame.init()

    # Set the height and width of the screen
    size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT]
    screen = pygame.display.set_mode(size)

    pygame.display.set_caption("MEGA MAN θ")

    # Create the player
    player = Player()

    # Create all the levels
    level_list = []
    level_list.append(levels.Level_01(player))
    level_list.append(levels.Level_02(player))
    level_list.append(levels.Level_03(player))

    # Set the current level
    current_level_no = 0
    current_level = level_list[current_level_no]

    active_sprite_list = pygame.sprite.Group()
    player.level = current_level

    player.rect.x = 340
    player.rect.y = 15
    #constants.SCREEN_HEIGHT - player.rect.height
    active_sprite_list.add(player)

    #Loop until the user clicks the close button.
    done = False

    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()

    # -------- Main Program Loop -----------
    while not done:
        for event in pygame.event.get():  # User did something
            if event.type == pygame.QUIT:  # If user clicked close
                done = True  # Flag that we are done so we exit this loop

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    player.go_left()
                if event.key == pygame.K_RIGHT:
                    player.go_right()
                if event.key == pygame.K_UP:
                    player.jump()
                #if event.key == pygame.K_SPACE:
                #    player.shoot()
                #if event.key == pygame.K_P:
                #    player.pause()

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT and player.change_x < 0:
                    player.stop()
                if event.key == pygame.K_RIGHT and player.change_x > 0:
                    player.stop()
                #if event.key == pygame.K_SPACE:
                #    player.menu()

        # Update the player.
        active_sprite_list.update()

        # Update items in the level
        current_level.update()

        # If the player gets near the right side, shift the world left (-x)
        if player.rect.x >= 500:
            diff = player.rect.x - 500
            player.rect.x = 500
            current_level.shift_world(-diff)

        # If the player gets near the left side, shift the world right (+x)
        if player.rect.x <= 120:
            diff = 120 - player.rect.x
            player.rect.x = 120
            current_level.shift_world(diff)

        #If the player gets near the top, shift the world up (+y)
        if player.rect.y <= 100:
            diff = 120 - player.rect.y
            player.rect.y = 120
            current_level.shift_world(diff)

        # If the player gets to the end of the level, go to the next level
        current_position = player.rect.x + current_level.world_shift
        if current_position < current_level.level_limit:
            player.rect.x = 120
            if current_level_no < len(level_list) - 1:
                current_level_no += 1
                current_level = level_list[current_level_no]
                player.level = current_level

        current_level.draw(screen)
        active_sprite_list.draw(screen)

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

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

    # Be IDLE friendly. If you forget this line, the program will 'hang'
    # on exit.
    pygame.quit()
Пример #8
0
def main():
    """ Main Program """
    pygame.init()

    # Set the height and width of the screen
    size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT]
    screen = pygame.display.set_mode(size)
    bounds = screen.get_rect()
    pygame.display.set_caption("Super Alien Assault!")

    # Load the sound mixer:
    pygame.mixer.pre_init(44100, -16, 2, 2048)
    # This is supposed to help stop sound lag

    # Create the player
    player = Player(bounds.center, bounds)
    player_grp = GroupSingle(player)

    # Create an enemy
    enemies = pygame.sprite.Group()

    # Create all the levels
    lindex = random.randrange(3, 9)

    level_list = []
    level_list.append(levels.Level_01(player))
    level_list.append(levels.Level_02(player))
    level_list.append(levels.Level_03(player))
    for i in range(lindex):
        level_list.append(levels.Level_01(player))
        level_list.append(levels.Level_02(player))
        level_list.append(levels.Level_03(player))

    # Initialize variables
    score = 0
    spawn_counter = 0
    tween_diff = 1

    # Select the font to use
    font = pygame.font.SysFont("calibri", 48)

    # Set the current level
    current_level_no = 0
    current_level = level_list[current_level_no]

    # List of each block
    block_list = pygame.sprite.Group()

    # Set current level for player and inital x,y position
    player.level = current_level
    player.rect.x = 340
    player.rect.y = 200

    # Loop until the user clicks the close button.
    done = False

    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()

    # Play "Hot Nights" by Beardmont / Three Chain Links
    # Available under Creative Commons attribution license from:
    # https://soundcloud.com/beardmont
    pygame.mixer.music.load('HotNights.ogg')
    pygame.mixer.music.set_endevent(pygame.constants.USEREVENT)
    pygame.mixer.music.play()

    # -------- Main Program Loop -----------
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

            elif event.type == pygame.constants.USEREVENT:
                # This event is triggered when the song stops playing.
                #
                # Next, play "Happiest Days" by Beardmont / Three Chain Links
                # Available under Creative Commons attribution license from:
                # https://soundcloud.com/beardmont
                pygame.mixer.music.load('HappiestDays.ogg')
                pygame.mixer.music.play()

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    done = True
                if event.key == pygame.K_q:
                    done = True
                if event.key == pygame.K_LEFT:
                    player.go_left()
                if event.key == pygame.K_RIGHT:
                    player.go_right()
                if event.key == pygame.K_UP:
                    player.jump()
                if event.key == pygame.K_SPACE:
                    player.shoot()
                if event.key == pygame.K_r and not player.alive():
                    main()

            elif event.type == pygame.KEYUP:

                if event.key == pygame.K_LEFT and player.change_x < 0:
                    player.stop()
                if event.key == pygame.K_RIGHT and player.change_x > 0:
                    player.stop()

        # Update items in the level
        current_level.update()
        player_grp.update()
        player.bullets.update()
        player.bulletcasings.update()
        enemies.update()

        # Messing around with easing the enemy spawn counter
        # They should gradually trickle in at first and then build
        # to a flood of enemies then recede kind of like a tide
        spawn_counter += (101 - spawn_counter) * .1
        if spawn_counter >= 100:
            n = random.randrange(3)
            for i in range(n):
                x = random.randint(900, 1000)
                y = random.randint(100, 520)
                enemy = Enemy((x, y))
                enemies.add(enemy)
            spawn_counter = 0

        # Collision between player and enemies results in player death
        groupcollide(player_grp, enemies, True, False)

        # Add 1 point to score for every enemy the player kills
        for enemy in groupcollide(enemies, player.bullets, True, True):
            if player.alive():
                score += 1

        # If the player gets near the right side, shift the world left (-x)
        if player.rect.x >= 310:
            diff = player.rect.x - 310
            # add some tweening/easing for momentum
            tween_diff += (diff - tween_diff) * .1
            player.rect.x = 310
            current_level.shift_world(int(-tween_diff))
            # also adjust enemies and bulletcasings by the world shift
            for enemy in enemies:
                enemy.rect.x += (int(-tween_diff))
            for bulletcasing in player.bulletcasings:
                bulletcasing.rect.x += (int(-tween_diff))

        # If the player gets near the left side, shift the world right (+x)
        if player.rect.x <= 290:
            diff = 290 - player.rect.x
            # add some tweening/easing for momentum
            tween_diff += (diff - tween_diff) * .1
            player.rect.x = 290
            current_level.shift_world(int(tween_diff))
            # also adjust enemies and bulletcasings by the world shift
            for enemy in enemies:
                enemy.rect.x += (int(tween_diff))
            for bulletcasing in player.bulletcasings:
                bulletcasing.rect.x += (int(tween_diff))

        # If the player gets to the end of the level, go to the next level
        current_position = player.rect.x + current_level.world_shift
        if current_position < current_level.level_limit:
            player.rect.x = 120
            if current_level_no < len(level_list) - 1:
                current_level_no += 1
                current_level = level_list[current_level_no]
                player.level = current_level

        # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
        current_level.draw(screen)
        player_grp.draw(screen)
        player.bullets.draw(screen)
        player.bulletcasings.draw(screen)
        enemies.draw(screen)

        # Blit the current score
        score_text = font.render("Score: %08d" % score, True, constants.PEACH)
        screen.blit(score_text, (5, 5))

        # If player dies, blit the respawn menu
        if not player.alive():
            gameover = font.render("Press R to Respawn or ESC to Quit", True,
                                   constants.PEACH)
            rect = gameover.get_rect()
            rect.center = screen.get_rect().center
            screen.blit(gameover, rect)

        # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT

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

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

    # Be IDLE friendly. If you forget this line, the program will 'hang'
    # on exit.
    pygame.quit()