Exemple #1
0
def startGame(gameState=None):
    word = getWordFromFile("wordsList.txt")
    highScoreData = getHighScoreFromFile("scores.txt")
    if gameState == None:
        newGameState = GameState(word, highScoreData[0], int(highScoreData[1]))
    else:
        newGameState = GameState(word, highScoreData[0], int(highScoreData[1]),
                                 gameState.winsInARow)
    print("Let's play the Hangman game !\n")
    print("High score : ", newGameState.highScore)
    print("Best Player :", newGameState.highScorePlayer)
    print("Your Score :", newGameState.winsInARow)

    newTry(newGameState)
def startGame(mainWindow=None, prevGameState=None):
    if mainWindow == None:
        mainWindow = MainWindow()

    word = getWordFromFile("wordsList.txt")
    highScoreData = getHighScoreFromFile("scores.txt")
    if prevGameState == None:
        gameState = GameState(word, highScoreData[0], int(highScoreData[1]))
    else:
        gameState = GameState(word, highScoreData[0], int(
            highScoreData[1]), prevGameState.winsInARow)

    mainWindow.tryButton.configure(
        command=lambda: tryLetter(mainWindow, gameState))

    updateWidgets(mainWindow, gameState)

    mainWindow.bind_all(
        '<Return>', lambda event: tryLetter(mainWindow, gameState))
    mainWindow.mainloop()
Exemple #3
0
def end_screen():
    # Keeps track of all sprites to be updated every frame
    allsprites = pygame.sprite.Group()
    # Song to be used in game. Only one can be used.
    song = song_library.example_song_short  # Short random song for debugging
    # song = song_library.example_song_long  # Ode To Joy

    # Create game_state instance, this holds all required game info
    game_state = GameState(allsprites, song)

    loop = True

    replayButton = Button(500, 500, 200, 45, ' Replay', game_state.restart,
                          song.get_font_filename(), allsprites, game_state)
    mainMenuButton = Button(650, 500, 200, 45,
                            ' Main menu', game_state.menu_start,
                            song.get_font_filename(), allsprites, game_state)

    top5 = score.get_top5_high_score()

    while loop:

        text_font.render_to(screen, (590, 200), "Highscores:", (153, 204, 255))
        eventlist = pygame.event.get()
        for event in eventlist:
            # Checks if a mouse is clicked
            if event.type == pygame.MOUSEBUTTONDOWN:
                replayButton.check_click()
                mainMenuButton.check_click()
                quitButton.check_click()

    # This calls the update() function on all sprites
    allsprites.update()

    # Draw Everything
    screen.blit(game_state.get_background(),
                (0, 0))  # First draw a new background
    allsprites.draw(screen)  # Next draw all updated sprites
    pygame.display.update()  # Finally render everything to the display
