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()
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(): """ Main Program """ pygame.init() pygame.mixer.init() # Set the height and width of the screen size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT] screen = pygame.display.set_mode(size) pygame.display.set_caption("Unloader: Grocery Store Edition") # Create the user's player player = Player() # Create all the levels level_list = [] level_list.append(levels.Level_01(player)) # Points # point = 0 # 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 = 400 player.rect.y = 300 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() pygame.mixer.music.load('assets\\Initial D - Deja Vu.mp3') pygame.mixer.music.set_endevent(pygame.constants.USEREVENT) pygame.mixer.music.play() wall_sound = pygame.mixer.Sound("assets\\iump.ogg") # -------- 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.go_up() if event.key == pygame.K_DOWN: player.go_down() 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_DOWN and player.change_y > 0: player.stop() if event.key == pygame.K_UP and player.change_y < 0: player.stop() # Update the player if player.play_sound: wall_sound.play() player.play_sound = False active_sprite_list.update() # Update items in the level current_level.update() # 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() pygame.quit()
def main(): """ Main Program """ pygame.mixer.init(44100, -16, 2, 2048) pygame.init() # Set the height and width of the screen size = [1400, constants.SCREEN_HEIGHT] screen = pygame.display.set_mode(size) pygame.display.set_caption("WohnJick") sound_library.pygame.mixer.music.play(-1) # 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 = 1300 player.rect.y = 450 active_sprite_list.add(player) # you_died = pygame.transform.scale(pygame.image.load('images/you_died.jpg'), (1400,constants.SCREEN_HEIGHT)) #Loop until closed 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 input if event.type == pygame.QUIT: done = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: player.RunLeft() if event.key == pygame.K_RIGHT: player.RunRight() if event.key == pygame.K_SPACE: player.jump() if event.key == pygame.K_DOWN: player.Crouch() elif event.key == pygame.K_f: player.Attack() elif event.key == pygame.K_r: player.Shoot() if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT and player.change_x < 0: player.Idle() if event.key == pygame.K_RIGHT and player.change_x > 0: player.Idle() if event.key == pygame.K_f: player.Idle() if event.key == pygame.K_r: player.Idle() if event.key == pygame.K_DOWN: player.Idle() # Update the player active_sprite_list.update(screen) # Update items in the level current_level.update(screen) # If the player gets near the right side, shift the world left (-x) if player.rect.x >= 800: diff = player.rect.x - 800 if current_level.world_shift - size[0] >= current_level.level_limit: player.rect.x = 800 #Reset player to the middle current_level.shift_world(-diff) else: #Don't shift if player near right side of the screen current_level.shift_world(0) # If the player gets near the left side, shift the world right (+x) if player.rect.x < 800: diff = 800 - player.rect.x if current_level.world_shift < 0: player.rect.x = 800 #Reset player to the middle current_level.shift_world(diff) else: #Don't shift if player near left side of screen current_level.world_shift = 0 # If player hits the left or right screen if player.rect.left == 0: player.change_x = 0 player.rect.left = 0 if player.rect.right == size[0]: player.change_x = 0 player.rect.right = size[0] # Draw Everything current_level.draw(screen) active_sprite_list.draw(screen) # Limit to 60 frames per second clock.tick(60) # Update the screen with what we've drawn. pygame.display.flip() if player.Health() <= 0: if player.deathCount >= 34: done = True pygame.quit()
def runGame(): # create player # init Player player = Player() bullet = Bullet(player.rect.x, player.rect.y) level_list = [] level_list.append(levels.Level_01(player, bullet)) level_list.append(levels.Level_02(player, bullet)) # 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() active_sprite_list.add(bullet) bullets.add(bullet) player.rect.x = 340 player.rect.y = constants.SCREEN_HEIGHT - player.rect.height + 100 active_sprite_list.add(player) #-- 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() 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 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 # -- 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(): # Initialise Pygame pygame.mixer.pre_init(44100, -16, 1, 512) pygame.init() pygame.mixer.init() pygame.mixer.set_num_channels(16) # allow 16 sounds to be played at once screen_size = (constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT) screen = pygame.display.set_mode(screen_size, ) #pygame.FULLSCREEN) pygame.display.set_caption(constants.WIN_CAPTION) # Create Player class player = entities.Player() # Create all levels level_list = [] level_list.append(levels.Level_01(player)) # Hardcode curent level current_level = level_list[0] current_level.player_list.add(player) # Define player and entities player.rect.x = constants.SCREEN_WIDTH / 2 player.rect.y = constants.SCREEN_HEIGHT - player.rect.height * 2 player.level = current_level pistol = entities.Pistol(player) shotgun = entities.Shotgun(player) machete = entities.Machete(player) player.weapon_list = [shotgun, pistol, machete] player.current_weapon = shotgun current_level.player_list.add(shotgun) FPSCLOCK = pygame.time.Clock() game_running = True while game_running == True: # Event Handling for event in pygame.event.get(): if event.type == pygame.QUIT: constants.terminate() if event.type == pygame.KEYDOWN: if player.alive: # Movement/Actions 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_z: player.current_weapon.use_weapon() if event.key == pygame.K_r: player.current_weapon.reload() if event.key == pygame.K_x: player.throw_grenade() # Change Weapon if event.key == pygame.K_1: player.current_weapon = shotgun current_level.player_list.add(shotgun) current_level.player_list.remove(pistol) current_level.player_list.remove(machete) if event.key == pygame.K_2: player.current_weapon = pistol current_level.player_list.add(pistol) current_level.player_list.remove(machete) current_level.player_list.remove(shotgun) if event.key == pygame.K_3: player.current_weapon = machete current_level.player_list.add(machete) current_level.player_list.remove(pistol) current_level.player_list.remove(shotgun) # Quit Game if event.key == pygame.K_ESCAPE: game_running = False if event.type == pygame.KEYUP: if player.alive: if event.key == pygame.K_LEFT and player.x_vel < 0: player.stop() if event.key == pygame.K_RIGHT and player.x_vel > 0: player.stop() #update level current_level.update() current_position = player.rect.x + current_level.world_shift # Shift the world if the player is near the boundary if player.rect.right >= constants.right_boundary: diff = player.rect.right - constants.right_boundary player.rect.right = constants.right_boundary if current_position >= current_level.level_limit: current_level.shift_world(-diff) # If the player gets near the left side, shift the world right (+x) if player.rect.left <= constants.left_boundary: diff = constants.left_boundary - player.rect.left player.rect.left = constants.left_boundary if current_position <= -current_level.level_limit: current_level.shift_world(diff) # Draw current_level.render(screen) #current_level.draw_fps(screen, FPSCLOCK) FPSCLOCK.tick(constants.FPS) pygame.display.update() # Write score if quit current_level.write_score() constants.terminate()
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 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(): pygame.init() pygame.font.init() size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT] screen = pygame.display.set_mode(size) pygame.display.set_caption("BeaverTale") player = Player(100, 1) player2 = Player(100, 2) player2.attack = Stick level_list = [] level_list.append(levels.Level_01(player)) level_list.append(levels.Level_01(player2)) current_level_no = 0 current_level = level_list[current_level_no] items = pygame.sprite.Group() speed_items = pygame.sprite.Group() last_mushroom = time.time() last_speed = time.time() active_sprite_list = pygame.sprite.Group() player_projectiles = pygame.sprite.Group() player2_projectiles = pygame.sprite.Group() player_specs = pygame.sprite.Group() player2_specs = pygame.sprite.Group() player_portals = pygame.sprite.Group() player2_portals = pygame.sprite.Group() player.level = current_level player2.level = current_level player.rect.x = 1050 player.rect.y = constants.SCREEN_HEIGHT - player.rect.height player2.rect.x = 100 player2.rect.y = constants.SCREEN_HEIGHT - player2.rect.height active_sprite_list.add(player) active_sprite_list.add(player2) done = False clock = pygame.time.Clock() # Game Loop 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: if time.time() - player.last_shot > 1: if player.direction == "L": projectile = player.attack(-1) else: projectile = player.attack(1) # Set the bullet so it is where the player is projectile.rect.x = player.rect.x + 60 projectile.rect.y = player.rect.y + 30 if player.attack == Stick: projectile.rect.x = player.rect.x projectile.rect.y = player.rect.y - 10 # Add the bullet to the lists player_projectiles.add(projectile) player.last_shot = time.time() if event.key == pygame.K_RSHIFT: player_specs # if time.time() - player.last_spec > 0.1: # if player.direction == "L": # spec = Shuriken(-1, player) # else: # spec = Shuriken(1, player) # spec.rect.x = player.rect.x + 60 # spec.rect.y = player.rect.y + 30 # player_specs.add(spec) # player.last_spec = time.time() 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() # Player 2 code if event.type == pygame.KEYDOWN: if event.key == pygame.K_a: player2.go_left() if event.key == pygame.K_d: player2.go_right() if event.key == pygame.K_w: player2.jump() if event.key == pygame.K_q: if time.time() - player2.last_shot > 1: # Fire a bullet if the user clicks the mouse button if player2.direction == "L": projectile = player2.attack(-1) else: projectile = player2.attack(1) # Set the bullet so it is where the player is projectile.rect.x = player2.rect.x + 60 projectile.rect.y = player2.rect.y + 30 if player2.attack == Stick: projectile.rect.x = player2.rect.x projectile.rect.y = player2.rect.y - 10 elif player2.attack == MegaStick: projectile.rect.x = player2.rect.x - 40 projectile.rect.y = player2.rect.y - 100 # Add the bullet to the lists player2_projectiles.add(projectile) player2.last_shot = time.time() # Portal elif event.key == pygame.K_e and player2.can_portal: if player2.portal_up: if player2.direction == 1: start_portal = Portal(player2, player, 1, True, 5) end_portal = Portal(player2, player, -1, False, 5) else: start_portal = Portal(player2, player, -1, True, 5) end_portal = Portal(player2, player, 1, False, 5) player2_portals.add(start_portal) player2_portals.add(end_portal) player2.last_portal = time.time() player2.portal_up = False elif event.key == pygame.K_RSHIFT and player.can_portal: if player.portal_up: if player.direction == 1: start_portal = Portal(player, player2, 1, True, 5) end_portal = Portal(player, player2, -1, False, 5) else: start_portal = Portal(player, player2, -1, True, 5) end_portal = Portal(player, player2, 1, False, 5) player_portals.add(start_portal) player_portals.add(end_portal) player.last_portal = time.time() player.portal_up = False if event.type == pygame.KEYUP: if event.key == pygame.K_a and player2.change_x < 0: player2.stop() if event.key == pygame.K_d and player2.change_x > 0: player2.stop() # Add block collisions if pygame.sprite.spritecollide(player, player2_projectiles, True): player.health -= 10 if pygame.sprite.spritecollide(player, player2_projectiles, True): player.health -= 10 if pygame.sprite.spritecollide(player, player2_projectiles, True): player.health -= 10 if pygame.sprite.spritecollide(player2, player_projectiles, True): player2.health -= 10 if pygame.sprite.spritecollide(player2, player_specs, True): player2.health -= 40 if pygame.sprite.spritecollide(player, player2_specs, True): player.health -= 40 if pygame.sprite.spritecollide(player2, player2_portals, False): player2.rect.x = end_portal.rect.x + 50 player2.rect.y = end_portal.rect.y + 100 if pygame.sprite.spritecollide(player, player_portals, False): player.rect.x = end_portal.rect.x + 50 player.rect.y = end_portal.rect.y + 100 if pygame.sprite.groupcollide(player2_projectiles, player2_portals, True, False): void_projectile = MegaStick(1) void_projectile.rect.x = end_portal.rect.x + 50 void_projectile.rect.y = end_portal.rect.y + 50 player2_specs.add(void_projectile) if pygame.sprite.groupcollide(player_projectiles, player_portals, True, False): void_projectile = MegaStick(1) void_projectile.rect.x = end_portal.rect.x + 50 void_projectile.rect.y = end_portal.rect.y + 50 player_specs.add(void_projectile) for portal in player_portals: if not portal.active: player_portals.remove(portal) for portal in player2_portals: if not portal.active: player2_portals.remove(portal) if pygame.sprite.spritecollide(player, items, True): player.can_portal = True player.portal_up = True last_mushroom = time.time() if pygame.sprite.spritecollide(player2, items, True): player2.can_portal = True player2.portal_up = True last_mushroom = time.time() if pygame.sprite.spritecollide(player, speed_items, True): player.speed_mul += 0.2 last_speed = time.time() if pygame.sprite.spritecollide(player2, speed_items, True): player2.speed_mul += 0.2 last_speed = time.time() # if time.time() - player2.last_portal > 15: # player2.portal_up = True # if time.time() - player.last_portal > 15: # player.portal_up = True if time.time() - last_mushroom > 15 and not items: mushroom = Item("images/mushroom.png") rand = random.randint(0,1) if rand == 0: mushroom.rect.x = 750 mushroom.rect.y = 50 if rand == 1: mushroom.rect.x = 520 mushroom.rect.y = 530 items.add(mushroom) if time.time() - last_speed > 30 and not speed_items: speed = Item("images/speed.png") rand = random.randint(0,1) if rand == 0: speed.rect.x = 950 speed.rect.y = 400 if rand == 1: speed.rect.x = 50 speed.rect.y = 370 speed_items.add(speed) if player.health < 0: player.health = 0 player.lives -= 1 player.health = 100 player.rect.y = 600 player.rect.x = 1000 if player2.health < 0: player2.health = 0 player2.lives -= 1 player2.health = 100 player2.rect.y = 50 player_projectiles.update() player2_projectiles.update() player_specs.update() player2_specs.update() player_portals.update() player2_portals.update() active_sprite_list.update() current_level.update() current_level.draw(screen) player_portals.draw(screen) player2_portals.draw(screen) active_sprite_list.draw(screen) player_projectiles.draw(screen) player2_projectiles.draw(screen) player_specs.draw(screen) player2_specs.draw(screen) player.update_heart(screen, 1) player2.update_heart(screen, 2) if player.can_portal: player.update_portal(screen, 1) if player2.can_portal: player2.update_portal(screen, 2) items.draw(screen) speed_items.draw(screen) player.level.update_text(screen) 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 player2.health >= 66: player2.update_health(screen,(0, 255, 0)) elif player2.health >= 33: player2.update_health(screen,(255, 255, 0)) else: player2.update_health(screen,(255, 0, 0)) if player.lives <= 0: pygame.quit() if player2.lives <= 0: pygame.quit() clock.tick(60) pygame.display.flip() pygame.quit()
def main(): """ Main Program """ pygame.init() pygame.joystick.init() joystick1 = get_360_controller() # 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() # create container for fireballs fireballs = [] # 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: # allow the joystick to start listening if joystick1: #print("joystick1 enabled") joystick1.dispatch_events() 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_DOWN: player.go_down() if event.key == pygame.K_UP: player.go_up() 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_UP and player.change_y < 0: player.stop() if event.key == pygame.K_DOWN and player.change_y > 0: player.stop() # also check controller input if joystick1: if event.type == JOYAXISMOTION: #print('JOYAXISMOTION: axis {}, value {}'.format(e.axis, e.value)) if event.axis == 2: #left_trigger.value = event.value print("1") pass elif event.axis == 5: #right_trigger.value = event.value print("2") pass elif event.axis == 1 or event.axis == 0: # For smoother xbox 360 controls # left_right_on = False # up_down_on = False if event.axis == 1: # right and left motion if event.value > 0.2: player.go_right(speed=event.value*5) elif event.value < -0.2: player.go_left(speed=event.value*5) else: player.stop_left_right() # if event.value > 0.3: # player.go_right() # left_right_on = True # elif event.value < -0.3: # player.go_left() # left_right_on = True elif event.axis == 0: # up and down motion if event.value > 0.2: player.go_up(speed=-event.value*5) elif event.value < -0.2: player.go_down(speed=-event.value*5) else: player.stop_up_down() #print("event.value="+str(event.value*1)) # if event.value > 0.3: # player.go_up() # up_down_on = True # elif event.value < -0.3: # player.go_down() # up_down_on = True # # if not (left_right_on or up_down_on): # player.stop() # elif event.axis == 3: #right_stick.y = stick_center_snap(event.value * -1) pass elif event.axis == 4: #right_stick.x = stick_center_snap(event.value) pass elif event.type == JOYBUTTONDOWN: print("in JOYBUTTONDOWN") #print('JOYBUTTONDOWN: button {}'.format(e.button)) #buttons[event.button].value = 1 if event.button == 0: # jump active_sprite_list.add(player.shoot_fireball()) else: print("event.button == "+str(event.button)) elif event.type == JOYBUTTONUP: #print('JOYBUTTONUP: button {}'.format(e.button)) #buttons[event.button].value = 0 pass elif event.type == JOYHATMOTION: # pygame sends this; xinput sends a button instead--the handler converts the button to a hat event #print('JOYHATMOTION: joy {} hat {} value {}'.format(e.joy, e.hat, e.value)) # if which_hat: # hats[which_hat].value = 0 # if event.value != (0, 0): # which_hat = event.value # hats[which_hat].value = 1 pass elif event.type == KEYDOWN: if event.key == K_ESCAPE: quit() # 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 main(): """ Main Program """ pygame.init() multiplayer = False # Set the height and width of the screen size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT] screen = pygame.display.set_mode(size, pygame.FULLSCREEN) pygame.display.set_caption("Artnoc") #add in a scoreboard font = pygame.font.Font(None, 28) #player1 = Player() #player2 = Player() #enemy_list = [] #level_list = [] #level_list.append(levels.Level_01(player1, player2)) #current_level = level_list[0] #active_sprite_list = pygame.sprite.Group() #enemy_sprite_list = pygame.sprite.Group() #done = False #clock = pygame.time.Clock() play = False #----------MAIN MENU----------------- while True: multiplayer = mainMenu(screen, play, multiplayer) # Create the player1 player1 = Player() player2 = Player() enemy_list = [] powerup_list = [] # Create all the levels level_list = [] level_list.append(levels.Level_01(player1, player2)) # Set the current level current_level = level_list[0] for i in range(0, 3): enemy_list.append(Enemy(random.randint(0, 1))) enemy_list[i].level = current_level for i in range(0, 4): powerup_type = random.randint(2, 4) powerup_list.append(PowerUp(powerup_type)) powerup_list[i].level = current_level active_sprite_list = pygame.sprite.Group() enemy_sprite_list = pygame.sprite.Group() powerup_sprite_list = pygame.sprite.Group() player1.level = current_level if multiplayer == True: player2.level = current_level for i in range(0, 3): x = random.randint(constants.SCREEN_WIDTH, constants.SCREEN_WIDTH + 1) #y = random.randint(0,constants.SCREEN_HEIGHT-5) enemy_list[i].spawn(x, 0) enemy_sprite_list.add(enemy_list[i]) for i in range(0, 1): x = random.randint(0, 10000) powerup_list[i].spawn(x, 0) powerup_sprite_list.add(powerup_list[i]) player1.rect.x = 340 player1.rect.y = constants.SCREEN_HEIGHT - player1.rect.height active_sprite_list.add(player1) if multiplayer == True: player2.rect.x = 340 player2.rect.y = constants.SCREEN_HEIGHT - player2.rect.height active_sprite_list.add(player2) # Used to manage how fast the screen updates clock = pygame.time.Clock() play = True newpoweruplength = constants.SCREEN_WIDTH powerupflag = False #----------END MAIN MENU, START INITIALISATION------------- #init(multiplayer) # -------- Main Game Loop ----------- while (player1.lives > 0 and player2.lives > 0) and (play == True): for event in pygame.event.get(): # User did something if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: play = False if event.key == pygame.K_DOWN: player1.prone() if event.key == pygame.K_LEFT: player1.go_left() if event.key == pygame.K_RIGHT: player1.go_right() if event.key == pygame.K_UP: player1.aimup() if event.key == pygame.K_j: player1.jump() if event.key == pygame.K_k: player1.shoot() if event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT and player1.change_x > 0: player1.stop() if event.key == pygame.K_UP or event.key == pygame.K_DOWN: player1.resetaim() if event.key == pygame.K_LEFT and player1.change_x < 0: player1.stop() if event.key == pygame.K_k: player1.stopshooting() # if multiplayer == True: if event.type == pygame.KEYDOWN: if event.key == pygame.K_s: player2.prone() if event.key == pygame.K_a: player2.go_left() if event.key == pygame.K_d: player2.go_right() if event.key == pygame.K_w: player2.aimup() if event.key == pygame.K_1: player2.jump() if event.key == pygame.K_2: player2.shoot() if event.type == pygame.KEYUP: if event.key == pygame.K_d and player2.change_x > 0: player2.stop() if event.key == pygame.K_w or event.key == pygame.K_s: player2.resetaim() if event.key == pygame.K_a and player2.change_x < 0: player2.stop() if event.key == pygame.K_2: player2.stopshooting() # Update the player1. active_sprite_list.update(enemy_list) enemy_sprite_list.update(player1) powerup_sprite_list.update(player1) if multiplayer == True: enemy_sprite_list.update(player2) powerup_sprite_list.update(player2) #update the enemies #for enemy in levels.Level.enemy_list: # enemy.update() # Update items in the level current_level.update() # If the player1 gets near the right side, shift the world left (-x) if player1.rect.x >= 500: diff = player1.rect.x - 500 player1.rect.x = 500 current_level.shift_world(-diff) current_level.draw(screen) # If the player1 gets near the left side, shift the world right (+x) if player1.rect.x <= 120: diff = 120 - player1.rect.x player1.rect.x = 120 current_level.shift_world(diff) current_level.draw(screen) if multiplayer == True: if player2.rect.x >= 500: diff = player2.rect.x - 500 player2.rect.x = 500 current_level.shift_world(-diff) current_level.draw(screen) if player2.rect.x <= 120: diff = 120 - player2.rect.x player2.rect.x = 120 current_level.shift_world(diff) current_level.draw(screen) # If the player1 gets to the end of the level, go to the next level current_position = player1.rect.x + current_level.world_shift if current_position < current_level.level_limit: 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 if multiplayer == True: current_position = player2.rect.x + current_level.world_shift if current_position < current_level.level_limit: player2.rect.x = 120 if current_level_no < len(level_list) - 1: current_level_no += 1 current_level = level_list[current_level_no] player2.level = current_level # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT current_level.draw(screen) active_sprite_list.draw(screen) enemy_sprite_list.draw(screen) powerup_sprite_list.draw(screen) for x in enemy_sprite_list: if x.bullet_list != None: x.bullet_list.draw(screen) if multiplayer == True: if player1.dead == False and player2.dead == False: if player1.bullet_list != None: player1.bullet_list.draw(screen) if player2.bullet_list != None: player2.bullet_list.draw(screen) else: if player1.dead == False: if player1.bullet_list != None: player1.bullet_list.draw(screen) text = font.render("P1 Score = " + str(player1.score), 1, (constants.WHITE)) screen.blit(text, (0, 0)) if multiplayer == True: text = font.render("P2 Score = " + str(player2.score), 1, (constants.WHITE)) screen.blit(text, (0, 40)) text = font.render("Quit to Main Menu (Esc)", 1, constants.WHITE) screen.blit(text, (constants.SCREEN_WIDTH / 2 - 120, 0)) text = font.render("P1 Lives = " + str(player1.lives), 1, (constants.WHITE)) screen.blit(text, (constants.SCREEN_WIDTH - 115, 0)) if multiplayer == True: text = font.render("P2 Lives = " + str(player2.lives), 1, (constants.WHITE)) screen.blit(text, (constants.SCREEN_WIDTH - 115, 40)) # 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.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 main(): """ Main Program """ pygame.init() #Défini les dimensions size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT] #[nom_du_fichier.VARIABLE] screen = pygame.display.set_mode(size) #Titre de la fenetre pygame.display.set_caption("The pudi pudi quest") # Créer le joueur en important le fichier (voir importations) player = Player() enemies = Enemy() # Police font = pygame.font.SysFont("calibri", 48) # Créer les niveaux (listes) level_list = [] level_list.append(levels.Level_01(player)) # Met en player le niveau actuel current_level_no = 0 current_level = level_list[current_level_no] active_sprite_list = pygame.sprite.Group() player.level = current_level player.rect.x = 492 player.rect.y = 1342 active_sprite_list.add(player) enemies.rect.x = 300 enemies.rect.y = 600 active_sprite_list.add(enemies) #Relais permettant le maintien de la boucle tant que la variable est False gameExit = False # Temps du raffraichissement de l'écran (voir FPS) clock = pygame.time.Clock() score_text = font.render("Score: ", True, constants.WHITE) screen.blit(score_text, (5, 5)) #Musique d'ambiance pygame.mixer.music.load("data/sound/ambiance.mp3") pygame.mixer.music.play(-1) # -------- Programme : MAIN LOOP ----------- #Main while not gameExit: for event in pygame.event.get( ): # Quand l'utilisation fait quelque chose if event.type == pygame.QUIT: # Si il clique sur 'Fermer' gameExit = True # La variable relais prends la valeur True et permet la sortie #Quand l'utilisateur appuie sur une touche if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: # Touche echap gameExit = 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() #Quand l'utilisateur relâche la touche if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: player.stop() if event.key == pygame.K_RIGHT: player.stop() # Update le joueur active_sprite_list.update() # Affiche tous les items du niveau current_level.update() # Mvt caméra si le joueur va à droite (ici nul) if player.rect.x >= 0: #car on veut aucun décallage (sinon on met 500) diff = player.rect.x - 350 # on peut mettre (constants.SCREEN_WIDTH/2) player.rect.x = 350 # milieu de l'écran current_level.shift_world(-diff) # Mvt caméra si le joueur va à gauche (ici nul) if player.rect.x <= 0: diff = 350 - player.rect.x #(constants.SCREEN_WIDTH/2) player.rect.x = 350 #mileu de l'écran current_level.shift_world(diff) if player.rect.y <= 200: diff = player.rect.y - 350 player.rect.y = 350 currentb_level.shift_world_y(-diff) if player.rect.y >= 200: diff = 350 - player.rect.y #(constants.SCREEN_WIDTH/2) player.rect.y = 350 #mileu de l'écran current_level.shift_world_y(diff) # 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 # FPS : limités à 60 FPS = constants.FPS clock.tick(FPS) # Update pygame de tout se qu'on a écrit pygame.display.flip() # Sortie du programme 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(): 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 """ pg.init() #============================================================================== """Define o Tamano da Janela do Game:""" icon = pg.image.load("Fotos\SatanIcon.png") pg.display.set_caption("Satan's Wolrd Hero") pg.display.set_icon(icon) size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT] screen = pg.display.set_mode(size) """Coloca a tela na posiçao desejada do monitor""" os.environ["SDL_VIDEO_WINDOW_POS"] = '100,30' screen = pg.display.set_mode((1, 1)) #============================================================================== pg.mouse.set_visible(0) #Deixa o mouse imvisivel #============================================================================== """Define o icone e nome do Jogo""" #============================================================================== """Carrega o Jogar, Inimigos e Fases""" player1 = personagens.MrSatan() boss1 = enemy.Cell() #============================================================================== # Enemys #============================================================================== enemys_list =[[enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))], [enemy.Cell_Jr(),random.choice(range(-200,2400)),constants.SCREEN_HEIGHT, random.choice(range(0,100))]] backup_enemys_list = enemys_list[:] level_list = [] enemy_l=[] backup_enemy_l = [] backup_enemy = [] backup_boss = [] for inimigo in enemys_list: Enemy = inimigo[0] Enemy.rect.x = inimigo[1] Enemy.Muda_Rota = inimigo[3] Enemy.rect.y = inimigo[2] - Enemy.rect.height - Enemy.Muda_Rota level_list.append(levels.Level_01(player1,Enemy,boss1)) enemy_l.append(Enemy) backup_enemy_l = enemy_l[:] #============================================================================== """Iniciaiza o Joystick""" pg.joystick.init() if pg.joystick.get_count()> 0: joystick = pg.joystick.Joystick(0) joystick.init() #============================================================================== """Seleciona o level Inicial e Define a Posiçao o player e dos inimigos na tela""" current_level_no = 0 current_level = level_list[current_level_no] #============================================================================== # Cria as listas de Sprites #============================================================================== player1_list = pg.sprite.Group() enemy_list = pg.sprite.Group() boss_list = pg.sprite.Group() #============================================================================== # Define a Posiçao inicial #============================================================================== """Player""" player1.level = current_level player1.rect.x = -200 player1.Muda_Rota = 20 player1.rect.y = constants.SCREEN_HEIGHT - player1.rect.height - player1.Muda_Rota player1_list.add(player1) """Boss""" boss1.level = current_level boss1.rect.x = constants.SCREEN_WIDTH+100 boss1.rect.y = constants.SCREEN_HEIGHT - boss1.rect.height - player1.Muda_Rota boss_list.add(boss1) backup_boss = boss_list.copy() """Enemy""" for Enemy in enemy_l: Enemy.level = current_level enemy_list.add(Enemy) backup_enemy = enemy_list.copy() #============================================================================== # Used to manage how fast the screen updates clock = pg.time.Clock() Regen = pygame.USEREVENT + 1 Boss_Action = pygame.USEREVENT + 2 Boss_Sub_Action = pygame.USEREVENT + 3 pg.time.set_timer(Regen,50) pg.time.set_timer(Boss_Action,1000) pg.time.set_timer(Boss_Sub_Action,500) pg.time.set_timer(pygame.USEREVENT + 4,5000) levels.Start_Screen() levels.Music_play(0) #============================================================================== """Main Loop""" while not constants.Game_loop: #============================================================================== #============================================================================== """Joystck Configuration""" #============================================================================== # Recebe valor real entre (-1) e (1) para o analógico esquerdo no eixo horizontal, onde (0) é parado if pg.joystick.get_count() >0: axis_lh = joystick.get_axis(0) # Recebe valor real entre (-1) e (1) para o analógico esquerdo no eixo vertical, onde (0) é parado axis_lv = joystick.get_axis(1) # Recebe valor inteiro de (-1) e (1) para os botões direcionais, onde (0) é parado hat = joystick.get_hat(0) #============================================================================== #============================================================================== # Comfiguraçoes teclado: #============================================================================== for event in pg.event.get(): if event.type == pg.QUIT: constants.Game_loop = True pressed = pg.key.get_pressed() if (pressed[pg.K_LALT] and pressed[pg.K_F4]) or (pressed[pg.K_RALT] and pressed[pg.K_F4]): pg.quit() pg.key.set_repeat(10,20) if pressed[pg.K_UP]: player1.Muda_Rota_Sup() if pressed[pg.K_DOWN]: player1.Muda_Rota_Inf() if event.type == pg.KEYDOWN: if event.key == pg.K_LEFT: if player1.State('move') and not constants.game_start: player1.go_left() if event.key == pg.K_RIGHT: if player1.State('move') and not constants.game_start: player1.go_right() if event.key == pg.K_z: if player1.State('punch') and not constants.game_start: player1.Soco_1() if event.key == pg.K_x: if player1.State('kick') and not constants.game_start: player1.Chute_1() if event.key == pg.K_c: if player1.State('jump') and not constants.game_start: player1.Jump() if event.key == pg.K_v: if player1.State('defending') and not constants.game_start: player1.Defesa() if event.key == pg.K_RETURN: if not player1.com and not constants.reset: pygame.mixer.music.pause() levels.Pause() if event.type == pg.KEYUP: if event.key == pg.K_LEFT and player1.change_x < 0: player1.stop() if event.key == pg.K_RIGHT and player1.change_x > 0: player1.stop() if event.key == pg.K_v: player1.stop() if event.type == Regen: player1.healt_regen() player1.Mp_regen() #============================================================================== #Enemy: #============================================================================== for Enemy in enemy_l: if event.type == pygame.USEREVENT + 4: Enemy.ml = False if event.type == Boss_Action: Enemy.boss_action() if event.type == Boss_Sub_Action: Enemy.sub_action() if not Enemy.live: if constants.delay_dead > 85: constants.delay_dead = 0 enemy_list.remove(Enemy) enemy_l.remove(Enemy) else: constants.delay_dead += 1 #============================================================================== # Boss: #============================================================================== if event.type == Boss_Action: boss1.boss_action() if event.type == Boss_Sub_Action: boss1.sub_action() if not boss1.live: if constants.delay_dead > 85: constants.delay_dead = 0 boss_list.remove(boss1) else: constants.delay_dead += 1 #============================================================================== #============================================================================== """Configuraçoes dos botoes do controle""" #============================================================================== if pg.joystick.get_count()>0: # Direcional ou Analógico esquerdo para a esquerda if (hat == ((-1,0) or (-1,1) or (-1,-1))) or axis_lh <= -0.5: if player1.State('move') and not constants.game_start: player1.go_left() # Direcional ou Analógico esquerdo para a direita if (hat == ((1,0) or (1,1) or (1,-1))) or axis_lh >= 0.5: if player1.State('move') and not constants.game_start: player1.go_right() if (hat == ((0,1) or (1,1) or (-1,1))) or axis_lv <= -0.5: if player1.State('move') and not constants.game_start: player1.Muda_Rota_Sup() if (hat == ((0,-1) or (1,-1) or (-1,-1))) or axis_lv >= 0.5: if player1.State('move') and not constants.game_start: player1.Muda_Rota_Inf() # Direcional ou Analógico esquerdo parados if (hat == ((0,0) or (0,1) or (0,-1)) and (-0.5 < axis_lh < 0.5)) and (player1.change_x != 0): player1.stop() if event.type == pg.JOYBUTTONDOWN: if event.button == 2: # Botão X pressionado if player1.State('jump') and not constants.game_start: player1.Jump() if event.button == 1: # Botão CIRCULO pressionado if player1.State('kick') and not constants.game_start: player1.Chute_1() if event.button == 3: # Botão QUADRADO pressionado if player1.State('punch') and not constants.game_start: player1.Soco_1() if event.button == 5: # Botão R1 pressionado if player1.State('defending') and not constants.game_start: player1.Defesa() if event.button == 9: if not player1.com and not constants.reset and not constants.game_start: pygame.mixer.music.pause() levels.Pause() if event.type == pg.JOYBUTTONUP: if event.button == 5: player1.stop() # Botao R1 # if button_L1: # Botão L1 pressionado # # else: # Botão L1 solto # # if button_L2: # Botão L2 pressionado # # if button_R1: # Botão R1 pressionado # # if button_R2: # Botão R2 pressionado # # if button_start: # Botão START pressionado #============================================================================== #============================================================================== """ Realiza af funçoes necessarias para relizar ad achoes no game""" #============================================================================== for Enemy in enemy_l: if not constants.game_start: collide.check_colide(player1,Enemy) Enemy.ai(player1) if len(enemy_list)<10: collide.check_colide(player1,boss1) boss1.ai(player1) if constants.Pause: pygame.mixer.music.unpause() if constants.reset: levels.Music_play(0) constants.i = 0 constants.d = 0 constants.s = 0 constants.teste = 0 player1.rect.x +=1 player1.com = False enemys_list = backup_enemys_list [:] enemy_l = backup_enemy_l[:] enemy_list.remove() enemy_list = backup_enemy.copy() boss_list.remove() boss_list = backup_boss.copy() for i,Enemy in enumerate(enemy_l): Enemy.Re_life(enemys_list[i][1],enemys_list[i][2],enemys_list[i][3]) constants.reset = False player1_list.update() enemy_list.update() if len(enemy_list)<10: boss_list.update() current_level.update() #============================================================================== """Define a posiçao da tela em relaçao ao cenario""" current_position = player1.rect.x + abs(current_level.world_shift) if current_position > 200 and current_position < 2000 and current_level_no != 1: if player1.rect.right >= 800: diff = player1.rect.right - 800 player1.rect.right = 800 boss1.rect.left -= diff for Enemy in enemy_l: Enemy.rect.right -= diff current_level.shift_world(-diff) if player1.rect.left <= 200: diff = 200 - player1.rect.left player1.rect.left = 200 boss1.rect.left += diff for Enemy in enemy_l: Enemy.rect.left += diff current_level.shift_world(diff) #============================================================================== """Desenha tudo o que aparece na tela""" #============================================================================== current_level.draw(screen) #Desenha a fase #Desenha os Inimigo enemy_list.draw(screen) for Enemy in enemy_l: if Enemy.ml: Enemy.enemy_hud(screen) #Desenha o boss if len(enemy_list)<10: boss_list.draw(screen) boss1.boss_hud(screen) if constants.i==0: pygame.mixer.music.stop() constants.i = 1 if constants.d == 0: levels.Music_play(1) constants.d = 1 #Desenha o Player player1_list.draw(screen) player1.player_hud(screen) if not player1.live and player1.Lives == 0: player.dead_screen(screen,player1,current_position) pygame.mixer.music.stop() if len(enemy_l) == 0 and not boss_list.has(boss1): player.Stage_Clear(screen,player1) player1.stop() player1.Vitoria() if constants.game_clear: player.Game_Clear(screen,player1,current_position) if constants.game_start: player.Game_Start(screen,player1) #============================================================================== clock.tick(constants.FPS) pg.display.flip() pg.quit()
elif pos[1] >= constants.EXIT_GAME[1][0] and pos[ 1] <= constants.EXIT_GAME[1][1]: pygame.quit() pygame.mixer.music.stop() screen = pygame.display.set_mode([constants.MENU_SIZE, constants.SCREEN_SIZE]) pygame.display.set_caption('Adventures of Manuel (by gNrg)') # Hide the mouse cursor pygame.mouse.set_visible(0) # Player player = Manolito() # 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] # Sprites sprites = pygame.sprite.Group() sprites.add(player) current_level.set_player_position(current_level.posx, current_level.posy) # Music & sounds pygame.mixer.music.load("Sounds/levels.mp3") pygame.mixer.music.play(-1) manolito_shot_sound = pygame.mixer.Sound("Sounds/manolitosShot.ogg")
def main(): """ Main Program """ pygame.init() # -------------- Screen Settings ---------------- # Set the height and width of the screen size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT] screen = pygame.display.set_mode(size) # Top of window caption pygame.display.set_caption("Muffin Knight Clone") # ----------------- Scores + Players ------------------- # Create the player player_one = Player(constants.PLAYER_ONE_AT) player_two = Player(constants.PLAYER_TWO_AT) # Scores player_one_score = 0 player_two_score = 0 p1_old_score = -1 p2_old_score = -1 # ---------------- Level Assignment --------------- # Create all the levels level_list = [] level_list.append(levels.Level_01(player_one, player_two)) # Set the current level current_level_no = 0 current_level = level_list[current_level_no] # ----------------- Create Sprite Groups ------------------- # Create list of players sprites active_sprite_list = pygame.sprite.Group() # Create list of scores sprites scores_list = pygame.sprite.Group() # Group that only contains scoreboard scoreboard_list = pygame.sprite.GroupSingle() # --------------- Assign Player Attributes -------------- # Set the players levels player_one.level = current_level player_two.level = current_level # Set the player locations player_one.rect.x = 100 player_two.rect.x = 1100 player_one.rect.y = 865 - player_one.rect.height player_two.rect.y = 865 - player_two.rect.height # Add players to their sprite list active_sprite_list.add(player_one) active_sprite_list.add(player_two) # ----------------- Scoreboard ----------------- # Create the scoreboard frame and add to it's sprite list scoreboard = score.Scoreboard() scoreboard_list.add(scoreboard) # ------------------- Timing -------------------- # Used to manage how fast the screen updates clock = pygame.time.Clock() # Player 1 time between bullets p1_bullet_time = time.time() # Payer 2 time between bullets p2_bullet_time = time.time() # ---------------- Sounds -------------------- # Load backround music music = pygame.mixer.music.load('music.mid') # Backround music loop pygame.mixer.music.play(-1) # -------- MAIN PROGRAM LOOP ----------- done = False #Loop until the user hits backspace while not done: # ---------- Player Controls ------------ 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: # Player One controls if event.key == pygame.K_a: player_one.go_left() if event.key == pygame.K_d: player_one.go_right() if event.key == pygame.K_w: player_one.jump() if event.key == pygame.K_SPACE: p1_temp_btime = time.time() if (p1_temp_btime - p1_bullet_time) >= .5: bullet = weapons.Bullet(player_one) current_level.bullet_list.add(bullet) p1_bullet_time = p1_temp_btime # Player Two controls if event.key == pygame.K_LEFT: player_two.go_left() if event.key == pygame.K_RIGHT: player_two.go_right() if event.key == pygame.K_UP: player_two.jump() if event.key == pygame.K_KP0: p2_temp_btime = time.time() if (p2_temp_btime - p2_bullet_time) >= .5: bullet = weapons.Bullet(player_two) current_level.bullet_list.add(bullet) p2_bullet_time = p2_temp_btime # Quit game if event.key == pygame.K_ESCAPE: done = True if event.type == pygame.KEYUP: # Player One controls if event.key == pygame.K_a and player_one.change_x < 0: player_one.stop() if event.key == pygame.K_d and player_one.change_x > 0: player_one.stop() # Player Two controls if event.key == pygame.K_LEFT and player_two.change_x < 0: player_two.stop() if event.key == pygame.K_RIGHT and player_two.change_x > 0: player_two.stop() # --------------- Updates ----------------- # Update the player current_level.update() active_sprite_list.update() # Update items in the level (for moving platforms) #current_level.update() # ------------------- Check For Stun ------------------ for player in active_sprite_list: player_stun_list = pygame.sprite.spritecollide( player, current_level.bullet_list, False) # If player is hit by a bullet if player_stun_list: if player.pname != player_stun_list[0].player_name: if player.stunned == False: player.stun_wait = time.time() # Check if the player has cooled down since last stun if player.stun_wait - player.stun_start >= 5: player.stunned = True player.stunned_direction = player.direction player.stun_start = time.time() # ------------ Check If Player Is Hit By Enemy --------- hit_players = pygame.sprite.groupcollide(active_sprite_list, current_level.enemy_list, False, False) for hit_player in hit_players: # Send player to respawn point hit_player.rect.x = 585 hit_player.rect.y = 100 # Remove a life and point from hit player hit_player.lives -= 1 if hit_player.pname == 'p1': player_one_score -= 1 else: player_two_score -= 1 # Need to add a delay and explosion class # ----------- Check If Players Are Off Map ---------- for guy in active_sprite_list: if guy.rect.y > constants.SCREEN_HEIGHT: # Move to the top middle platform guy.rect.x = 585 guy.rect.y = 100 # Minus a life guy.lives -= 1 # Lose five points for falling death if guy.pname == 'p1': player_one_score -= 5 else: player_two_score -= 5 # -------------- Bullet Impacts ------------ # Lists of bullet impacts for bullet in current_level.bullet_list: bullet_hit_list = pygame.sprite.spritecollide( bullet, current_level.enemy_list, False) for enemy in bullet_hit_list: enemy.health -= 1 if enemy.health <= 0: # Create explosion instance here enemy.kill() if bullet.player_name == 'p1': player_one_score += 1 else: player_two_score += 1 bullet.kill() # Create an explosion in dead enemy's place #for enemy in enemy_explode: # explosion = explosions.WalkerExplosion() # explosion_list.add(explosion) bullet_wall_hit = pygame.sprite.groupcollide( level_list[0].bullet_list, current_level.platform_list, True, False) # ------------ Scoreboard Display ------------ # Set score to zero if it's negative if player_one_score < 0: player_one_score = 0 elif player_two_score < 0: player_two_score = 0 # Used to decide if score had changed if player_one_score != p1_old_score or player_two_score != p2_old_score: p1_old_score = player_one_score p2_old_score = player_two_score #Removes old scores from list scores_list.empty() # Returns images of player one's score new_score = scoreboard.display_score(player_one_score, 1) # Add player one's scores to list scores_list.add(new_score[0]) scores_list.add(new_score[1]) # Return images of player two's score new_score = scoreboard.display_score(player_two_score, 0) # Adds player two's score to list scores_list.add(new_score[0]) scores_list.add(new_score[1]) # --------------- Draw To Display --------------- # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT current_level.draw(screen) scoreboard_list.draw(screen) scores_list.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() if player_one_score >= 20: print 'PLAYER ONE WINS!!' done = True elif player_two_score >= 20: print 'PLAYER TWO WINS!!' done = True # Be IDLE friendly. If you forget this line, the program will 'hang' # on exit. pygame.quit()
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(): """ Main Program First initializes pygame and pygame.mixer variables: size: The size of the window screen: Sets the display for the game player: The player object title: The title itself butOne: The start button butTwo: Load game (didn't implement) hubLevel: Where the player begins and is able to choose other levels golBossLev: The golem boss skeBossLev: The skeleton boss magBosLev: The magma boss level_list: Holds the levels in a list TwoBut: Holds the starting buttons menuSelect: determins which button is currently selected cover: Used for transitions backTitle: background for the title current_level_no: The number of the current level the player is in current_level: The current level the player is in active_sprite_list: Used to hold the player sprite slash: Holds the melee sprite bullets: Holds the bullet sprites beampew: Holds the laser sprite begin: Holds sprites needed for the titlescreen beginBack: Holds the background for the title transition: Holds the sprite that covers the screen during transition winMes: Holds the win message hugLeft: True if player is moving left so they can cling to the wall hugRight: True if player is moving right so they can cling to the wall done: True if player wants to quit and exit the game toIntro: True when player leaves the titlescreen to the game or quit the application count2: Used to determine how long the melee attack will stay on screen attack: True if player wants to melee attack linger: Allows the melee attack to stay on screen laser: True if player wants to laser attack clock: Used to manage how fast the screen updates canSelect: Allows player to select the starting buttons ToNextPart: True when player presses the start button to get to the game canMove = Allows player to move in game canUpdate = Allows game to update most assets canChange = Allows player to change level fading = True if the game is in the process of a transition aboutToFade = True when the player hits a point to begin transition worldChosen = The level the player chose xLimR = Limits level layout to the right xLimL = Limits level layout to the left Functions: Reset: resets the levels after player loses or lears it While loops: First loop: The title loop Second loop: The main game loop """ pygame.init() pygame.mixer.init() # Set the height and width of the screen size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT] screen = pygame.display.set_mode(size) #Sets the title pygame.display.set_caption("Doki Doki Island!") # Create the player player = Player() #Creates the title screen title = Title.Start() butOne = But1.Start() butTwo = But2.Start() # Create all the levels hubLevel = levels.Level_00(player, screen) hubLevel2 = levels.Level_01(player, screen) hubLevel3 = levels.Level_01(player, screen) golBossLev = levels.Level_04(player, screen) skeBossLev = levels.Level_03(player, screen) magBossLev = levels.Level_05(player, screen) # Appends the levels to the list level_list = [] level_list.append(hubLevel) level_list.append(hubLevel2) level_list.append(hubLevel3) '''level_list.append(golBossLev)''' '''level_list.append(skeBossLev)''' '''level_list.append(magBossLev)''' # To hold the title buttons Twobut = [] menuSelect = 0 #Used during transitions, fades screen black cover = black.Fade(screen) #Sets the background in the title screen backTitle = backgroundTitle.Start() # Set the current level current_level_no = 0 current_level = level_list[current_level_no] # All relevant groups for sprites to be used in the game active_sprite_list = pygame.sprite.Group() slash = pygame.sprite.Group() bullets = pygame.sprite.Group() beampew = pygame.sprite.Group() begin = pygame.sprite.Group() beginBack = pygame.sprite.Group() transition = pygame.sprite.Group() winMes = pygame.sprite.Group() # Starts the player off in the hub level player.level = current_level player.bullets = bullets # this is to place the character player.rect.x = 200 player.rect.y = 350 active_sprite_list.add(player) #Adds these to their relevant groups begin.add(title) beginBack.add(backTitle) transition.add(cover) #Used when player hugs a wall hugLeft = False; hugRight = False; # Loop until the user clicks the close button. done = False toIntro = False count2 = 0 attack = False linger = False laser = False # Used to manage how fast the screen updates clock = pygame.time.Clock() #Loads the first music file, the title screen music """pygame.mixer.music.load('RabiRabiMain.ogg') pygame.mixer.music.play(-1, 0.0) """ # Used when selecting the buttons on title screen canSelect = False toNextPart = False #----- Title screen ------- while not toIntro: for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done = True toIntro = True if event.type == pygame.KEYDOWN and canSelect: if event.key == pygame.K_LEFT: #When use press left key, it selects the left button if menuSelect == 1: menuSelect = 0 butOne.highlighted = True butTwo.highlighted = False if event.key == pygame.K_RIGHT: #When use press right key, it selects the right button if menuSelect == 0: menuSelect = 1 butTwo.highlighted = True butOne.highlighted = False if event.key == pygame.K_SPACE: #When use press space key, it selects the button if menuSelect == 1: print('1') if menuSelect == 0: butOne.selected = True if event.type == pygame.KEYUP and canSelect: if event.key == pygame.K_SPACE: #When player releases space key, then the button chosen will do its action if menuSelect == 1: #Meant for a load file button, but didn't get around to it print('lol') if menuSelect == 0: butOne.selected = False #fade out black, then to main game cover.inout = True cover.go = True toNextPart = True canSelect = False #pygame.mixer.music.fadeout(1000) screen.fill(constants.BLUE) #Updates and draws the relevant groups for the title screen beginBack.update() begin.update() transition.update() beginBack.draw(screen) begin.draw(screen) transition.draw(screen) #Intially, 'cover' will be black. This is to stop the transition once the title screen can be seen if cover.time < 0 and cover.go: cover.go = False cover.time = 0 #After the title finishes bouncing, the two buttons are added if title.change_y == 0 and len(begin) <= 1: begin.add(butOne) begin.add(butTwo) Twobut.append(butOne) Twobut.append(butTwo) #This to intially highlight the first button once the buttons stop moving if butOne.change_y >= 0 and butTwo.change_y >= 0 and not canSelect: butOne.highlighted = True canSelect = True #When the uer chooses an option, the screen will fade and break from the loop, then onto the game if toNextPart and cover.inout and cover.time >= 255: toIntro = True clock.tick(60) pygame.display.flip() #Variables used for various functions in the game canMove = True canUpdate = True canChange = False fading = False aboutToFade = True worldChosen = 0 previousWorld = 0 bossLev = False hubLev = True xLimR = True xLimL = True #Resets the levels so the player can play them again if they go back to the specific level def reset(player, screen, level_list, worldChosen): print(current_level.getOriX()) if worldChosen == 0: current_level.resetHub(current_level.level_x_limit, current_level.level_y_limit) elif worldChosen == 1: current_level.resetHub(current_level.level_x_limit, current_level.level_y_limit) player.rect.x = 600 elif worldChosen == 3: #hubLevel = levels.Level_00(player, screen) golBossLev = levels.Level_04(player, screen) if len(level_list) < 4: level_list.append(golBossLev) #level_list[0] = hubLevel else: level_list[3] = golBossLev player.rect.x = 200 player.rect.y = 350 # -------- Main Game Loop ----------- while not done: for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done = True # Flag that we are done so we exit this loop if event.type == pygame.KEYDOWN and not player.hurt: if event.key == pygame.K_LEFT: #Moves the player left if canMove: player.go_left() hugLeft = True hugRight = False player.direction = 'l' if event.key == pygame.K_RIGHT: #Moves the player right if canMove: player.go_right() hugRight = True hugLeft = False player.direction = 'r' if event.key == pygame.K_UP: #Makes player jump if canMove: player.jump(hugRight, hugLeft) if event.key == pygame.K_DOWN: #Makes player crouch if canMove: player.crouch() if event.key == pygame.K_y: #Allows player to melee attack if canMove: attack = True if event.key == pygame.K_w: #Allows player to shoot if canMove: shot = Shooter(player) shot.level = current_level bullets.add(shot) if event.key == pygame.K_i: #Allows player to fire the laser if canMove: laser = True if event.key == pygame.K_o: #Allows player to fire the wave shot if canMove: waveshot = Wave(player, 1) waveshot2 = Wave(player, -1) bullets.add(waveshot) bullets.add(waveshot2) if event.type == pygame.KEYUP and not player.hurt: #When player releases left key, stops moving if event.key == pygame.K_LEFT and player.change_x < 0: player.stop() hugLeft = False if event.key == pygame.K_RIGHT and player.change_x > 0: #When player releases right key, stops moving player.stop() hugRight = False '''if event.key == pygame.K_DOWN: #When player releases down key, makes player stand up if canMove: player.stand()''' if event.key == pygame.K_i: beampew.empty() #checks what level the player is in and if music isn't pkaying at the moment and plays the appropriate song """ if current_level_no == 0 and not pygame.mixer.music.get_busy(): pygame.mixer.music.load('RabiRabiHub.ogg') pygame.mixer.music.play(-1, 0.0) elif current_level_no == 1 and not pygame.mixer.music.get_busy(): pygame.mixer.music.load('RabiRabiRavine.ogg') pygame.mixer.music.play(-1, 0.0) elif current_level_no == 2 and not pygame.mixer.music.get_busy(): pygame.mixer.music.load('RabiRabiPandora.ogg') pygame.mixer.music.play(-1, 0.0) elif current_level_no == 3 and not pygame.mixer.music.get_busy(): pygame.mixer.music.load('RabiRabiVolcano.ogg') pygame.mixer.music.play(-1, 0.0) """ #When player wins, creates the 'clear' that falls down from the top if player.winner: player.winner = False win = winning.win() winMes.add(win) bullets.empty() beampew.empty() #When the 'clear' is gone, it begins transition if len(winMes) > 0: for winThi in winMes: if winThi.rect.y >= constants.SCREEN_HEIGHT: winMes.empty() aboutToFade = True worldChosen = previousWorld #If player is dead, begin transition if player.dead: aboutToFade = True worldChosen = previousWorld #Sets the variables before transitioning if aboutToFade and not fading: cover.go = True canMove = False canUpdate = False fading = True if cover.inout: cover.inout = False else: cover.inout = True #pygame.mixer.music.fadeout(800) #If true, allows to update the relevant game assets if canUpdate: active_sprite_list.update(hugRight, hugLeft) current_level.update() bullets.update(bullets) beampew.update(player) winMes.update() """ if attack == True: swipe = Hammer(player) slash.add(swipe) linger = True if linger == True: slash.update() count2 += 1 if count2 == 5: slash.empty() count2 = 0 linger = False if laser == True: beam = Laser(player) beampew.add(beam) laser = False """ #Used to determine if player is close to an edge of a level toTheRight = player.rect.x + current_level.world_shift toTheLeft = player.rect.x + current_level.left_x #Sets the relevant variables when player reaches an edge from the right or the left if toTheRight < current_level.level_x_limit: xLimR = False if toTheLeft <= 450: xLimL = False # If the player gets near the right side, shift the world left (-x) # Wont shift if in boss level if player.rect.x >= 550 and not player.bossChange and xLimR: diff = player.rect.x - 550 player.rect.x = 550 current_level.shift_world(-diff) xLimL = True # If the player gets near the left side, shift the world right (+x) # Wont shift if in boss level if player.rect.x <= 450 and not player.bossChange and xLimL: diff = 450 - player.rect.x player.rect.x = 450 current_level.shift_world(diff) xLimR = True # if player is jumping up, shift the world up when appropriate # Wont shift if in boss level if player.rect.y <= 150 and not player.bossChange: diff = 150 - player.rect.y player.rect.y = 150 current_level.shift_worldY(diff) # if player is falling, shift world down when appropriate # Wont shift if in boss level if player.rect.y >= 500 and not player.bossChange: diff = player.rect.y - 500 player.rect.y = 500 current_level.shift_worldY(-diff) # When a player chose a portal, will transport player to appropriate level playerChose = pygame.sprite.spritecollide(player, current_level.platform_choose, False) if len(playerChose) > 0 and not aboutToFade: aboutToFade = True for chosen in playerChose: worldChosen = chosen.choice if worldChosen < 2: previousWorld = worldChosen print(worldChosen) #if true, changes the level if canChange: canChange = False print(worldChosen) if worldChosen < 2: hubLev = True bossLev = False else: bossLev = True hubLev = False #Checks player's current level and then transports to the approprate level if bossLev: reset(player, screen, level_list, worldChosen) current_level_no = worldChosen current_level = level_list[current_level_no] elif hubLev: current_level_no = worldChosen current_level = level_list[current_level_no] reset(player, screen, level_list, worldChosen) player.level = current_level # Checks if player is in a boss level if bossLev: player.bossTime = True # Draws the sprites current_level.draw(screen) active_sprite_list.draw(screen) slash.draw(screen) bullets.draw(screen) beampew.draw(screen) winMes.draw(screen) #When the transition is fully finished, it sets the variables if cover.time <= 0 and not cover.inout and cover.go: cover.go = False fading = False aboutToFade = False canMove = True canUpdate = True #As the screen is fully black, sets the variables if cover.time >= 255 and cover.inout and cover.go: cover.inout = False canChange = True player.hp = 100 player.dead = False player.bossTime = False #If the player's last level was a boss level, sets these variables if bossLev: player.bossTime = False player.bossChange = False player.normalChange = True player.hurtCounter = 0 '''player.rect.y = 450''' active_sprite_list.update(hugRight, hugLeft) active_sprite_list.draw(screen) #If the player's last level was the hub level, sets these variables else: player.bossTime = True print("yo") active_sprite_list.update(hugRight, hugLeft) active_sprite_list.draw(screen) # if true, does the transition if fading: transition.update() transition.draw(screen) #For hammer, prevents multiple melee attacks in one spot #attack = False # Limit to 60 frames per second clock.tick(60) # Go ahead and update the screen with what we've drawn. pygame.display.flip() # Be IDLE friendly. If you forget this line, the program will 'hang' # on exit. pygame.quit()
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(): # 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(): 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() # 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 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("Platformer with sprite sheets") # 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.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) # 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() # 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 main(): """ Main function for the game. """ pygame.init() # set width, height of screen size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT] screen = pygame.display.set_mode(size) pygame.display.init() pygame.display.set_caption("Game of Badassdom") player = Player() level_list = [] level_list.append(levels.Level_01(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) bullet_list = pygame.sprite.Group() # loop until user clicks close button done = False clock = pygame.time.Clock() # --- Main Program Loop --- 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: bullet = Bullet() bullet.rect.x = player.rect.x bullet.rect.y = player.rect.y active_sprite_list.add(bullet) bullet_list.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() active_sprite_list.update() current_level.update() current_level.draw_tiles(0, 0, screen) active_sprite_list.draw(screen) clock.tick(60) pygame.display.flip() pygame.quit()