def bomba_explotar(self, bomba, celda, nivel_explosion): """ Función que utilizan las bombas para esparcir sus explosiones por el mapa. Devuelve None """ self.liberar_bomba(bomba) movs = [(0, 1), (-1, 0), (0, -1), (1, 0)] nivel_exp_actual = nivel_explosion explosion = Explosion(self.em, celda, self) self.explosiones.append(explosion) for mov in movs: nivel_exp_actual = nivel_explosion celda_actual = celda bloque = False while nivel_exp_actual != 0 and not bloque: celda_tentativa = self.get_celda(celda_actual.fila + mov[0], celda_actual.columna + mov[1]) if celda_tentativa.comprobar_mov(): # Se genere explosion explosion = Explosion(self.em, celda_tentativa, self) self.explosiones.append(explosion) celda_actual = celda_tentativa else: # Se explote pero no se genere celda_tentativa.ser_explotado() bloque = True nivel_exp_actual -= 1
def ship_hit(ai_settings, screen, stats, sb, ship, aliens, bullets, alienbullets, explosions, ufos): # Respond to ship being hit by alien explosion = Explosion(ai_settings, screen, False, False) explosion.x = ship.rect.x explosion.rect.x = ship.rect.x explosion.rect.y = ship.rect.y explosions.add(explosion) if stats.ships_left > 0: # Decrement ships left stats.ships_left -= 1 # Update scoreboard sb.prep_ships() # Empty the list of aliens and bullets aliens.empty() bullets.empty() alienbullets.empty() ufos.empty() # Create a new fleet and center the ship create_fleet(ai_settings, screen, ship, aliens) ship.center_ship() else: stats.game_active = False pygame.mouse.set_visible(True)
def player2_collision(self): """ Checks for player2 collision with other game objects, also checks for collision between player2 blast and player1 position """ for blast in self.player2.blast_list: if pygame.sprite.collide_rect(blast, self.player1): self.player2.blast_list.remove(blast) boom = Explosion(self.player1.rect.center) self.group.add(boom) C.EXPLOSION_SOUND.play() if self.player1.health <= 1: self.group.remove(self.player1) else: self.player1.health -= 1 if self.mandatory_object in self.group: if pygame.sprite.collide_rect(blast, self.mandatory_object): self.player2.blast_list.remove(blast) boom = Explosion(self.player2.blast.rect.center) self.group.add(boom) if self.fuel in self.group: if pygame.sprite.collide_rect(self.fuel, self.player2): self.player2.fuel += 500 self.group.remove(self.fuel) self.fuel_count -= 1 C.FUEL_SOUND.play() if self.mandatory_object in self.group: if pygame.sprite.collide_rect(self.mandatory_object, self.player2): temp = self.player2.speed self.player2.speed = -1 * temp * 3
def hit_by_laser(self): explosion = Explosion(self.batch, self.objects, self.window) explosion.x = self.x explosion.y = self.y self.destroy_object() return True
def __init__(self, spawn, x, y, scrW, scrH, shipID, isHitable): super(Enemy02, self).__init__(spawn, isHitable, shipID) self.HP = 20 self.__explosion = Explosion(0, 0, Explosion.EXPLOSION01_TYPE) self.__fire = ShipFire(0, 0, ShipFire.SHIPFIRE02_TYPE) self.state = Enemy02.ALIVE self.__lastBtnReleased = True self.__isShooting = False self.__scrW = scrW self.__scrH = scrH self.__shipRect = None self.__curFrameIndex = 0 if not Enemy02.shipSpriteSheet: Enemy02.shipSpriteSheet = SpriteSheet("res/img/enemyship02.png") if not Enemy02.imgs: for frames in shipFrames: Enemy02.imgs.append(Enemy02.shipSpriteSheet.getFrame(*frames)) self.setShipFrame(0) self.setPos(x, y) self.__shipAnimTimer = pygame.time.get_ticks() self.__shootingTimer = pygame.time.get_ticks() self.setupBulletPool(Bullet.BULLET02_TYPE, scrW, scrH, 10) # Set the moving area of the spaceship self.setRandomDestRange(scrW // 2, 45, scrW - self.getRect().width, scrH - 5) # Select a random spot within the moving area as the flying destination self.generateRandomDest() self.__randStep = Enemy02.movStep + random.randint(0, 200) / 1000
def __init__(self, spawn, x, y, scrW, scrH, shipID, isHitable): super(Enemy01, self).__init__(spawn, isHitable, shipID) self.HP = 10 self.__explosion = Explosion(0, 0, Explosion.EXPLOSION01_TYPE) self.__fire = ShipFire(0, 0, ShipFire.SHIPFIRE02_TYPE) self.state = Enemy01.ALIVE self.__lastBtnReleased = True self.__isShooting = False self.__scrW = scrW self.__scrH = scrH self.__shipRect = None self.__curFrameIndex = 0 if not Enemy01.shipSpriteSheet: Enemy01.shipSpriteSheet = SpriteSheet("res/img/enemyship01.png") if not Enemy01.imgs: for frames in shipFrames: Enemy01.imgs.append(Enemy01.shipSpriteSheet.getFrame(*frames)) self.setShipFrame(0) self.setPos(x, y) self.__shipAnimTimer = pygame.time.get_ticks() self.setupBulletPool(Bullet.BULLET02_TYPE, scrW, scrH, 10) self.setRandomDestRange(scrW // 3, 45, scrW - self.getRect().width, scrH - 5) self.generateRandomDest() # Make sure the space ship always fly towards the # left edge of the screen. self.destX = -((self.getRect().width // 2) + 5) self.calcMoveSteps() self.__randStep = Enemy01.movStep + random.randint(0, 200) / 1000
def __init__(self, spawn, x, y, scrW, scrH, shipID, isHitable, shiftPhase): super(Enemy03, self).__init__(spawn, isHitable, shipID) self.HP = 5 self.__explosion = Explosion(0, 0, Explosion.EXPLOSION01_TYPE) self.__fire = ShipFire(0, 0, ShipFire.SHIPFIRE02_TYPE) self.state = Enemy03.ALIVE self.__lastBtnReleased = True self.__isShooting = False self.__scrW = scrW self.__scrH = scrH self.__shipRect = None self.__curFrameIndex = 0 self.__originY = y # Shift the phase or offset of the sine wave so that 2 rockets can # travel in opposite direction self.__degree = 180 if shiftPhase else 0 if not Enemy03.shipSpriteSheet: Enemy03.shipSpriteSheet = SpriteSheet("res/img/enemyship03.png") if not Enemy03.imgs: for frames in shipFrames: Enemy03.imgs.append(Enemy03.shipSpriteSheet.getFrame(*frames)) self.setShipFrame(0) self.setPos(x, y) self.__shipAnimTimer = pygame.time.get_ticks() self.setupBulletPool(Bullet.BULLET02_TYPE, scrW, scrH, 10)
def handle_collisions(self): new_exp = [] for i in self.interceptors: if i.cury - i.endy < 0.1: new_exp.append(Explosion(self.ctx, i.endx, i.endy)) self.interceptors.remove(i) del i for m in self.missiles: if m.endy - m.cury < 0.1: new_exp.append(Explosion(self.ctx, m.endx, m.endy)) self.missiles.remove(m) for c in self.cities: if m.endx == c.x and not c.broken: c.broken = True for b in self.bases: if m.endx == b.x and not b.broken: b.broken = True b.ammo = 0 del m for e in self.explosions: for i in self.interceptors: if e.is_inside(i.curx, i.cury): new_exp.append(Explosion(self.ctx, i.curx, i.cury)) self.interceptors.remove(i) del i for m in self.missiles: if e.is_inside(m.curx, m.cury): new_exp.append(Explosion(self.ctx, m.curx, m.cury)) self.missiles.remove(m) del m self.explosions += new_exp
def create_explosion(self, x, y): """ Creates an instance of Explosion and appends it to the animations sprite list """ new_explosion = Explosion(self.explosion_texture_list, x, y) # Call update() because it sets which image we start on new_explosion.update() self.animations.append(new_explosion)
def check_bullet_meteor_collisions(screen, bullets, meteors, explosions, explosion_anim, exp_sounds): collisions = pygame.sprite.groupcollide(bullets, meteors, True, True) for collision in collisions: ex = Explosion(screen, collision.rect.center, 'sm', explosion_anim) explosions.add(ex) ex.blitme() for e in exp_sounds: e.play()
def _made_contact (self, entity) : #spawn an explosion explosion = Explosion (default='images/explosion.png') explosion.set_pos ( (self.rect.centerx - 50, self.rect.centery - 50) ) for entity in self._friendly_entities : explosion._friendly_entities.append (entity) for entity in self._pass_through_entities : explosion._pass_through_entities.append (entity) self._delegate.spawn_entity (explosion)
def boom(self): """ Метод - взрыв бомбы. :return: None """ is_explosion = Explosion(self.position, self, screen=self.screen) is_explosion.explosion_region() # print('Взрыв') self.remove() # ремув будет в map при удалении блока == бромбы
def collisionFunc(count_meteoro, tiros, ship, coracao_array_object): global score global run global NaveDead global boss_dead #check collission for meteoro in count_meteoro: #Meteoro vs Nave if meteoro.rect.colliderect(ship.rectNave): meteoro.remove_meteoro(count_meteoro, True) ship.nav_collision() explosao = Explosion(meteoro.rect.x, meteoro.rect.y, win, count_explosions) count_explosions.append(explosao) if ship.health <= 0: NaveDead = True for tiro in tiros: #Tiro vs Meteoro if meteoro.rect.colliderect(tiro.rectBullets): score += 1 #Criando explosão explosao = Explosion(meteoro.rect.x, meteoro.rect.y, win, count_explosions) count_explosions.append(explosao) meteoro.remove_meteoro(count_meteoro, True) tiro.remover_balas(True) #Tiro vs Boss if boss != 0: if boss.enemy_rect.colliderect(tiro.rectBullets): boss.boss_decrease_health() explosao = Explosion(tiro.rectBullets.x, tiro.rectBullets.y, win, count_explosions) count_explosions.append(explosao) tiro.remover_balas(True) print('COLIDIU COM O BOSS') if boss.health <= 0: boss_dead = True #Nave vs Coração for coracao in coracao_array_object: if ship.rectNave.colliderect(coracao.rect_heart): ship.health = coracao.health_restore(ship.health) coracao_array_object.remove(coracao) #Nave vs Tiro do Boss if boss != 0: for boss_bullet in boss.bullet_array: if ship.rectNave.colliderect(boss_bullet.bullet_rect): boss.bullet_array.remove(boss_bullet) ship.nav_collision() if ship.health <= 0: NaveDead = True
def test_explosion(): exp = Explosion(QPoint(0, 0), 'BIG') scene.addItem(exp) scene.map.objects.append(exp) exp.ticks = 5 exp.update(scene) pos = exp.pos() assert QPoint(0, 0) != pos exp.ticks = 12 exp.update(scene) assert pos != exp.pos()
def __init__(self): pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode((1600, 900), pygame.RESIZABLE) self.caption = pygame.display.set_caption("Sideways shooter") self.stats = GameStats(self) self.sb = Scoreboard(self) self.ship = Ship(self) self.explosion = Explosion(self) self.bullets = pygame.sprite.Group() self.aliens = pygame.sprite.Group() self._create_fleet() self.play_button = Button(self, "Play")
def test_explosion_tick(self): simple_bomb = SimpleBomb(self.player.position, self.player, self.player.power_bomb) explosion = Explosion(simple_bomb.position, simple_bomb, simple_bomb.power_bomb) SET_EXPLOSIONS.clear() # почему он уже не пустой? SET_EXPLOSIONS.add(explosion) for i in range(2): explosion.ticker() self.assertEqual(0, SET_EXPLOSIONS.__len__())
def check_bullet_alien_collisions(self, display): """Respond to bullet-alien collisions.""" # Remove any bullets, aliens, and ufos that have collided. collisions = pygame.sprite.groupcollide(self.bullets, self.fleet.aliens, True, True) ufo_collisions = pygame.sprite.groupcollide(self.bullets, self.fleet.ufos, True, True) if collisions or ufo_collisions: for aliens in collisions.values(): for alien in aliens: self.sounds.alien_destroy_sound.play() explosion = Explosion(screen=self.screen, sprite_sheet=self.sprite_sheet, rect=alien.rect) explosion.blitme() self.explosions.add(explosion) self.stats.score += (alien.points * self.ai_settings.score_scale) self.sb.prep_score() for ufos in ufo_collisions.values(): for ufo in ufos: self.sounds.ufo_sound.stop() self.sounds.alien_destroy_sound.play() ufo_points = random.randrange(40, 200, 10) display.draw_ufo_points(ufo_points, ufo) self.stats.score += ufo_points self.sb.prep_score() self.sb.check_high_score() if (len(self.fleet.aliens) == 40 or len(self.fleet.aliens) == 25 or len(self.fleet.aliens) == 10)\ and self.last_alien_amount != len(self.fleet.aliens): # Speed up tempo of background music here self.sounds.background_music.stop() self.sounds.speed_up_bg_music() self.last_alien_amount = len(self.fleet.aliens) self.sounds.background_music.play(-1) print(self.sounds.background_music_counter) if len(self.fleet.aliens) == 0 and len(self.fleet.ufos) == 0: # If the entire fleet is destroyed, increase the difficulty and start a new level. self.bullets.empty() self.ai_settings.increase_speed() self.stats.level += 1 self.sb.prep_level() self.fleet.create_fleet() self.sounds.background_music.stop() self.sounds.background_music = self.sounds.background_track[0] self.sounds.background_music.play(-1) self.sounds.background_music_counter = 1 display.create_barriers()
def _update_superbullets(self): """Renewing superbullets position and removing old ones""" self.superbullets.update() # Removing superbullets outside the screen for superbullet in self.superbullets.copy(): if superbullet.rect.bottom <= 0: self.superbullets.remove(superbullet) # Checking superbullet-alien collision collisions = pygame.sprite.spritecollide(superbullet, self.aliens, True) # Running explosion animation for collision in collisions: explosion = Explosion(self, collision.rect.center, "big") self.explosions.add(explosion) self.stats.score += self.settings.alien_points_superbullet self.scoreboard.prep_score() self.scoreboard.check_high_score() if self.settings.sound_on: self.settings.play_sound_effect("big_explosion") if not self.aliens: self._start_new_level()
def collapse(self, field): for point_x in range( max(int(self.x) - self.splash, 0), min( math.ceil(self.x) + self.splash, self.const['field_width'])): h = math.ceil( (self.splash**2 - abs(int(self.x) - point_x)**2)**0.5) for point_y in range( max(int(self.y) - h, 0), min(math.ceil(self.y) + h, self.const['field_height'])): field[point_x, point_y] = 0 new_boom = Explosion(self.canvas) new_boom.start(self) self.game.boom.append(new_boom) return (field)
def _ship_hit(self): """Processing alien-starship collision""" # Creating explosion ship_explosion = Explosion(self, self.ship.rect.center, "big") self.explosions.add(ship_explosion) if self.stats.ships_left > 0: # Decreasing number of ships left self.stats.ships_left -= 1 self.scoreboard.prep_ships() # Clearing alien and (super)bullets groups self.aliens.empty() self.bullets.empty() self.superbullets.empty() # Positioning new ship in the center self.ship.center_ship() # Pause sleep(0.5) else: self.stats.game_active = False pygame.mouse.set_visible(True) if self.settings.sound_on: self.settings.play_sound_effect("big_explosion")
def _check_bullet_alien_collision(self): """Respond to bullet-alien collision.""" # Check for any bullets that have hit aliens. # If so, get rid of the bullet and the alien. collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True) if collisions: for aliens in collisions.values(): self.stats.score += self.settings.alien_points * len(aliens) for alien in aliens: # Display explosion effect at collision location alien_center = alien.rect.center expl = Explosion(alien_center) self.explosions.add(expl) self.sb.prep_score() self.sb.check_high_score() # Create new fleet if all aliens are destroyed. if not self.aliens: # Destroy existing bullets and create new fleet. self.bullets.empty() self._create_fleet() self.settings.increase_speed() # Increase level. self.stats.level += 1 self.sb.prep_level()
def __init__(self, spawn, x, y, scrW, scrH, shipID, isHitable): super(Enemy04, self).__init__(spawn, isHitable, shipID) self.HP = 200 self.__explosion = [] for i in range(4): self.__explosion.append(Explosion(0, 0, Explosion.EXPLOSION01_TYPE)) self.__fire = [ShipFire(0, 0, ShipFire.SHIPFIRE02_TYPE), ShipFire(0, 0, ShipFire.SHIPFIRE02_TYPE)] self.state = Enemy04.ALIVE self.__lastBtnReleased = True self.__isShooting = False self.__scrW = scrW self.__scrH = scrH self.__shipRect = None self.__curFrameIndex = 0 if not Enemy04.shipSpriteSheet: Enemy04.shipSpriteSheet = SpriteSheet("res/img/enemyship04.png") if not Enemy04.imgs: for frames in shipFrames: Enemy04.imgs.append(Enemy04.shipSpriteSheet.getFrame(*frames)) self.setShipFrame(0) self.setPos(x, y) self.__shipAnimTimer = pygame.time.get_ticks() self.__shootingTimer = pygame.time.get_ticks() self.setupBulletPool(Bullet.BULLET02_TYPE, scrW, scrH, 20) self.setRandomDestRange(scrW // 1.75, self.getRect().height // 2, scrW - self.getRect().width // 2, scrH - self.getRect().height // 2) self.generateRandomDest() self.__randStep = Enemy04.movStep + random.randint(0, 100) / 1000
def update(self): # ASTEROIDS hit = [] hit.extend( pygame.sprite.spritecollide(self, self.game.asteroids, False, pygame.sprite.collide_mask)) if self.type: hit.extend( pygame.sprite.spritecollide(self, self.game.player, False, pygame.sprite.collide_mask)) else: hit.extend( pygame.sprite.spritecollide(self, self.game.invaders, False, pygame.sprite.collide_mask)) if hit: for sprite in hit: sprite.hit(self.health, (self.x, self.y)) self.game.explosions.add(Explosion(self.game, self.x, self.y)) self.health = 0 else: self.move()
def die(self): self = Explosion(self.rect.centerx, self.rect.centery) Explosion.screen.blit(self.image, (self.rect.x, self.rect.y)) pygame.display.update(self.rect) pygame.time.wait(500) pygame.quit() sys.exit()
def body_update(self): if self.state == 1: boss_pattern.pattern_head_1(self.fire_time, self.x, self.y, 2) elif self.state == 2: boss_pattern.pattern_head_2(self.fire_time,self.x,self.y,2, self.degree) elif self.state == 3: boss_pattern.pattern_head_3(self.fire_time,self.x, self.y, 6, self.degree) if self.state != 0: if self.HP < 2000: boss_pattern.pattern_tentacle(self.fire_time, self.x + 250, self.y + 50, 0) boss_pattern.pattern_tentacle(self.fire_time, self.x + 250, self.y - 50, 0) boss_pattern.pattern_tentacle(self.fire_time, self.x - 250, self.y + 50, 0) boss_pattern.pattern_tentacle(self.fire_time, self.x - 250, self.y - 50, 0) for hero_bullet in game_world.get_objects(2): if ((hero_bullet.x - self.x)**2 + (hero_bullet.y - (self.y + 50))**2 ) < (PIXEL_PER_METER*2)**2 or \ ((hero_bullet.x - self.x)**2 + (hero_bullet.y - (self.y - 100))**2 ) < (PIXEL_PER_METER*2)**2 or \ ((hero_bullet.x - self.x) ** 2 + (hero_bullet.y - (self.y)) ** 2) < (PIXEL_PER_METER * 2) ** 2: #라이플은 단순한 데미지 if hero_bullet.state == 1 or hero_bullet.state == 2: self.HP -= hero_bullet.damage #바주카는 스플래시 데미지 elif hero_bullet.state == 3: self.HP -= hero_bullet.damage explosion = Explosion(hero_bullet.x, hero_bullet.y) game_world.add_object(explosion, 4) game_world.remove_object(hero_bullet)
def update(self, delta_time): # Applique la gravite & acceleration self.gravity(delta_time) self.position[0] += self.acceleration[0] * delta_time self.position[1] += self.acceleration[1] * delta_time # Mise a jour de la position self.rect.center = self.position # Est-ce que je touche quelque chose dans ce que j'ai le droit de toucher for col_mask in self.collisions_mask: hits = pygame.sprite.spritecollide(self, col_mask, False, pygame.sprite.collide_mask) if len(hits) != 0: # Touché BOOM ! Explosion(self.scene, self.position, self.scene.terrain, self.scene.group_players.sprites(), 2.5) self.kill() # Si je sors de l'ecran je meurs aussi :( if -64 > self.position[0] or self.position[0] > pygame.display.get_surface().get_width() + 64 or -256 > self.position[1] or self.position[1] > pygame.display.get_surface().get_height() + 64: self.kill() self.scene.next_player() # NEXT ! animation self.animations[self.key].iter() # change la direction du missile selon l'angle #IDK fait au feeling :s if math.pi/2 < self.angle: self.image = pygame.transform.flip(self.animations[self.key].next(), True, True) else: self.image = self.animations[self.key].next()
def check_bullet_enemy_ship_collisions(settings, screen, stats, scoreboard, ship, enemy_ships, bullets, enemy_bullets, exp_sprite): """Respond to bullet-enemy_ship collisions.""" # Remove any bullets and enemy_ship that have collected. collision = pygame.sprite.groupcollide(bullets, enemy_ships, True, True) if collision: for enemy_ship in collision.values(): stats.score += settings.enemy_ship_points * len(enemy_ship) for al in enemy_ship: exp = Explosion(screen, al.rect.center) exp_sprite.add(exp) scoreboard.prep_score() check_high_score(stats, scoreboard) if len(enemy_ships) == 0: # Destroy existing bullets and create new fleet. bullets.empty() enemy_bullets.empty() settings.increase_speed() # Increase the level stats.level += 1 scoreboard.prep_level() create_fleet(enemy_ships, settings, screen)
def explode(self): self.remove() # rewrite for loops for i in range( max(0, int(self.i - self.player.bomb_radious)), min(globals.squares_per_line, int(self.i + 1 + self.player.bomb_radious))): for j in range( max(0, int(self.j - self.player.bomb_radious)), min(globals.squares_per_line, int(self.j + 1 + self.player.bomb_radious))): center = (self.i, self.j) square = (i, j) if utils.distance(center, square) <= self.player.bomb_radious: # delete powerup in that square, if any for powerup in globals.powerups: if powerup.i == square[0] and \ powerup.j == square[1]: globals.powerups.remove(powerup) break # delete bomb in that square, if any for bomb in globals.bombs: if bomb.i == square[0] and \ bomb.j == square[1]: bomb.remove() break if globals.squares[i][j].owner != self.player: globals.squares[i][j].change_owner(self.player) globals.explosions.append(Explosion(i, j))
def update_meteorites(game_settings, stats, screen, rocket, meteorites, score_board, explosions): """Draw, move and remove meteorites.""" meteorites.update() # Delete meteorites for meteorite in meteorites.copy(): if meteorite.rect.top >= meteorite.screen_rect.bottom: meteorites.remove(meteorite) # Create roe of meteorites. if len(meteorites) < 10: create_row_meteorites(game_settings, stats, screen, rocket, meteorites) for meteorite in meteorites: if meteorite.rect.top == meteorite.screen_rect.centery - 300: create_row_meteorites(game_settings, stats, screen, rocket, meteorites) # Create explosion when rocket collides meteorite. if pygame.sprite.spritecollideany(rocket, meteorites): ship_hit(game_settings, stats, screen, rocket, meteorites, score_board) explosion = Explosion(screen, rocket) explosions.add(explosion) update_explosions(explosions) # Delete meteorite which hit the rocket. pygame.sprite.spritecollide(rocket, meteorites, True)
def explode_bomb(self, primed_bomb_queue, bomb_expl_queue): """Bomb explodes by removing it from the bomb_expl_queue. After a set amount of time, the explosion is removed from the explosion queue and goes away""" exp_bomb = primed_bomb_queue.pop(0) bomb_expl_queue.append(Explosion(exp_bomb[0], exp_bomb[1], self.size)) t = Timer(.5, bomb_expl_queue.pop, [0]) t.start()
def run_game(self): """Start the main loop for the game.""" while True: # Watch for keyboard and mouse events. for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: self.ship.moving_up = True if event.key == pygame.K_DOWN: self.ship.moving_down = True if event.key == pygame.K_RIGHT: self.ship.moving_right = True if event.key == pygame.K_LEFT: self.ship.moving_left = True elif event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT: self.ship.moving_right = False if event.key == pygame.K_LEFT: self.ship.moving_left = False if event.key == pygame.K_UP: self.ship.moving_up = False if event.key == pygame.K_DOWN: self.ship.moving_down = False # Update positions of any characters that might be moving. self.ship.update() self.aliens.update() if pygame.sprite.spritecollideany(self.ship, self.aliens): # The player's ship has hit an alien ship. # Show an explosion, pause the game, and reset player's ship and alien ships. explosion = Explosion(self, self.ship) explosion.blitme() pygame.display.flip() pygame.mixer.music.play(0) sleep(2) # sys.exit() self.screen.fill((255, 255, 255)) self.ship.blitme() self.aliens.draw(self.screen) # Make the most recently drawn screen visible. pygame.display.flip()
def __init__(self): pygame.mixer.pre_init(44100,-16,2,2048) pygame.init() self.sounds=Sounds() self.input_handler = InputHandler() self.game_screen = GameScreen(self.TITLE,self.WIDTH,self.HEIGHT) self.miner=Miner(8,0) self.explosion=Explosion(-1,-1) self.game_screen.add_sprite(self.miner) self.game_screen.add_sprite(self.explosion) self.health = 100 self.clock=pygame.time.Clock() self.state=self.WAITING self.game_screen.display_opening()
def __init__(self): pygame.mixer.pre_init(44100,-16,2,2048) pygame.init() self.screen=pygame.display.set_mode((680,600)) pygame.display.set_caption(self.TITLE) self.pressedkey=None self.bellsound=pygame.mixer.Sound('assets/sounds/bell.ogg') self.chargesound=pygame.mixer.Sound('assets/sounds/bomb.ogg') self.yeehawsound=pygame.mixer.Sound('assets/sounds/yeehaw.ogg') self.kachingsound=pygame.mixer.Sound('assets/sounds/kaching.ogg') self.board=[] self.bgbase=pygame.image.load('assets/images/background.png') self.bg=pygame.image.load('assets/images/background.png') self.digits=pygame.image.load('assets/images/digits.png') self.gamearea=pygame.Surface(self.bg.get_size()) self.is_playing=False # currently 2 nugget images self.nuggets=[] self.nuggets.append(pygame.image.load('assets/images/gold01-%dpx.png' % self.SQUARE_SIZE)) self.nuggets.append(pygame.image.load('assets/images/gold02-%dpx.png' % self.SQUARE_SIZE)) self.explosion=Explosion(0,0,self.SQUARE_SIZE) self.explosion_group=pygame.sprite.RenderPlain(self.explosion) self.miner=Miner(0,0) self.clock=pygame.time.Clock() # add title text=pygame.image.load('assets/images/text_title.png') self.screen.blit(text,(self.TITLE_X,self.BOARD_LEFT)) # add assay office self.office=pygame.image.load('assets/images/assayoffice.png') self.screen.blit(self.office,(self.ASSAY_X+self.BOARD_LEFT,self.ASSAY_Y)) self.cash=0 self.gold=0 self.charges=10 self.health=100 # add "Gold" text=pygame.image.load('assets/images/nugget.png') self.screen.blit(text,(self.GOLD_X,self.BOARD_LEFT)) self.display_gold() # add "Cash" text=pygame.image.load('assets/images/text_cash.png') self.screen.blit(text,(self.CASH_X,66)) self.display_cash() # add "Charges" text=pygame.image.load('assets/images/dynamite.png') self.screen.blit(text,(self.CHARGES_X,16)) self.display_charges() # add "Miner head" text=pygame.image.load('assets/images/miner_head.png') self.screen.blit(text,(self.CHARGES_X,66)) self.display_health() self.setup()
class Game(object): TITLE = "Gold Rush!" BOARD_LEFT = 20 BOARD_TOP = 130 SQUARE_SIZE = 32 BLACK = (0,0,0) GREEN=(128,255,128) YELLOW=(255,255,128) RED=(255,128,128) FRAMES_PER_SECOND = 30 ASSAY_X = 540 ASSAY_Y = 84 CHARGES_X = 180 CASH_X = 20 CASH_OFFSET = 30 GOLD_X = 16 CHARGES_OFFSET = 32 HEALTH_X =CHARGES_X + 40 TITLE_X = 340 def display_gold(self): scoretext='%03d' % self.gold for i in range(len(scoretext)): num=int(scoretext[i])*24 pos=i*24 self.screen.blit(self.digits,(self.CASH_X+self.CASH_OFFSET+(i*24),20),(num,0,24,35)) def display_charges(self): scoretext='%02d' % self.charges for i in range(len(scoretext)): num=int(scoretext[i])*24 pos=i*24 self.screen.blit(self.digits,(self.CHARGES_X+self.CHARGES_OFFSET+(i*24),20),(num,0,24,35)) def display_cash(self): scoretext='%05d' % self.cash for i in range(len(scoretext)): num=int(scoretext[i])*24 pos=i*24 self.screen.blit(self.digits,(self.CASH_X+self.CASH_OFFSET+(i*24),66),(num,0,24,35)) def display_health(self): h=int(84*(self.health/100.0)) b=84-h c=self.GREEN if self.health<20: c=self.RED elif self.health<40: c=self.YELLOW self.screen.fill(c,(self.HEALTH_X,70,h,32)) self.screen.fill(self.BLACK,(self.HEALTH_X+h,70,b,32)) # num=int(scoretext[i])*24 # pos=i*24 # self.screen.blit(self.digits,(self.CASH_X+self.CASH_OFFSET+(i*24),66),(num,0,24,35)) def __init__(self): pygame.mixer.pre_init(44100,-16,2,2048) pygame.init() self.screen=pygame.display.set_mode((680,600)) pygame.display.set_caption(self.TITLE) self.pressedkey=None self.bellsound=pygame.mixer.Sound('assets/sounds/bell.ogg') self.chargesound=pygame.mixer.Sound('assets/sounds/bomb.ogg') self.yeehawsound=pygame.mixer.Sound('assets/sounds/yeehaw.ogg') self.kachingsound=pygame.mixer.Sound('assets/sounds/kaching.ogg') self.board=[] self.bgbase=pygame.image.load('assets/images/background.png') self.bg=pygame.image.load('assets/images/background.png') self.digits=pygame.image.load('assets/images/digits.png') self.gamearea=pygame.Surface(self.bg.get_size()) self.is_playing=False # currently 2 nugget images self.nuggets=[] self.nuggets.append(pygame.image.load('assets/images/gold01-%dpx.png' % self.SQUARE_SIZE)) self.nuggets.append(pygame.image.load('assets/images/gold02-%dpx.png' % self.SQUARE_SIZE)) self.explosion=Explosion(0,0,self.SQUARE_SIZE) self.explosion_group=pygame.sprite.RenderPlain(self.explosion) self.miner=Miner(0,0) self.clock=pygame.time.Clock() # add title text=pygame.image.load('assets/images/text_title.png') self.screen.blit(text,(self.TITLE_X,self.BOARD_LEFT)) # add assay office self.office=pygame.image.load('assets/images/assayoffice.png') self.screen.blit(self.office,(self.ASSAY_X+self.BOARD_LEFT,self.ASSAY_Y)) self.cash=0 self.gold=0 self.charges=10 self.health=100 # add "Gold" text=pygame.image.load('assets/images/nugget.png') self.screen.blit(text,(self.GOLD_X,self.BOARD_LEFT)) self.display_gold() # add "Cash" text=pygame.image.load('assets/images/text_cash.png') self.screen.blit(text,(self.CASH_X,66)) self.display_cash() # add "Charges" text=pygame.image.load('assets/images/dynamite.png') self.screen.blit(text,(self.CHARGES_X,16)) self.display_charges() # add "Miner head" text=pygame.image.load('assets/images/miner_head.png') self.screen.blit(text,(self.CHARGES_X,66)) self.display_health() self.setup() def setup(self): # initialize score items self.cash=0 self.gold=0 self.charges=10 # load background image every time self.bg=pygame.image.load('assets/images/background.png') #redraw assay office self.bg.blit(self.office,(self.ASSAY_X,self.ASSAY_Y-self.BOARD_TOP)) self.board=[] # top row of empty spaces pathsup=2 self.board.append([' ']*20) self.board.append(['*']*20) for y in range(2,14): row=[] for x in range(20): c='*' if random()<0.4: # make a hole self.bg.fill(self.BLACK,(x*self.SQUARE_SIZE,y*self.SQUARE_SIZE,self.SQUARE_SIZE,self.SQUARE_SIZE)) c=' ' if y>1: c='G' nugg=self.nuggets[0 if random()<0.5 else 1] self.bg.blit(nugg,(x*self.SQUARE_SIZE,y*self.SQUARE_SIZE)) row.append(c) self.board.append(row) # add soil self.gamearea.blit(self.bg,(0,0)) pygame.display.flip() def print_board(self): for row in self.board: print ' '.join(row) def mainloop(self): deltat=self.clock.tick(self.FRAMES_PER_SECOND) tx=self.miner.x ty=self.miner.y self.miner_group.clear(self.gamearea,self.bg) self.explosion_group.clear(self.gamearea,self.bg) pressedspace=False for event in pygame.event.get(): #print event if event.type == KEYDOWN: if event.key == K_ESCAPE: exit(0) elif event.key in (K_RIGHT,K_LEFT,K_UP,K_DOWN): self.pressedkey= event.key elif event.key == K_SPACE: pressedspace = True elif event.type == KEYUP: if event.key in (K_RIGHT,K_LEFT,K_UP,K_DOWN): if self.pressedkey == event.key: self.pressedkey = None #elif event.key == K_SPACE: #pressedspace = False # only draw explosion if necessary if self.explosion.update(deltat): self.explosion_group.update(deltat) self.explosion_group.draw(self.gamearea) else: if pressedspace and self.pressedkey: # Do explosion pressedspace=False bx=self.miner.x by=self.miner.y if self.pressedkey == K_LEFT: bx-=1 if self.pressedkey == K_RIGHT: bx+=1 if self.pressedkey == K_UP: by-=1 if self.pressedkey == K_DOWN: by+=1 if bx>=0 and bx<20 and (by>0 or (by==0 and self.pressedkey == K_DOWN)) and by<20 and self.charges>0: self.explosion.explode(bx,by) self.charges-=1 # print "(%d,%d)->(%d,%d) Boom! %d charges left." % (self.miner.x,self.miner.y,bx,by,self.charges) self.board[by][bx]=' ' self.bg.fill(self.BLACK,(bx*self.SQUARE_SIZE,by*self.SQUARE_SIZE,self.SQUARE_SIZE,self.SQUARE_SIZE)) self.gamearea.blit(self.bg,(0,0)) self.display_charges() #self.screen.blit(self.digits,(460+(i*24),20),(num,0,24,35)) self.chargesound.play() for j in range(20): x=randint(0,19) y=randint(2,11) o=self.board[y][x] a=self.board[y-1][x] if o==' ' and a=='*': self.board[y][x]='*' xpos=x*self.SQUARE_SIZE ypos=y*self.SQUARE_SIZE self.bg.blit(self.bgbase,(x*self.SQUARE_SIZE,y*self.SQUARE_SIZE),(xpos,ypos,self.SQUARE_SIZE,self.SQUARE_SIZE)) if self.pressedkey == K_RIGHT and self.miner.can_move(): if tx<19: tx += 1 if self.pressedkey == K_LEFT and self.miner.can_move(): if tx>0: tx -= 1 if self.pressedkey == K_UP and self.miner.can_move(): if ty>0: ty -= 1 else: if tx==17: if self.gold!=0: self.cash+=self.gold*self.charges self.gold=0 self.kachingsound.play() self.display_gold() self.display_cash() self.yeehawsound.play() if self.pressedkey == K_DOWN and self.miner.can_move(): if ty<13: ty += 1 o=self.board[ty][tx] if (tx!=self.miner.x or ty!=self.miner.y) and o in ' G': self.miner.set_location(tx,ty) if o=='G': self.board[ty][tx]=' ' self.gold += 1 self.bellsound.play() self.bg.fill(self.BLACK,(self.miner.x*self.SQUARE_SIZE,self.miner.y*self.SQUARE_SIZE,self.SQUARE_SIZE,self.SQUARE_SIZE)) self.gamearea.blit(self.bg,(0,0)) self.display_gold() self.miner.update_move() self.miner_group.update(deltat) self.miner_group.draw(self.gamearea) if self.miner.y>0: self.health-=0.25 if self.health<0: self.health=0 pass self.display_health() else: self.health+=1 if self.health>100: self.health=100 self.display_health() self.screen.blit(self.gamearea,(self.BOARD_LEFT,self.BOARD_TOP)) pygame.display.flip()
class Game(object): TITLE = "Gold Rush!" WIDTH=680 HEIGHT=600 WAITING = 1 PLAYING = 2 FRAMES_PER_SECOND = 30 board=[] def __init__(self): pygame.mixer.pre_init(44100,-16,2,2048) pygame.init() self.sounds=Sounds() self.input_handler = InputHandler() self.game_screen = GameScreen(self.TITLE,self.WIDTH,self.HEIGHT) self.miner=Miner(8,0) self.explosion=Explosion(-1,-1) self.game_screen.add_sprite(self.miner) self.game_screen.add_sprite(self.explosion) self.health = 100 self.clock=pygame.time.Clock() self.state=self.WAITING self.game_screen.display_opening() def setup(self): self.gold=0 self.charges=10 self.cash=0 self.health=100 self.board=[] # top row of empty spaces self.board.append([' ']*20) self.board.append(['*']*20) for y in range(2,14): row=[] for x in range(20): c='*' if y>1 and random()<0.4: c=' ' if random()<0.5: c='0' else: c='1' row.append(c) self.board.append(row) self.miner.set_location(8,0) self.game_screen.setup() self.game_screen.set_board(self.board) self.game_screen.draw_board() def mainloop(self): deltat=self.clock.tick(self.FRAMES_PER_SECOND) running=True while running: self.input_handler.check() if self.input_handler.exit_action: running=False elif self.state == self.WAITING: if self.input_handler.key_press: self.setup() self.state=self.PLAYING else: self.game_screen.clear_sprites() if self.miner.can_move(): kpress=self.input_handler.arrow_press if kpress: dx=0 dy=0 if kpress == K_RIGHT: dx=1 elif kpress == K_LEFT: dx=-1 elif kpress == K_UP: dy=-1 elif kpress == K_DOWN: dy=1 if self.input_handler.space_press and (dx!=0 or dy!=0): self.do_explosion(dx,dy) tx=self.miner.x + dx ty=self.miner.y + dy if (dx!=0 or dy!=0) and (tx>=0 and tx<=19 and ty>=0 and ty<=13): o=self.board[ty][tx] if o in ' 01': self.miner.set_location(tx,ty) if o in '01': self.take_nugget(tx,ty) elif (dy==-1 and tx==17 and ty==-1 and self.gold!=0): self.cash_out() if self.charges==0: self.state=self.WAITING self.input_handler.reset() self.game_screen.display_gameover() if self.miner.y>0: self.health-=1 if self.health<0: self.health=0 self.game_screen.display_health(self.health) else: self.health+=1 if self.health>100: self.health=100 self.game_screen.display_health(self.health) self.game_screen.draw(deltat) pygame.quit() def do_explosion(self,dx,dy): bx=self.miner.x + dx by=self.miner.y + dy if bx>=0 and bx<20 and (by>0 or (by==0 and dy==1)) and by<14 and self.charges>0: self.explosion.explode(bx,by) self.charges-=1 self.board[by][bx]=' ' self.miner.add_delay(20) self.game_screen.clear_square(bx,by) self.game_screen.display_charges() self.sounds.play_boom() self.game_screen.display_charges(self.charges) for j in range(20): x=randint(0,19) y=randint(2,11) o=self.board[y][x] a=self.board[y-1][x] if o==' ' and a=='*': self.board[y][x]='*' self.game_screen.reset_square(x,y) def cash_out(self): self.cash+=self.gold*self.charges self.gold=0 self.sounds.play_kaching() self.game_screen.display_gold(self.gold) self.game_screen.display_cash(self.cash) self.sounds.play_yeehaw() def take_nugget(self,tx,ty): self.board[ty][tx]=' ' self.gold += 1 self.sounds.play_bell() self.game_screen.clear_square(tx,ty) self.game_screen.display_gold(self.gold)
def play(self): self.p1.status_win.display( curses.COLS // 2 - self.ship_space - self.max_health, 2 ) self.p2.status_win.display( curses.COLS // 2 + self.ship_space, 2 ) if self.p1.scene.objects[self.p1.stacking_order].x2 != self.midpoint_x - self.ship_space: self.main_win.move_to(self.p1, x=self.midpoint_x - self.ship_space - self.p1.width) self.main_win.pan(x=self.main_win.width - self.main_win.win_width) laser = Laser(self.p1, self.p2, self.main_win.height // 2) self.main_win.add_object(laser, laser.x1, laser.y) shield1 = Drawable(')') shield1.set_color(curses.COLOR_CYAN) shield1.set_attrs(curses.A_BOLD) self.main_win.add_object(shield1, laser.x1, laser.y) self.main_win.hide(shield1) shield2 = Drawable('(') shield2.set_color(curses.COLOR_CYAN) shield2.set_attrs(curses.A_BOLD) self.main_win.add_object(shield2, laser.x2, laser.y) self.main_win.hide(shield2) self.main_win.refresh() self.main_win.auto_refresh = True step = 0 while not self.p1.health.is_empty() and not self.p2.health.is_empty(): time.sleep(0.5) target1 = self.p1.get_target() target2 = self.p2.get_target() target = None successful = True if step < 5: target = self.p1 if not self.is_valid_target(target1): target1 = 0 elif not self.is_valid_target(target2) or target1 == target2: successful = False else: target = self.p2 if not self.is_valid_target(target2): target2 = 0 elif not self.is_valid_target(target1) or target1 == target2: successful = False self.p1.show_target(target2) self.p2.show_target(target1) direction = 1 if target is self.p1: direction = -1 self.main_win.show(laser) laser.start(direction) time.sleep(0.01) while laser.advance(): time.sleep(0.02) if not successful: if direction > 0: self.main_win.show(shield2) time.sleep(0.5) self.main_win.hide(shield2) else: self.main_win.show(shield1) time.sleep(0.5) self.main_win.hide(shield1) self.main_win.hide(laser) if successful: target.health.decrease() target.set_color(curses.COLOR_RED) if target.health.is_empty(): continue time.sleep(0.2) target.set_color(curses.COLOR_WHITE) step = (step + 1) % 10 explosion = Explosion(target) explosion.set_color(curses.COLOR_YELLOW) explosion.set_attrs(curses.A_BOLD) self.main_win.add_object(explosion, explosion.x, explosion.y) explosion.explode() self.winner = self.p2 if target is self.p2: self.winner = self.p1