def main():
    # Initialize pygame
    pygame.init()
    # Set screen size. Don't change this unless you know what you are doing!
    screen = pygame.display.set_mode((1280, 720))
    # Set the window title
    pygame.display.set_caption("Sweden - Interaction Hero")

    # Keeps track of all sprites to be updated every frame
    allsprites = pygame.sprite.Group()

    # Song to be used in game. Only one can be used.
    #song = song_library.example_song_short  # Short random song for debugging
    #song = song_library.example_song_long  # Ode To Joy
    song = song_library.du_gamla_du_fria

    # Create game_state instance, this holds all required game info
    game_state = GameState(allsprites, song)

    # Checks if the program is running on a Raspberry Pi
    is_running_on_rpi = utils.is_running_on_rpi()
    if is_running_on_rpi:
        # Below are some pin input numbers, feel free to change them. However,
        # !!! ALWAYS READ THE PIN DOCUMENTATION CAREFULLY !!!
        # Pay special attention to the difference between GPIO pin numbers and BOARD pin numbers
        # For example GPIO17 is addressed 17 rather than 11 (See pin numbering diagram.)
        # https://gpiozero.readthedocs.io/en/stable/recipes.html#pin-numbering
        gpio_pin_numbers = [22, 23, 24, 27]  # Max 4 pins
        gpio_buttons = init_rpi_buttons(gpio_pin_numbers)
        game_state.add_gpio_pins(gpio_pin_numbers)

    # Prepare game objects
    clock = pygame.time.Clock()
    startButton = Button(570, 200, 140, 40,
                         ' Börja', game_state.restart, "menu",
                         song.get_font_filename(), allsprites, game_state)
    quitButton = Button(570, 300, 140, 40, ' Sluta', quit, "menu",
                        song.get_font_filename(), allsprites, game_state)
    scoreButton = Button(570, 250, 140, 40, ' Score',
                         game_state.open_score_menu, "menu",
                         song.get_font_filename(), allsprites, game_state)
    scoreBackButton = Button(570, 350, 140, 40, ' Bakåt',
                             game_state.open_menu, "score",
                             song.get_font_filename(), allsprites, game_state)
    highscoreLabel = Label("", 100, 220, True, 36, song.get_font_filename(),
                           (255, 255, 255), "score", allsprites, game_state)

    # Main loop
    going = True
    while going:

        # Update the clock, argument is max fps
        clock.tick(60)

        # Every 'tick' or programcycle the gamestate update() is called
        game_state.update()

        # Get all events from the last cycle and store them as variable
        # This is stored as a variable because pygame.even.get() empties this list
        eventlist = pygame.event.get()

        # Check if there are any global quit events
        for event in eventlist:
            # If yes, the game loop won't start again
            if event.type == pygame.QUIT:
                going = False
            elif event.type == pygame.KEYDOWN and event.unicode == pygame.K_ESCAPE:
                going = False

        # This runs before the user starts the game
        if game_state.state == 'prestart':
            for event in eventlist:
                # Checks if a mouse is clicked
                if event.type == pygame.MOUSEBUTTONDOWN:
                    startButton.check_click()
                    quitButton.check_click()
                    scoreButton.check_click()

        elif game_state.state == 'score':
            highscoreLabel.text = "Highscore: " + str(
                game_state.scoreHandler.get_high_score())
            for event in eventlist:
                if event.type == pygame.MOUSEBUTTONDOWN:
                    scoreBackButton.check_click()

        # This runs when the users starts a game
        elif game_state.state == 'playing':
            # Loop through all potential hitboxes
            for hitbox in game_state.hitboxes:
                # Every hitbox needs to check all events
                for event in eventlist:
                    if event.type == pygame.KEYDOWN and event.unicode == hitbox.event_key:
                        game_state.check_for_hit(hitbox)
                    elif event.type == pygame.KEYUP:
                        hitbox.unpunch()
                    elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                        game_state.state = 'prestart'
                        hitbox.destroy_all_notes()

                # When on RPi also check for GPIO input
                if is_running_on_rpi:
                    for button in gpio_buttons:
                        # When a buttons is pressed in this loop and wasn't pressed in the last loop
                        if button.is_pressed(
                        ) and button.gpio_key is hitbox.gpio_event_key and button.is_available(
                        ):
                            button.use(
                            )  # Set the button as unavailable for the next loop
                            game_state.check_for_hit(hitbox)
                        # When a button was not pressed in this loop
                        elif not button.is_pressed():
                            button.wake()  # Set the button as available again
                            hitbox.unpunch()

        # This calls the update() function on all sprites
        allsprites.update()

        # Draw Everything
        screen.blit(game_state.get_background(),
                    (0, 0))  # First draw a new background
        allsprites.draw(screen)  # Next draw all updated sprites
        pygame.display.update()  # Finally render everything to the display
