def main(): # Main Program pygame.init() # Define altura, largura e posição inicial da janela size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT] screen = pygame.display.set_mode(size) os.environ["SDL_VIDEO_WINDOW_POS"] = '200,50' screen = pygame.display.set_mode((1, 1)) # Define ícone e label da janela icon = pygame.image.load("images/triforceicon.png") pygame.display.set_caption("The Legend Of Souls") pygame.display.set_icon(icon) # Esconde o cursor do mouse pygame.mouse.set_visible(0) # Cria o player player1 = player.Player() # Cria os inimigos boss1 = boss.Boss() # Cria todos os levels level_list = [] level_list.append(levels.Level_01(player1, boss1)) level_list.append(levels.Level_02(player1, boss1)) # Define o level atual current_level_no = 0 current_level = level_list[current_level_no] active_sprite_list = pygame.sprite.Group() player1.level = current_level boss1.level = current_level # Define posição inicial do player player1.rect.x = 150 player1.rect.y = constants.SCREEN_HEIGHT - player1.rect.height - 12 active_sprite_list.add(player1) # Define posição inicial do enemy boss1.rect.x = 550 boss1.rect.y = constants.SCREEN_HEIGHT - boss1.rect.height - 32 active_sprite_list.add(boss1) #Loop até o usuário fechar o jogo ingame = True # Controla quão rápido a janela atualiza clock = pygame.time.Clock() # Mostra a tela de início levels.start_screen() # -------- Main Program Loop ----------- while ingame: for event in pygame.event.get(): pressed = pygame.key.get_pressed() # Fecha a janela se o usuário clicar em fechar if event.type == pygame.QUIT: ingame = False if event.type == pygame.KEYDOWN: # Fecha a janela se o usuário pressionar ALT+F4 if ((pressed[pygame.K_LALT] and pressed[pygame.K_F4]) or (pressed[pygame.K_RALT] and pressed[pygame.K_F4])): ingame = False # Move o player para a esquerda if event.key == pygame.K_a: player1.go_left() if event.key == pygame.K_LEFT: boss1.go_left() # Move o player para a direita if event.key == pygame.K_d: player1.go_right() if event.key == pygame.K_RIGHT: boss1.go_right() # Faz o player pular if event.key == pygame.K_w: player1.jump() if event.key == pygame.K_UP: boss1.jump() # Faz o player recuperar vida if event.key == pygame.K_e: player1.use_estus() # Calcula o dano recebido pelo player if event.key == pygame.K_q: player1.calc_damage(40, player1.defending) if event.key == pygame.K_p: boss1.calc_damage(200) # Calcula a stamina gasta pelo player if event.key == pygame.K_r: player1.calc_stamina(15) # Regenera a stamina gasta pelo player if event.key == pygame.K_f: pygame.time.set_timer(pygame.USEREVENT+1, 5) # Coloca o player em posição de defesa if event.key == pygame.K_z: player1.defending = True player1.defend() # Calcula a regeneração de stamina do player if event.type == pygame.USEREVENT+1: player1.stamina_regen() if event.type == pygame.KEYUP: # Para o movimento do player if event.key == pygame.K_a and player1.change_x < 0: player1.stop() if event.key == pygame.K_LEFT and boss1.change_x < 0: boss1.stop() if event.key == pygame.K_d and player1.change_x > 0: player1.stop() if event.key == pygame.K_RIGHT and boss1.change_x > 0: boss1.stop() # Para a regeneração de stamina if event.key == pygame.K_f: pygame.time.set_timer(pygame.USEREVENT+1, 0) # Tira o player da posição de defesa if event.key == pygame.K_z: player1.defending = False # Atualiza o player active_sprite_list.update() # Atualiza os itens no level current_level.update() # Se o player chegar perto do lado direito, muda o world para a esquerda (-x) if player1.rect.right >= 500: diff = player1.rect.right - 500 player1.rect.right = 500 current_level.shift_world(-diff) # Se o player chegar perto do lado esquerdo, muda o world para a direita (+x) if player1.rect.left <= 120: diff = 120 - player1.rect.left player1.rect.left = 120 current_level.shift_world(diff) # Se o player chegar ao fim do level, vai para o próximo level current_position = player1.rect.x + current_level.world_shift if (current_position < current_level.level_limit) and current_level_no != 0: player1.rect.x = 120 if current_level_no < len(level_list)-1: current_level_no += 1 current_level = level_list[current_level_no] player1.level = current_level # Todo código de desenhar current_level.draw(screen) active_sprite_list.draw(screen) player.player_hud(screen, player1.health, player1.stamina, player1.estus_rn) boss.boss_hud(screen, boss1.health) # Limita os frames por segundo clock.tick(constants.FPS) # Atualiza a janela com o que foi desenhado pygame.display.update() pygame.quit() #Termina o jogo
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()
def main(): pygame.init() # set dimensions size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT] screen = pygame.display.set_mode(size) pygame.display.set_caption('Arcade-Platformer') # create the player player = Player() # create levels level_list = [] level_list.append(levels.Level_01(player)) level_list.append(levels.Level_02(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 user clocks the close button done = False #clock clock = pygame.time.Clock() # ----- Main Program Loop ------- while not done: for event in pygame.event.get(): # user did something if event.type == pygame.QUIT: done = True 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.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 current level current_level.update() # If the player gets near the right side shift the world left if player.rect.right >= 500: diff = player.rect.right - 500 player.rect.right = 500 current_level.shift_world(-diff) # if player gets near the left side shift the world right if player.rect.left <= 120: diff = 120 - player.rect.left player.rect.left = 120 current_level.shift_world(diff) # If player gets to end of 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) # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT #limit to 60 frames per second clock.tick(60) # update screen pygame.display.flip() # IDLE friendly to help end program when finished pygame.quit()
def main(): """ Main Program """ pygame.mixer.pre_init(44100, -16, 2, 2048) # setup mixer to avoid sound lag pygame.init() try: pygame.mixer.music.load( os.path.join('data', 'KnifeParty_PowerGlove.wav')) #load music except: raise (UserWarning, "could not load or play sound files in 'data' folder :-(") pygame.mixer.music.play(-1) # 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("Game Over.") # Set Icon icon = pygame.image.load("spaceIcon.png") pygame.display.set_icon(icon) pygame.mouse.set_visible(0) # 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)) # 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() # -------- 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_SPACE: player.jump() if event.key == pygame.K_ESCAPE: done = True 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 = 130 if current_level_no < len(level_list) - 1: current_level_no += 1 current_level = level_list[current_level_no] player.level = current_level # If the player gets to the left side, go to the previous level # if current_level_no > 0 and current_position: # 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) # 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()
def load_level(player,current_level_no): pygame.init() # Set the height and width of the screen size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT] screen = pygame.display.set_mode(size) if constants.FULLSCREEN: screen = pygame.display.set_mode(size,pygame.FULLSCREEN) pygame.display.set_caption("This game is so cool OMG :O (level "+str(current_level_no)+")") # 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)) # Set the current level 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.hitbox_rect.height player.set_hitbox() active_sprite_list.add(player) player.stop() #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_ESCAPE: done = True if event.key == pygame.K_LEFT or event.key == pygame.K_a: player.go_left() if event.key == pygame.K_RIGHT or event.key == pygame.K_d: player.go_right() if event.key == pygame.K_UP or event.key == pygame.K_SPACE: player.jump() if event.type == pygame.KEYUP: if (event.key == pygame.K_LEFT or event.key == pygame.K_a) and player.change_x < 0: player.stop() if (event.key == pygame.K_RIGHT or event.key == pygame.K_d) 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.hitbox.rect.x >= (constants.SCREEN_WIDTH-400) and not current_level.is_end_level(): diff = player.hitbox.rect.x - (constants.SCREEN_WIDTH-400) player.hitbox.rect.x = (constants.SCREEN_WIDTH-400) current_level.shift_world(-diff) # If the player gets near the left side, shift the world right (+x) if player.hitbox.rect.x <= 300 and not current_level.is_begin_level(): diff = 300 - player.hitbox.rect.x player.hitbox.rect.x = 300 current_level.shift_world(diff) # If the player gets to the end of the level, go to the next level #current_position = player.hitbox.rect.x + current_level.world_shift #if current_position < current_level.level_limit: if player.hitbox.rect.x > constants.SCREEN_WIDTH: #player.hitbox.rect.x = 300 done = True load_city(player,current_level.get_next_city()) if current_level.player.hitbox.rect.x < 0: #player.hitbox.rect.x = 300 done = True load_city(player,current_level.get_preced_city()) # 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 90 frames per second clock.tick(constants.GAME_SPEED) # 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()
#RiverClan = Clan("RiverClan",warriors,EveryCat) #RiverClan.SayCats() #SkyClan isn't a real clan # Create the player player = GameEntity(6,'kit',RandomFur(),isAI = False) player.Setup() player.CreateSprite() #player.Setup() #print(player.SayName()) #level_list.append(levels.ForestCamp(player)) level_list.append(levels.Level_01(player)) level_list.append(levels.Level_02(player)) active_sprite_list = pygame.sprite.Group() AI_sprite_list = pygame.sprite.Group() active_sprite_list.add(player) I=0 while I < len(EveryCat): #print (EveryCat[I].SayRank() + ": " + EveryCat[I].SayName()) EveryCat[I].PutSprite(AI_sprite_list,AIcats) I=I + 1
def main(): pygame.init() size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT] screen = pygame.display.set_mode(size) pygame.display.set_caption("Platformer with sprite sheets") player = Player() level_list = [] level_list.append(levels.Level_01(player)) level_list.append(levels.Level_02(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 = constants.SCREEN_HEIGHT - player.rect.height active_sprite_list.add(player) done = False clock = pygame.time.Clock() while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True 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.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() active_sprite_list.update() current_level.update() if player.rect.x >= 500: diff = player.rect.x - 500 player.rect.x = 500 current_level.shift_world(-diff) if player.rect.x <= 120: diff = 120 - player.rect.x player.rect.x = 120 current_level.shift_world(diff) 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) # --- Update the screen with what we've drawn. pygame.display.flip() # --- Limit to 60 frames per second clock.tick(60) # Close the window and quit. pygame.quit()
def main(): """ Main Program """ #pygame.init() #main_menu() # 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("Danga") ### Main score song we pause for debug song = pygame.mixer.Sound("sounds/danga.wav") song.play(-1) score = 0 # Create the player player = Player() player_shot = None # Create the enemy enemy = Enemy() enemies = pygame.sprite.Group() npcs = pygame.sprite.Group() #Prepare for enemy_shots enemy_shots = pygame.sprite.Group() npc = Npc() # Create all the levels level_list = [] level_list.append(levels.Level_01(player)) level_list.append(levels.Level_02(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 enemy.level = current_level npc.level = current_level player.rect.x = 340 player.rect.y = constants.SCREEN_HEIGHT - player.rect.height active_sprite_list.add(player) enemy.rect.x = constants.SCREEN_WIDTH - enemy.rect.width enemy.rect.y = 0 #constants.SCREEN_HEIGHT - enemy.rect.height active_sprite_list.add(enemy) enemies.add(enemy) npc.rect.x = constants.SCREEN_WIDTH - enemy.rect.width npc.rect.y = 0 #constants.SCREEN_HEIGHT - enemy.rect.height #aggiungiano un NPC ? #active_sprite_list.add(npc) #npcs.add(npc) #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.yell() if event.key == pygame.K_LCTRL: #shots.append(Shot(player.rect.center, player.direction)) player_shot = Shot(player.rect.center, player.direction) active_sprite_list.add(player_shot) #if event.key == pygame.K_RCTRL: #shots.append(EnemyShot(enemy.rect.center)) #active_sprite_list.add(EnemyShot(enemy.rect.center, player)) 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() ### ENEMY SHOTS time_now = pygame.time.get_ticks() #print (str(time_now - enemy.last_shot)) if time_now - enemy.last_shot > 1500: current_shot = EnemyShot(enemy.rect.center, player) enemy_shots.add(current_shot) active_sprite_list.add(current_shot) enemy.last_shot = time_now #draw_text('COLLIDE!', font40, constants.WHITE, int( constants.SCREEN_WIDTH / 2 - 100), int( constants.SCREEN_HEIGHT / 2 + 50)) ### MAIN COLLISION (Player Shot) if player_shot: if pygame.sprite.collide_rect(player_shot, enemy): #print("COLLIDE") explosion = Explosion(enemy.rect.centerx, enemy.rect.centery, 4) active_sprite_list.add(explosion) score += 10 ### MAIN COLLISION (Enemy Shot) if pygame.sprite.collide_rect(current_shot, player): #print("COLLIDE") explosion = DeathExplosion(player.rect.centerx, player.rect.centery, 4) active_sprite_list.add(explosion) player.shield = player.shield -3 ### SHIELD, DEATH, LIVES AND GAME OVER if player.shield <= 0: player_die_sound.play() death_explosion = DeathExplosion(player.rect.centerx, player.rect.centery, 4) active_sprite_list.add(death_explosion) # running = False ## GAME OVER 3:D player.hide() player.lives -= 1 player.shield = 100 ## if player died and the explosion has finished, end game if player.lives == 0 and not death_explosion.alive(): done = True #draw_text(screen, "GAME OVER", 30, constants.SCREEN_WIDTH/2, constants.SCREEN_HEIGHT/2) ### SPRITE UPDATES # Update the player. active_sprite_list.update() # Update items in the level current_level.update() ### PLAYER SCREEN LIMITS # print ('x:'+str(player.rect.x)) # print ('y:'+str(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(-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 ### DRAWS # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT current_level.draw(screen) active_sprite_list.draw(screen) draw_text(screen, str(score), 18, constants.SCREEN_WIDTH / 2, 10) ## 10px down from the screen #draw_shield_bar(screen, 5, 5, 100) draw_shield_bar(screen, 5, 5, player.shield) # Draw lives draw_lives(screen, constants.SCREEN_WIDTH - 100, 5, player.lives, player_mini_img) # 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() game_over() main_menu()
def main(): # main program pygame.init() # height and width of screen size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT] screen = pygame.display.set_mode(size) pygame.display.set_caption("Hey it works i guess") # create player player = Player() # create all the levels level_list = [] level_list.append(levels.Level_01(player)) level_list.append(levels.Level_02(player)) # set 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 user clicks close button done = False # used to manage how fast 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 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 player is touching a door, warp levels. if event.key == pygame.K_DOWN and player.door(): current_level_no = 1 current_level = level_list[current_level_no] player.level = current_level 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 player gets near left... if player.rect.left <= 120: diff = 120 - player.rect.left player.rect.left = 120 current_level.shift_world(diff) # if player gets to end of level, go to 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 here current_level.draw(screen) active_sprite_list.draw(screen) # all code to draw should go above here # limit 60 fps clock.tick(60) # go ahead and update the screen with what we've drawn pygame.display.flip() # program will "hang" without this line: pygame.quit()
def main(): pygame.init() playsoundtrack() size = (constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT) screen = pygame.display.set_mode(size) pygame.display.set_caption("Xeon Platformer") pc = Player() level_list = [] level_list.append(levels.Level_01(pc)) level_list.append(levels.Level_02(pc)) current_level_no = 0 current_level = level_list[current_level_no] active_sprite_list = pygame.sprite.Group() pc.level = current_level pc.rect.x = 340 pc.rect.y = constants.SCREEN_HEIGHT - pc.rect.height active_sprite_list.add(pc) end = False won = False font = pygame.font.Font(None, 40) textlost = font.render("YOU LOST", 1, (255, 255, 255)) textwon = font.render("YOU WIN!", 1, (255, 255, 255)) textwon2 = font.render("All coins collected!", 1, (255, 255, 255)) done = False clock = pygame.time.Clock() while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True if event.type == pygame.KEYDOWN and end == False: if event.key == pygame.K_LEFT: pc.go_left() if event.key == pygame.K_RIGHT: pc.go_right() if event.key == pygame.K_UP: pc.jump() if event.key == pygame.K_F1: end = True won = True if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT and pc.change_x < 0: pc.stop() if event.key == pygame.K_RIGHT and pc.change_x > 0: pc.stop() active_sprite_list.update() current_level.update() if pc.rect.x >= 500: diff = pc.rect.x - 500 pc.rect.x = 500 current_level.shift_world(-diff) if pc.rect.x <= 120: diff = 120 - pc.rect.x pc.rect.x = 120 current_level.shift_world(diff) current_position = pc.rect.x + current_level.world_shift if current_position < current_level.level_limit: if current_level_no < len(level_list) - 1: pc.rect.x = 120 current_level_no += 1 current_level = level_list[current_level_no] pc.level = current_level elif current_level_no == 1: won = True # Draw current_level.draw(screen) active_sprite_list.draw(screen) score = pc.get_score() score_conv = str(score) score_text = font.render(score_conv, 1, (255, 255, 255)) if pc.get_status() == False: if won == False: screen.blit(score_text, (750, 550)) else: if pc.get_score() == 13: screen.blit(textwon2, (300, 300)) screen.blit(textwon, (360, 250)) screen.blit(score_text, (420, 350)) end = True else: end = True screen.blit(score_text, (380, 300)) screen.blit(textlost, (300, 250)) clock.tick(60) pygame.display.flip() pygame.quit()
def main(): pygame.init() # Initialisation de l'écran size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT] screen = pygame.display.set_mode(size) pygame.display.set_caption(constants.TITLE) player = Player() # Initialisation des niveaux level_list = [] level_list.append(levels.Level_01(player)) level_list.append(levels.Level_02(player)) # Définition du niveau actuel current_level_no = 0 current_level = level_list[current_level_no] player.level = current_level # Initialisation des HUD hud_list = [] hud_list.append(hud.Level_01_Hud(current_level)) current_hud = hud_list[current_level_no] player.hud = current_hud # Variable suivant le shift vertical des objets du jeu total_diff = 0 # Initialisation du joueur player.rect.x = constants.PLAYERINIT player.true_pos_x = constants.PLAYERINIT player.rect.y = constants.SCREEN_HEIGHT - player.rect.height - constants.TILE_HEIGHT / 2 # Attend la fermeture du programme done = False clock = pygame.time.Clock() # Déroulement du jeu while not done: ticks = pygame.time.get_ticks() for event in pygame.event.get(): if event.type == pygame.QUIT: done = True 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.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() # Met à jour le joueur et les items player.update() current_level.update(ticks) current_hud.update() # Déplace le monde vers la droite if player.rect.right >= constants.SHIFTLIMITRIGHT and -current_level.world_shift_h + \ constants.PLAYERINIT < current_level.level_end: diff = player.rect.right - constants.SHIFTLIMITRIGHT player.rect.right = constants.SHIFTLIMITRIGHT current_level.shift_world_h(-diff) # Déplace le monde vers la gauche si l'on a pas atteint la limite gauche if player.rect.left <= constants.SHIFTLIMITLEFT and current_level.world_shift_h < 0: diff = constants.SHIFTLIMITLEFT - player.rect.left player.rect.left = constants.SHIFTLIMITLEFT current_level.shift_world_h(diff) # Déplace le monde vers le haut if player.rect.top <= constants.SHIFTLIMITTOP: diff = constants.SHIFTLIMITTOP - player.rect.top total_diff += diff player.rect.top = constants.SHIFTLIMITTOP current_level.shift_world_v(diff) # Déplace le monde vers le bas si l'on a pas atteint le sol if player.rect.bottom >= constants.SHIFTLIMITBOTTOM and current_level.world_shift_v > 0: diff = constants.SHIFTLIMITBOTTOM - player.rect.bottom player.rect.bottom = constants.SHIFTLIMITBOTTOM if total_diff + diff <= 0: total_diff += diff current_level.shift_world_v(diff) else: total_diff += diff current_level.shift_world_v(diff) # Passe au niveau suivant # Récupère la position de la porte ouverte exit_door_x = 0 for item_scenery in current_level.items_scenery_list: if item_scenery.rect.x > exit_door_x: exit_door_x = item_scenery.rect.x if player.rect.x < exit_door_x + 3 and player.rect.x > exit_door_x - 3 and player.rect_image.top == constants.SCREEN_HEIGHT - \ player.rect_image.height - constants.TILE_HEIGHT / 2 and player.has_key: # Affiche un écran contenant les données du niveau terminé done = end_level_screen(screen, ticks, current_level.number_coins, current_level.picked_coins) if not done: player.rect.x = constants.PLAYERINIT player.true_pos_x = constants.PLAYERINIT if current_level_no < len(level_list) - 1: current_level_no += 1 current_level = level_list[current_level_no] current_hud = hud_list[current_level_no] player.level = current_level else: # Si il n'y a plus de niveaux, quitte le programme done = True # Dessin if not done: current_level.draw(screen) current_hud.draw(screen) screen.blit(player.image, (player.rect_image.x, player.rect_image.y)) screen.blit( current_hud.score_text, (constants.POSHUDCOINTEXT_X, constants.POSHUDCOINTEXT_Y)) # Fin dessin clock.tick(60) # Met à jour l'affichage pygame.display.flip() pygame.quit()
def main(): """ Main Program """ pygame.init() pygame.font.init() # you have to call this at the start, # if you want to use this module. myfont = pygame.font.SysFont('Comic Sans MS', 50) #loads the sound and music files, playing the background music jump_sound = pygame.mixer.Sound("jump_06.wav") death_sound = pygame.mixer.Sound( "Scream And Die Fx-SoundBible.com-299479967.wav") pygame.mixer.music.load("Medley1.wav") pygame.mixer.music.play(-1, 0.0) # 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("Don't FALL ):") # 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)) # 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 = 80 player.rect.y = 200 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_SPACE: player.jump() jump_sound.play() if event.key == pygame.K_r: main() 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 <= 50: diff = 50 - player.rect.x player.rect.x = 50 current_level.shift_world(diff) # If the player falls off the platforms, reset to the beginning of the game if player.rect.y >= 600: textsurface = myfont.render( 'You fell! Oh no! Game will reset in 3 seconds!', True, constants.WHITE, constants.BLACK) textr = textsurface.get_rect() textr.center = (600, 350) screen.fill(constants.BLACK) death_sound.play() screen.blit(textsurface, textr) pygame.display.update() sleep(3.0) main() #Finds the position of the player and displays a message if player reached the end of level 2 current_position = player.rect.x + current_level.world_shift if current_level_no == 1 and current_position < current_level.level_limit: textsurface1 = myfont.render( 'You reached the end of the game! Congrats!', True, constants.WHITE, constants.BLACK) textr1 = textsurface1.get_rect() textr1.center = (600, 350) screen.fill(constants.BLACK) screen.blit(textsurface1, textr1) pygame.display.update() sleep(3.0) done = True pygame.quit() # If the player gets to the end of the level, go to the next level current_position1 = player.rect.x + current_level.world_shift if current_position1 < 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) # 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()
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()
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()
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)
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("Right to Vengeance") # Create the player p1 = player.Player() # Create all the levels level_list = [] level_list.append(levels.Start_Menu(p1)) level_list.append(levels.Options_Menu(p1)) level_list.append(levels.Help_Menu(p1)) level_list.append(levels.Level_01(p1)) level_list.append(levels.Level_02(p1)) level_list.append(levels.Win_Screen(p1)) # Set the current level current_level_no = 0 previous_level_no = 0 current_level = level_list[current_level_no] active_sprite_list = pygame.sprite.Group() p1.level = current_level enemy.level = current_level p1.rect.x = p1.level.player_x p1.rect.y = p1.level.player_y active_sprite_list.add(p1) pygame.mixer.music.load('brass_song.wav') pygame.mixer.music.set_endevent(pygame.constants.USEREVENT) pygame.mixer.music.set_volume(p1.music_volume) #Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates clock = pygame.time.Clock() menu_up = True # -------- Main Program Loop ----------- while not done: while not done and menu_up: 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_1: current_level_no = 3 menu_up = False current_level = level_list[current_level_no] p1.level = current_level pygame.mixer.music.play() if event.key == pygame.K_2: current_level_no = 4 menu_up = False current_level = level_list[current_level_no] p1.level = current_level if event.type == pygame.MOUSEBUTTONDOWN: x, y = event.pos for button in current_level.platform_list: if button.rect.collidepoint(x, y): if button.button_type == "start": pygame.mixer.music.play() previous_level_no = current_level_no current_level_no = 3 menu_up = False current_level = level_list[current_level_no] p1.level = current_level if button.button_type == "options": previous_level_no = current_level_no current_level_no = 1 current_level = level_list[current_level_no] if button.button_type == "gooptions": current_level_no = 1 current_level = level_list[current_level_no] if button.button_type == "back": temp = current_level_no current_level_no = previous_level_no previous_level_no = temp current_level = level_list[current_level_no] if current_level_no >= 3: p1.level = current_level menu_up = False pygame.mixer.music.unpause() if button.button_type == "quit": pygame.quit() if button.button_type == "help": current_level_no = 2 current_level = level_list[current_level_no] if button.button_type == "music_plus": if (p1.music_volume <= .95): p1.music_volume += .05 pygame.mixer.music.set_volume( p1.music_volume) if button.button_type == "music_minus": if (p1.music_volume >= .05): p1.music_volume -= .05 pygame.mixer.music.set_volume( p1.music_volume) if button.button_type == "difficulty_plus": if (p1.difficulty <= 5): p1.difficulty += 1 p1.dif_multiplier = p1.dif_multiplier * 2 if button.button_type == "difficulty_minus": if (p1.difficulty >= 1): p1.difficulty -= 1 p1.dif_multiplier = p1.dif_multiplier / 2 # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT current_level.draw_menu(screen) if current_level_no == 1: pygame.draw.rect(screen, constants.GREEN, [500, 300, p1.music_volume * 200, 20]) if current_level_no == 1: pygame.draw.rect(screen, constants.GREEN, [500, 385, p1.difficulty * 50, 20]) # 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() if 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_1: current_level_no = 3 current_level.player_x = p1.rect.x current_level.player_y = p1.rect.y current_level = level_list[current_level_no] p1.level = current_level p1.rect.x = current_level.player_x p1.rect.y = current_level.player_y if event.key == pygame.K_2: current_level_no = 4 current_level.player_x = p1.rect.x current_level.player_y = p1.rect.y current_level = level_list[current_level_no] p1.level = current_level p1.rect.x = current_level.player_x p1.rect.y = current_level.player_y if event.key == pygame.K_j: p1.p_attack = True if event.key == pygame.K_a: p1.go_left() if event.key == pygame.K_d: p1.go_right() if event.key == pygame.K_w: p1.jump() #in event handling: if event.key == pygame.K_ESCAPE: previous_level_no = current_level_no current_level_no = 1 menu_up = True current_level = level_list[current_level_no] pygame.mixer.music.pause() if event.type == pygame.KEYUP: if event.key == pygame.K_j: p1.p_attack = False if event.key == pygame.K_a and p1.change_x < 0: p1.stop() if event.key == pygame.K_d and p1.change_x > 0: p1.stop() if event.type == pygame.constants.USEREVENT: # This event is triggered when the song stops playing. pygame.mixer.music.load('level1_song.wav') pygame.mixer.music.play() # 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 p1.rect.x >= constants.RIGHT_SHIFT: diff = p1.rect.x - constants.RIGHT_SHIFT p1.rect.x = constants.RIGHT_SHIFT current_level.shift_world(-diff) # If the player gets near the left side, shift the world right (+x) if p1.rect.x <= constants.LEFT_SHIFT: diff = constants.LEFT_SHIFT - p1.rect.x p1.rect.x = constants.LEFT_SHIFT current_level.shift_world(diff) # If the player gets to the end of the level, go to the next level current_position = p1.rect.x + current_level.world_shift if p1.won == True: p1.rect.x = 120 p1.won = False current_level_no += 1 current_level = level_list[current_level_no] p1.level = current_level if p1.level_2_win == True: current_level_no = 5 menu_up = True current_level = level_list[current_level_no] pygame.mixer.music.pause() if (p1.hp < 1): p1.rect.x = current_position - 320 p1.rect.y = constants.SCREEN_HEIGHT - p1.rect.height p1.hp = p1.MAX_HP # 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(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()
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 main(): # Main program pygame.init() timer = 0 score = 0 # Set height and width of screen size = [Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT] screen = pygame.display.set_mode(size) # Set the name of the game window pygame.display.set_caption("Metal_Snail") directory_name = (sys.path[0] + "\Assets") font = pygame.font.Font(os.path.join(directory_name, "Romulus.ttf"), 40) # Create the player player = create_player() # Create the levels level_list = [] level_list.append(levels.Level_01(player)) level_list.append(levels.Level_02(player)) # Set the current level current_level_number = 0 current_level = level_list[current_level_number] active_sprite_list = pygame.sprite.Group() enemy_sprite_list = pygame.sprite.Group() firebolt_list = pygame.sprite.Group() enemy_firebolt_list = pygame.sprite.Group() player_list = pygame.sprite.Group() player.level = current_level player.rect.x = 1 player.rect.y = Constants.SCREEN_HEIGHT - player.rect.height active_sprite_list.add(player) player_list.add(player) active_sprite_list.add(current_level.get_enemy_list()) enemy_sprite_list.add(current_level.get_enemy_list()) clock = pygame.time.Clock() done = False shift = True while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a: player.move_left() elif event.key == pygame.K_d: player.move_right() elif event.key == pygame.K_SPACE: player.jump() elif event.key == pygame.K_RETURN: # Fire a firebolt if the user clicks the mouse button firebolt = spells.Firebolt() # Set the firebolt so it is where the player is, and so it shoots the same direction as the player if player.get_direction() == "R": firebolt.rect.x = player.rect.x + 25 firebolt.rect.y = player.rect.y + 25 firebolt.shoot_right() elif player.get_direction() == "L": firebolt.rect.x = player.rect.x - 25 firebolt.rect.y = player.rect.y + 25 firebolt.shoot_left() # Add the firebolt to the lists active_sprite_list.add(firebolt) firebolt_list.add(firebolt) elif event.type == pygame.KEYUP: if event.key == pygame.K_a or event.key == pygame.K_d: player.stop() # Update the player active_sprite_list.update() timer += 1 if timer >= 50: for enemy in enemy_sprite_list: enemy_firebolt = spells.Enemy_Firebolt() if enemy.get_direction() == "R": enemy_firebolt.rect.x = enemy.rect.x + 25 enemy_firebolt.rect.y = enemy.rect.y + 25 enemy_firebolt.shoot_right() timer = 0 elif enemy.get_direction() == "L": enemy_firebolt.rect.x = enemy.rect.x - 25 enemy_firebolt.rect.y = enemy.rect.y + 25 enemy_firebolt.shoot_left() timer = 0 active_sprite_list.add(enemy_firebolt) enemy_firebolt_list.add(enemy_firebolt) # Calculate mechanics for enemy firebolts for firebolt in enemy_firebolt_list: # See if it hit the player block_hit_list = pygame.sprite.spritecollide( firebolt, player_list, False) # When a firebolt hits the player deduct the players health based on the firebolts damage for block in block_hit_list: block.take_damage(firebolt.get_damage()) enemy_firebolt_list.remove(firebolt) active_sprite_list.remove(firebolt) if block.get_health() <= 0: enemy_sprite_list.remove(block) active_sprite_list.remove(block) player_list.remove(player_list) # Calculate mechanics for player firebolt for firebolt in firebolt_list: # See if it hit a block block_hit_list = pygame.sprite.spritecollide( firebolt, enemy_sprite_list, False) # When a firebolt hits an enemy deduct the enemies health based on the firebolts damage for block in block_hit_list: block.take_damage(firebolt.get_damage()) firebolt_list.remove(firebolt) active_sprite_list.remove(firebolt) if block.get_health() <= 0: score += 100 enemy_sprite_list.remove(block) active_sprite_list.remove(block) current_level.get_enemy_list().remove(block) # Remove the firebolt if it flies up off the screen if firebolt.rect.x < -10: firebolt_list.remove(firebolt) active_sprite_list.remove(firebolt) # Update the level current_level.update() # if the player gets near the right side, shift the world left (-x) current_position = player.rect.x + current_level.world_shift if player.rect.x >= 500 and shift == True: diff = player.rect.x - 500 if current_position < current_level.level_limit: diff = 0 shift = False player.rect.x = 500 current_level.shift_world(-diff) # If the player gets near the left side, shift the world left (x) if player.rect.x <= 1: player.rect.x = 0 if player.rect.x >= 800: player.rect.x = 120 if current_level_number < len(level_list) - 1: current_level_number += 1 current_level = level_list[current_level_number] player.level = current_level current_level.play_audio() active_sprite_list.add(current_level.get_enemy_list()) enemy_sprite_list.add(current_level.get_enemy_list()) shift = True # ALL CODE FOR DRAWING THE LEVEL GOES BELOW THIS LINE current_level.draw(screen) active_sprite_list.draw(screen) text_surface = font.render("Health: " + str(player.get_health()), True, Constants.black) TextRect = text_surface.get_rect() TextRect.center = (90, 20) screen.blit(text_surface, TextRect) text_surface = font.render("Score: " + str(score), True, Constants.black) TextRect = text_surface.get_rect() TextRect.center = (650, 20) screen.blit(text_surface, TextRect) # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT pygame.display.flip() pygame.display.update() # Limits the fps of the game clock.tick(60) pygame.quit()
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("Platformer with sprite sheets") # Create the player player = Player(100) blue_powerup = power_up("blue_fire", (900, 700)) combee = Combee(1000, 1) # Create all the levels level_list = [] level_list.append(levels.Level_01(player)) level_list.append(levels.Level_02(player)) # List of each bullet # Set the current level current_level_no = 0 current_level = level_list[current_level_no] combee_sprite_list = pygame.sprite.Group() player_sprite_list = pygame.sprite.Group() blue_powerup_sprite_list = pygame.sprite.Group() player_projectile_sprite_list = pygame.sprite.Group() pokeball_sprite_list = pygame.sprite.Group() player.level = current_level combee.level = current_level player.rect.x = 340 player.rect.y = constants.SCREEN_HEIGHT - player.rect.height blue_powerup.rect.x = 900 blue_powerup.rect.y = 700 combee.rect.x = 500 combee.rect.y = 500 combee_sprite_list.add(combee) player_sprite_list.add(player) blue_powerup_sprite_list.add(blue_powerup) #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: print("good throw") if player.direction == "L": pokeball = Pokeball(-1) else: pokeball = Pokeball(1) # Set the bullet so it is where the player is pokeball.rect.x = player.rect.x pokeball.rect.y = player.rect.y pokeball_sprite_list.add(pokeball) 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() elif event.type == pygame.MOUSEBUTTONDOWN: # Fire a bullet if the user clicks the mouse button if player.direction == "L": projectile = player.attack(-1) else: projectile = player.attack(1) # Set the bullet so it is where the player is if player.attack == Fireball or player.attack == Bluefireball: projectile.rect.x = player.rect.x projectile.rect.y = player.rect.y # Add the bullet to the lists player_projectile_sprite_list.add(projectile) if player.health < 0: player.health = 0 if combee.health < 0: combee.health = 0 combee.capturable = True # Update the player. combee_sprite_list.update() player_sprite_list.update() blue_powerup_sprite_list.update() player_projectile_sprite_list.update() pokeball_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 # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT current_level.draw(screen) combee_sprite_list.draw(screen) player_sprite_list.draw(screen) # blue_powerup_sprite_list.draw(screen) player_projectile_sprite_list.draw(screen) pokeball_sprite_list.draw(screen) # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT if player.health >= 66: player.update_health(screen, (0, 255, 0)) elif player.health >= 33: player.update_health(screen, (255, 255, 0)) else: player.update_health(screen, (255, 0, 0)) if combee.health >= 666: combee.update_health(screen, (0, 255, 0)) elif combee.health >= 333: combee.update_health(screen, (255, 255, 0)) else: combee.update_health(screen, (255, 0, 0)) if pygame.sprite.groupcollide(combee_sprite_list, player_projectile_sprite_list, False, True): combee.health -= 100 if combee.capturable: if pygame.sprite.groupcollide(combee_sprite_list, pokeball_sprite_list, True, True): combee.captured = True # 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()
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("Escapey Pet") # 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)) # 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() # -------- 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.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 # 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(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()
def comenzar_nuevo_juego(self): pygame.init() # Atributos puntuacion = 0 enemie_dead = True enemie_dead2 = True entrar = False muertohalcon = False done = False count = 0 kill = False kill2 = False clock = pygame.time.Clock() crears = True size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT] screen = pygame.display.set_mode(size) pygame.display.set_caption("Looking for my Son") # Sonidos iniciales pygame.mixer.music.load("sounds/birdgame.mp3") jump = pygame.mixer.Sound("sounds/jump.wav") pygame.mixer.music.play() # Creamos el jugador y los enemigos player = Player() buho = Buho() enemies_list = [] enemies_list2 = [] ls_balaenemie = [] aguila = Aguila() halcon = Halcon() # Creamos todos los niveles level_list = [] level_list.append(levels.Level_01(player, buho, aguila)) level_list.append(levels.Level_02(player, buho, aguila)) # Iniciamos el nivel 0 current_level_no = 0 current_level = level_list[current_level_no] # Activamos el group sprite para almacenar todos los sprites(dibujos) del juego # Situamos al jugador en el nivel actual y lo añadimos al grupo de sprites self.active_sprite_list = pygame.sprite.Group() player.level = current_level player.rect.x = 340 player.rect.y = constants.SCREEN_HEIGHT - player.rect.height self.active_sprite_list.add(player) # Establece una ubicación aleatoria para el aguila aguila.rect.x = random.randrange(160) aguila.rect.y = random.randrange(10) aguila.cambio_x = random.randrange(-3, 4) aguila.cambio_y = random.randrange(-3, 4) aguila.limite_izquierdo = 0 aguila.limite_superior = 0 aguila.limite_derecho = constants.SCREEN_WIDTH aguila.limite_inferior = constants.SCREEN_HEIGHT # Establecemos una ubicacion aleatoria para el halcon halcon.rect.x = random.randrange(160) halcon.rect.y = random.randrange(10) halcon.cambio_x = random.randrange(-3, 4) halcon.cambio_y = random.randrange(-3, 4) halcon.limite_izquierdo = 0 halcon.limite_superior = 0 halcon.limite_derecho = constants.SCREEN_WIDTH halcon.limite_inferior = constants.SCREEN_HEIGHT """# Establece una ubicación aleatoria superman superman.rect.x = random.randrange(160) superman.rect.y = random.randrange(40,600) superman.cambio_x = random.randrange(-3,4) superman.cambio_y = random.randrange(-3,4) superman.limite_izquierdo = 0 superman.limite_superior = 0 superman.limite_derecho = constants.SCREEN_WIDTH superman.limite_inferior = constants.SCREEN_HEIGHT """ # Creamos la cantidad de enemigos buho en el juego for i in range(1): buho = Buho() balaenemie = Bala('yoga-ball.png') balaenemie.jugador = 2 #Establecemos una ubicación central aleatoria para que orbite el buho. buho.centrar_x = random.randrange(200, constants.SCREEN_WIDTH / 2) buho.centrar_y = random.randrange(100, constants.SCREEN_HEIGHT / 2) # Radio aleatorio, desde a to b buho.radio = random.randrange(0, 300) # Ángulo de inicio aleatorio, desde 0 a 2pi buho.angulo = random.random() * 2 * math.pi # radianes por fotograma. buho.velocidad = 0.008 balaenemie.rect.x = buho.centrar_x balaenemie.rect.y = buho.centrar_y # Añadimos el buho a la lista de objetos. enemies_list.append(buho) buho.level = current_level ls_balaenemie.append(balaenemie) # Creamos la cantida de enemigos gallinazos en el juego for i in range(5): gallinazo = Gallinazo() balaenemie = Bala('yoga-ball.png') balaenemie.jugador = 2 #Establecemos una ubicación central aleatoria para que orbite el buho. gallinazo.centrar_x = random.randrange(300, constants.SCREEN_WIDTH / 2) gallinazo.centrar_y = random.randrange(100, constants.SCREEN_HEIGHT / 2) # Radio aleatorio, desde a to b gallinazo.radio = random.randrange(0, 280) # Ángulo de inicio aleatorio, desde 0 a 2pi gallinazo.angulo = random.random() * 2 * math.pi # radianes por fotograma. gallinazo.velocidad = 0.058 balaenemie.rect.x = gallinazo.centrar_x balaenemie.rect.y = gallinazo.centrar_y # Añadimos el buho a la lista de objetos. enemies_list2.append(gallinazo) gallinazo.level = current_level ls_balaenemie.append(balaenemie) # Activamos los buhos en el juego for i in enemies_list: self.active_sprite_list.add(i) # Otras configuraciones ls_bala = [] self.active = False fuente = pygame.font.Font(None, 30) # LOOP PRINCIPAL DEL JUEGO while not done: for event in pygame.event.get( ): # Observamos los eventos en la pantalla if event.type == pygame.QUIT: # Si el usuario cierra la pantalla cerramos el juego done = True # Bandera para saber si salir o no pygame.mixer.music.stop() # Paramos la musica self.main() # Salimos a la pantalla principal # Capturamos los eventos de tecla if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT and self.active == False: player.go_left() if event.key == pygame.K_RIGHT and self.active == False: player.go_right() if event.key == pygame.K_UP and self.active == False: player.jump() jump.play() # Aqui pausamos if (event.key == pygame.K_p): pygame.mixer.music.pause() self.active = True self.pause = True self.paused() # Aqui disparamos if event.key == pygame.K_x: if player.direction == 'L': bala = Bala('corn_l.png') bala.jugador = 1 else: bala = Bala('corn_r.png') bala.rect.x = player.rect.x + 10 bala.rect.y = player.rect.y self.active_sprite_list.add(bala) ls_bala.append(bala) # Dependiendo el nivel matamos o aguilas o halcones for j in ls_bala: if current_level_no == 0: for i in enemies_list: if i == aguila: if pygame.sprite.collide_rect(i, j): aguila.vida -= 10 self.active_sprite_list.remove(j) ls_bala.remove(j) puntuacion += 50 else: if pygame.sprite.collide_rect(i, j): self.active_sprite_list.remove(i) enemies_list.remove(i) self.active_sprite_list.remove(j) ls_bala.remove(j) puntuacion += 50 else: for i in enemies_list2: if i == halcon: if pygame.sprite.collide_rect(i, j): halcon.vida -= 10 self.active_sprite_list.remove(j) ls_bala.remove(j) puntuacion += 50 else: if pygame.sprite.collide_rect(i, j): self.active_sprite_list.remove(i) enemies_list2.remove(i) self.active_sprite_list.remove(j) ls_bala.remove(j) puntuacion += 50 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() # Generamos un numero aleatorio para saber cuando disparar disparar = random.randint(1, 60) # Disparamos cuando el numero generado es 1 y dependiendo el nivel activamos los disparos para # los buhos o gallinazos if disparar == 1 and current_level_no == 0: self.recargarEnem(enemies_list, ls_balaenemie, self.active_sprite_list) if disparar == 1 and current_level_no == 1: self.recargarEnem(enemies_list2, ls_balaenemie, self.active_sprite_list) # Actualizamos todos los sprites # Esto permite usar todos las funciones updates de los sprites que hemos creado self.active_sprite_list.update() # Actualizamos el nivel current_level.update() """if player.vida < 400: self.active_sprite_list.add(superman) if pygame.sprite.collide_rect(player,superman): self.active_sprite_list.remove(superman) for sprite in self.active_sprite_list: if sprite == superman: sprite.kill() active_sprite_list.remove(sprite) player.vida += 300 """ # Si la vida se nos agota entonces perdimos y salimos al menu inicial if player.vida <= 0: screen.blit(self.gameover, (0, 0)) pygame.display.flip() pygame.mixer.music.stop() time.sleep(2) done = True self.main() puntuacion = 0 player.vida = 1000 # Si la vida del aguila se acaba entonces activamos las variables que nos permiten cambiar de nivel if aguila.vida <= 0: self.active_sprite_list.remove(aguila) for i in enemies_list[:]: enemies_list.remove(i) enemie_dead = False entrar = True aguila.vida = 0 # Si la vida del halcon se acaba entonces hemos ganado if halcon.vida <= 0: self.active_sprite_list.remove(halcon) for i in enemies_list2[:]: enemies_list2.remove(i) enemie_dead2 = False entrar = False halcon.vida = 0 muertohalcon = True # Recorremos la lista de balas y la lista de bala de enemigos para saber si colisionaron y eliminarlas for j in ls_bala: for i in ls_balaenemie: if pygame.sprite.collide_rect(i, j): self.active_sprite_list.remove(i) ls_balaenemie.remove(i) self.active_sprite_list.remove(j) ls_bala.remove(j) # Si estamos en el nivel 0 y chocamos con los enimigos restamos 10 puntos de nuestra vida # en caso contrario si estamos en el nive 1 hacemos lo mismo if current_level_no == 0: for i in enemies_list: if pygame.sprite.collide_rect( i, player) and puntuacion > 0 and player.vida > 0: player.vida -= 10 else: for i in enemies_list2: if pygame.sprite.collide_rect( i, player) and puntuacion > 0 and player.vida > 0: player.vida -= 10 # Recorremos la lista de balas y si chocan con el jugador restamos vida y borramos la bala for i in ls_balaenemie: if pygame.sprite.collide_rect( i, player) and puntuacion >= 0 and player.vida >= 0: player.vida -= 10 self.active_sprite_list.remove(i) ls_balaenemie.remove(i) # Nos sirve para resetear la posicion del jugador despues de cierto limite if player.rect.x >= 500: diff = player.rect.x - 500 player.rect.x = 500 current_level.shift_world(-diff) # Nos sirve para resetear la posicion del jugador despues de cierto limite if player.rect.x <= 120: diff = 120 - player.rect.x player.rect.x = 120 current_level.shift_world(diff) # Nos permite activar el aguila del primer nivel if not enemies_list: if enemie_dead: kill = True else: kill = False # Nos permite activar el halcon del segundo nivel if not enemies_list2: if enemie_dead2: kill2 = True else: kill2 = False # Calculamos la posicion actual del jugador current_position = player.rect.x + current_level.world_shift # Si la posicion es menor a -760 y hemos matado a los enemigos secundarios, mostramos al Aguila if current_position < -760 and kill and current_level_no == 0: #Añade el aguila a la lista de objetos pygame.mixer.music.load("battle.mp3") pygame.mixer.music.play() enemies_list.append(aguila) current_level.draw(screen, puntuacion, player.vida, aguila.vida) self.active_sprite_list.add(aguila) kill = False enemie_dead = False # Si estamos en el segundo nivel y hemos matada a los enemigos secundatios, mostramos el Halcon elif current_position < -760 and kill2 and current_level_no == 1: pygame.mixer.music.load("battle.mp3") pygame.mixer.music.play() enemies_list2.append(halcon) current_level.draw(screen, puntuacion, player.vida, halcon.vida) self.active_sprite_list.add(halcon) kill2 = False enemie_dead2 = False # Si hemos matado al halcon del nivel 2, GANAMOS el juego if current_level_no == 1 and not enemies_list2 and muertohalcon: time.sleep(2) screen.blit(self.gana, (0, 0)) pygame.display.flip() pygame.mixer.music.stop() time.sleep(2) done = True self.main() puntuacion = 0 player.vida = 1000 # Nos permite cambiar de nivel if current_position < current_level.level_limit and entrar: for i in enemies_list2: self.active_sprite_list.add(i) if current_level_no < len(level_list) - 1: current_level_no += 1 current_level = level_list[current_level_no] player.level = current_level # Nos permite mostrar la vida y la puntuacion en la pantalla if current_level_no == 0: current_level.draw(screen, puntuacion, player.vida, aguila.vida) else: current_level.draw(screen, puntuacion, player.vida, halcon.vida) # Dibujamos todos los sprites en la pantalla de juego self.active_sprite_list.draw(screen) # 60 imagenes por segundo para el reloj de refresco clock.tick(60) pygame.display.flip()
def runGame(): # create player # init Player player = Player() bullet = Bullet() drag = FlyEnemy() level_list = [] level_list.append(levels.Level_01(player, bullet, drag)) level_list.append(levels.Level_02(player, bullet, drag)) # set the current level current_level_no = 0 current_level = level_list[current_level_no] player.level = current_level # Sprite Groups active_sprite_list = pygame.sprite.Group() bullets = pygame.sprite.Group() enemies = pygame.sprite.Group() player.rect.x = 340 player.rect.y = constants.SCREEN_HEIGHT - player.rect.height + 100 active_sprite_list.add(player) enemies.add(drag) active_sprite_list.add(drag) #active_sprite_list.add(bullet) #bullets.add(bullet) bullet_count = 0 #-- Timer Display Setup frame_count = 0 start_time = 45 # loop until the user clicks the close button done = False while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True 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() bullet.rect.x = player.rect.centerx bullet.rect.y = player.rect.y active_sprite_list.add(bullet) bullets.add(bullet) 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() bulletCounter = 0 # update the player active_sprite_list.update() #update items in the level current_level.update() # If the player gets near the right side, shift world left (-x) if player.rect.right >= 500: diff = player.rect.right - 500 player.rect.right = 500 current_level.shift_world(-diff) # if player gets near left side, shift world right (+x) if player.rect.left <= 120: diff = 120 - player.rect.left player.rect.left = 120 current_level.shift_world(diff) # If player gets to end of level, go to 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 # player collide with FlyEnemy flyhit = pygame.sprite.spritecollide(player, enemies, True) for hit in flyhit: player.kill() done = True # - Batarang Kill Enemies bathit = pygame.sprite.groupcollide(enemies, bullets, True, True) for hit in bathit: enemies.kill() # -- Win Screen once player reaches end #if current_level_no > len(level_list)-2: #done = True #winScreen() # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT current_level.draw(screen) active_sprite_list.draw(screen) # --- Timer going up --- # Calculate total seconds total_seconds = frame_count // constants.frame_rate #Calculate for Going Down --- #total_seconds = start_time - (frame_count // constants.frame_rate) #if total_seconds < 0: #total_seconds = 0 # Divide by 60 to get total minutes minutes = total_seconds // 60 # use remainder to get seconds seconds = total_seconds % 60 # Python string formatting to format into leading zeros output_string = "Time Wasted: {0:02}:{1:02}".format(minutes, seconds) #blit to screen text_time = font.render(output_string, True, constants.red) screen.blit(text_time, [15, 5]) # -------------------Timer----------- # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT frame_count += 1 # limit to 60 frames per second clock.tick(constants.frame_rate) # update screen pygame.display.flip() # Add GamesOver Screen #if total_seconds == 0: #done = True #gameOver() # to avoid exit errors pygame.quit()
def main(): # Main Program pygame.init() # Define altura, largura e posição inicial da janela size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT] screen = pygame.display.set_mode(size) os.environ["SDL_VIDEO_WINDOW_POS"] = '200,50' screen = pygame.display.set_mode((1, 1)) # Define ícone e label da janela icon = pygame.image.load("images/triforceicon.png") pygame.display.set_caption("The Legend Of Souls") pygame.display.set_icon(icon) # Esconde o cursor do mouse pygame.mouse.set_visible(0) # Cria o player player = Player() # Cria os inimigos enemy = Enemy() # Cria todos os levels level_list = [] level_list.append(levels.Level_01(player, enemy)) level_list.append(levels.Level_02(player, enemy)) # Define o level atual current_level_no = 0 current_level = level_list[current_level_no] active_sprite_list = pygame.sprite.Group() player.level = current_level enemy.level = current_level # Define posição inicial do player player.rect.x = 150 player.rect.y = constants.SCREEN_HEIGHT - player.rect.height - 12 active_sprite_list.add(player) # Define posição inicial do enemy enemy.rect.x = 550 enemy.rect.y = constants.SCREEN_HEIGHT - enemy.rect.height - 32 active_sprite_list.add(enemy) #Loop até o usuário fechar o jogo ingame = True # Controla quão rápido a janela atualiza clock = pygame.time.Clock() # Mostra a tela de início levels.start_screen() # -------- Main Program Loop ----------- while ingame: for event in pygame.event.get(): pressed = pygame.key.get_pressed() if event.type == pygame.QUIT: ingame = False # Fecha a janela se o usuário clicar em fechar if event.type == pygame.KEYDOWN: if ((pressed[pygame.K_LALT] and pressed[pygame.K_F4]) or (pressed[pygame.K_RALT] and pressed[pygame.K_F4])): ingame = False # Fecha a janela se o usuário pressionar ALT+F4 if event.key == pygame.K_a: player.go_left() if event.key == pygame.K_LEFT: enemy.go_left() if event.key == pygame.K_d: player.go_right() if event.key == pygame.K_RIGHT: enemy.go_right() if event.key == pygame.K_w: player.jump() if event.key == pygame.K_UP: enemy.jump() if event.type == pygame.KEYUP: if event.key == pygame.K_a and player.change_x < 0: player.stop() if event.key == pygame.K_d and player.change_x > 0: player.stop() if event.key == pygame.K_LEFT and enemy.change_x < 0: enemy.stop() if event.key == pygame.K_RIGHT and enemy.change_x > 0: enemy.stop() # Atualiza o player active_sprite_list.update() # Atualiza os itens no level current_level.update() # Se o player chegar perto do lado direito, muda o world para a esquerda (-x) if player.rect.right >= 500: diff = player.rect.right - 500 player.rect.right = 500 current_level.shift_world(-diff) # Se o player chegar perto do lado esquerdo, muda o world para a direita (+x) if player.rect.left <= 120: diff = 120 - player.rect.left player.rect.left = 120 current_level.shift_world(diff) # Se o player chegar ao fim do level, vai para o próximo level current_position = player.rect.x + current_level.world_shift if (current_position < current_level.level_limit) and current_level_no != 0: 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 # Todo código de desenhar current_level.draw(screen) active_sprite_list.draw(screen) # Limita os frames por segundo clock.tick(60) # Atualiza a janela com o que foi desenhado pygame.display.flip() pygame.quit() #Termina o jogo
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()
def main(self): """ Main Program """ pygame.init() # Create the player player = Player(SpriteSheet('catman.png')) # Create all the levels level_list = [] level_list.append(levels.Level_01(player)) level_list.append(levels.Level_02(player)) # Set the current level & player position 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 - 500 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() start_ticks = pygame.time.get_ticks() #starter tick # -------- Main Program Loop ----------- while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == None: player.idle() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a or event.key == pygame.K_LEFT: player.go_left() elif event.key == pygame.K_d or event.key == pygame.K_RIGHT: player.go_right() elif event.key == pygame.K_w or event.key == pygame.K_UP: player.jump() elif event.key == pygame.K_SPACE: if len(player.bullet_list) < 4: # Fire a bullet if the user clicks the mouse button bullet = Bullet(player) # Set the bullet so it is where the player is bullet.rect.x = player.rect.x + 10 bullet.rect.y = player.rect.y + 10 # Add the bullet to the lists player.bullet_list.add(bullet) # set what happens when player lets the key up elif event.type == pygame.KEYUP: if event.key == pygame.K_a or event.key == pygame.K_LEFT and player.change_x < 0: player.stop() elif event.key == pygame.K_d or event.key == pygame.K_RIGHT and player.change_x > 0: player.stop() # Update the player. active_sprite_list.update() player.bullet_list.update() # Update items in the level current_level.update() ydiff = 0 diff = 0 # if the player gets near the top, shift the world up (ydiff) if player.rect.top <= 20: ydiff = player.rect.top - 20 player.rect.top = 20 current_level.shift_world_y(ydiff) # if the player gets near the bottom, shift the world down (ydiff) if player.rect.bottom >= 550: ydiff = player.rect.bottom - 550 player.rect.bottom = 550 current_level.shift_world_y(ydiff) # 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 = 150 if current_level_no < len(level_list) - 1: current_level_no += 1 current_level = level_list[current_level_no] player.level = current_level player.stop() # IF the player falls, game done if player.rect.y + player.level.world_shift_y + 75 > constants.SCREEN_HEIGHT: done = True seconds = (pygame.time.get_ticks() - start_ticks) / 1000 #calculate how many seconds # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT current_level.draw(screen) active_sprite_list.draw(screen) player.bullet_list.draw(screen) font = pygame.font.SysFont(None, 25) showscore = font.render(f"Score: {player.score}", True, constants.BLACK) showclock = font.render(f"Time: {round(seconds,2)}", True, constants.BLACK) screen.blit(showscore, (10, 10)) screen.blit(showclock, (constants.SCREEN_WIDTH / 2, 10)) for crony in player.level.enemy_list: crony.draw(screen) for platform in player.level.platform_list: try: platform.draw(screen) except: pass # 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.update() print(player.rect.x - player.level.world_shift, player.rect.y) # Be IDLE friendly. If you forget this line, the program will 'hang' # on exit. pygame.quit()