Exemple #5
0
def main():
    # Initialize pygame
    pygame.init()
    # Set screen size. Don't change this unless you know what you are doing!
    screen = pygame.display.set_mode((1280, 720))
    # Set the window title
    pygame.display.set_caption("IAT Challengeweek: Interaction Hero | China")

    # Keeps track of all sprites to be updated every frame
    allsprites = pygame.sprite.Group()

    text_font = pygame.freetype.Font("data/RobotoMono-VariableFont_wght.ttf",
                                     34)
    # Song to be used in game. Only one can be used.
    song = song_library.example_song_short  # Short random song for debugging
    # song = song_library.example_song_long  # Ode To Joy

    # Create game_state instance, this holds all required game info
    game_state = GameState(allsprites, song)

    # Checks if the program is running on a Raspberry Pi
    is_running_on_rpi = utils.is_running_on_rpi()
    if is_running_on_rpi:
        # Below are some pin input numbers, feel free to change them. However,
        # !!! ALWAYS READ THE PIN DOCUMENTATION CAREFULLY !!!
        # Pay special attention to the difference between GPIO pin numbers and BOARD pin numbers
        # For example GPIO17 is addressed 17 rather than 11 (See pin numbering diagram.)
        # https://gpiozero.readthedocs.io/en/stable/recipes.html#pin-numbering
        gpio_pin_numbers = [2, 3, 4, 17]  # Max 4 pins
        gpio_buttons = init_rpi_buttons(gpio_pin_numbers)
        game_state.add_gpio_pins(gpio_pin_numbers)

    # Prepare game objects
    clock = pygame.time.Clock()
    startButton = Button(500, 300, 140, 40, ' Start', game_state.restart,
                         song.get_font_filename(), allsprites, game_state)
    quitButton = Button(500, 350, 140, 40, ' Quit', quit,
                        song.get_font_filename(), allsprites, game_state)

    # easyButton = Button(450, 250, 140, 40, ' Easy', select_difficulty, song.get_font_filename(), allsprites, game_state)
    # normalButton = Button(600, 250, 140, 40, ' Normal', select_difficulty, song.get_font_filename(), allsprites, game_state)
    # hardButton = Button(750, 250, 140, 40, ' Hard', select_difficulty, song.get_font_filename(), allsprites, game_state)

    # Main loop
    going = True
    while going:

        # Update the clock, argument is max fps
        clock.tick(60)

        # Every 'tick' or programcycle the gamestate update() is called
        game_state.update()

        # Get all events from the last cycle and store them as variable
        # This is stored as a variable because pygame.even.get() empties this list
        eventlist = pygame.event.get()

        # Check if there are any global quit events
        for event in eventlist:
            # If yes, the game loop won't start again
            if event.type == pygame.QUIT:
                going = False
            elif event.type == pygame.KEYDOWN and event.unicode == pygame.K_ESCAPE:
                going = False

        # This runs before the user starts the game
        if game_state.state == 'prestart':

            for event in eventlist:
                # Checks if a mouse is clicked
                if event.type == pygame.MOUSEBUTTONDOWN:
                    startButton.check_click()
                    quitButton.check_click()
                    # Difficulty buttons
                    # easyButton.check_click()
                    # normalButton.check_click()
                    # hardButton.check_click()

        # This runs when the users starts a game
        elif game_state.state == 'playing':
            stopButton = Button(100, 100, 140, 40,
                                ' Stop', game_state.menu_start,
                                song.get_font_filename(), allsprites,
                                game_state)
            # Loop through all potential hitboxes
            for hitbox in game_state.hitboxes:
                # Every hitbox needs to check all events
                for event in eventlist:
                    if event.type == pygame.KEYDOWN and event.unicode == hitbox.event_key:
                        game_state.check_for_hit(hitbox)
                    elif event.type == pygame.KEYUP:
                        hitbox.unpunch()
                    elif event.type == pygame.MOUSEBUTTONDOWN:
                        stopButton.check_click()

                # When on RPi also check for GPIO input
                if is_running_on_rpi:
                    for button in gpio_buttons:
                        # When a buttons is pressed in this loop and wasn't pressed in the last loop
                        if button.is_pressed(
                        ) and button.gpio_key is hitbox.gpio_event_key and button.is_available(
                        ):
                            button.use(
                            )  # Set the button as unavailable for the next loop
                            game_state.check_for_hit(hitbox)
                        # When a button was not pressed in this loop
                        elif not button.is_pressed():
                            button.wake()  # Set the button as available again
                            hitbox.unpunch()

        # elif game_state.state == 'end_game':
        #     going = False
        #     end_screen()

        # End state
        elif game_state.state == 'end_game':
            replayButton = Button(500, 500, 200, 45,
                                  ' Replay', game_state.restart,
                                  song.get_font_filename(), allsprites,
                                  game_state)
            mainMenuButton = Button(650, 500, 200, 45, ' Main menu',
                                    game_state.menu_start,
                                    song.get_font_filename(), allsprites,
                                    game_state)

            top5 = score.get_top5_high_score()
            text_font.render_to(screen, (500, 200), "top 5 Score:", (0, 0, 0))

            height = 250
            for count, top in enumerate(top5):
                h = height + 30 * count
                text_font.render_to(screen, (500, h), str(top), (0, 0, 0))

            # text_font.render_to(screen, (500, 250), "ss", (153, 204, 255))
            # [90, 70, 65, 60, 60]

            for event in eventlist:
                # Checks if a mouse is clicked
                if event.type == pygame.MOUSEBUTTONDOWN:
                    replayButton.check_click()
                    mainMenuButton.check_click()
                    quitButton.check_click()

        # text_font.render_to(screen, (40, 350), "Hello World!", (0, 0, 0))

        # This calls the update() function on all sprites
        allsprites.update()
        pygame.display.flip()
        # Draw Everything
        screen.blit(game_state.get_background(),
                    (0, 0))  # First draw a new background
        allsprites.draw(screen)  # Next draw all updated sprites
        pygame.display.update()  # Finally render everything to the display
def main():
    clock = pygame.time.Clock()
    bgY = 0
    bgY2 = -BG.get_height()
    main_font = pygame.font.SysFont("roboto", 30, bold=False, italic=False)
    lost_font = pygame.font.SysFont("roboto", 70, bold=True, italic=False)

    # init game state
    gameState = GameState([], [])
    player = Player(WIDTH / 2, HEIGHT - 50)

    def enemy_shoot(enemy):
        if enemy.y > 0:
            rand = random.randrange(0, 100)
            if enemy.cooldown < enemy.shoot_timer:
                enemy.cooldown += 1
            if enemy.cooldown >= enemy.shoot_timer and rand > 95:
                enemy.cooldown = 0
                laser = Laser(enemy.x + 10,
                              enemy.y + enemy.ship_img.get_height() - 10,
                              ENEMY_LASER_IMG,
                              enemy.laser_vel + enemy.ship_vel, 1,
                              enemy.damage)
                gameState.lasers.append(laser)

    def stageHandler():
        if len(gameState.enemies) == 0:
            gameState.level += 1
            gameState.wave_length += 5
            enemy_dic = (Enemy1, Enemy2, Enemy3)
            for i in range(gameState.wave_length):
                enemy = random.choice(enemy_dic)
                gameState.enemies.append(
                    enemy(random.randrange(100, WIDTH - 100),
                          random.randrange(-1500, -100)))
        else:
            # handles enemies
            for enemy in gameState.enemies:
                enemy.move()
                enemy_shoot(enemy)
                if (enemy.y >= HEIGHT
                        or enemy.y > 0 and player.collide(enemy)):
                    gameState.enemies.remove(enemy)
                    enemy.death()
                    gameState.hit()

        # handles lasers
        if len(gameState.lasers):
            for laser in gameState.lasers:
                if laser.off_screen(HEIGHT):
                    gameState.lasers.remove(laser)
                elif player.collide(laser):
                    player.hit()
                    gameState.hit()
                    gameState.lasers.remove(laser)
                else:
                    move = True
                    for obj in (gameState.enemies):
                        if (laser.collision(obj)):
                            obj.Damage(laser.damage)
                            if obj.health <= 0:
                                gameState.enemies.remove(obj)
                            gameState.lasers.remove(laser)
                            move = False
                            continue
                    if (laser.collision(player)):
                        player.Damage(laser.damage)
                        gameState.lasers.remove(laser)
                        move = False
                        continue
                    if move:
                        laser.moveLaser()
        player.shot_counter()

    def deathHandler():
        # handles lost game timer
        if gameState.lives == 0:
            if (gameState.lost_counter == 0):
                player.death()
            gameState.lost = True
            gameState.lost_counter += 1

        # checks if lost the game
        if gameState.lost:
            if gameState.lost_counter > gameState.FPS * 3:
                gameState.run = False
            else:
                return True

    def reRender():
        # background
        WIN.blit(BG, (0, int(bgY)))
        WIN.blit(BG, (0, int(bgY2)))

        # enemies
        for enemy in gameState.enemies:
            enemy.draw(WIN)

        # player
        player.draw(WIN)

        # lasers
        for laser in gameState.lasers:
            laser.draw(WIN)

        # render lost message
        if gameState.lost:
            lost_message = lost_font.render("You Lost! Better Luck Next Time",
                                            1, (255, 255, 255))
            WIN.blit(lost_message,
                     (int(WIDTH / 2 - lost_message.get_width() / 2),
                      int(HEIGHT / 2 - lost_message.get_height() / 2)))

        # draw text
        level_label = main_font.render(f"Level: {gameState.level}", 1,
                                       (255, 255, 255))
        enemies_left = main_font.render(
            f"Enemies Left: {len(gameState.enemies)}", 1, (255, 255, 255))

        # render lives
        for i in range(gameState.lives):
            WIN.blit(PLAYER_LIFE_IMG,
                     (10 + (i * PLAYER_LIFE_IMG.get_width()) + 5, 10))

        WIN.blit(level_label, (WIDTH - level_label.get_width() - 10, 10))
        WIN.blit(enemies_left, (WIDTH - enemies_left.get_width() - 10,
                                20 + level_label.get_height()))
        pygame.display.update()

    while gameState.run:

        clock.tick(gameState.FPS)
        reRender()

        # handles death
        if (deathHandler()):
            continue

        # handle background repetition
        bgY += 0.8
        bgY2 += 0.8
        if bgY > BG.get_height():
            bgY = -BG.get_height()
        if bgY2 > BG.get_height():
            bgY2 = -BG.get_height()

        stageHandler()

        # handles pygame events
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gameState.run = False

        # track movment
        player.controles(WIDTH, HEIGHT, gameState.lasers)
"""
main.py

entry point for the Space Invaders Game

17/12/20 by Loïc (Pyrrha) TOCQUET and MALOSSE Alice

https://github.com/lTocquetCPE/Space-Invaders-for-CPE-Lyon-CSDEV-TP03-
"""
from tkinter import Tk, Label, Button, Canvas

from classes.MainWindow import MainWindow
from classes.Sprite import Sprite
from classes.GameState import GameState
from classes.Alien import Alien
from funcs.gameLoop import gameLoop


gameState = GameState()
mainWindow = MainWindow(gameState)

gameState.canon.sprite.setSpriteScale(1)
gameLoop(mainWindow, gameState)


mainWindow.manageEvent(gameState)
mainWindow.mainloop()