def update(self): self.scr.fill(self.bg) self.vwsx = self.player.vx self.vwsy = self.player.vy self.wsx += self.vwsx self.wsy += self.vwsy self.entitylist = [self.player] + [e for e in self.enemyC.opponentlist] if self.main.holdingSpace: self.player.shoot({ "dad": self.player, "color": (0, 250, 100), "colorindex": (0, 100, 50), "angle": self.player.rotation, "radius": 2, "speed": 16, "damage": 1.5, "lifetime": 90, "pos": self.player.pos, }) self.player.update() self.enemyC.update() self.effectC.update() self.projectile.udpate() self.shiftworld() Stars.update(self) self.s1.update()
def __init__(self): """Creates all game objects needed, loads resources, initializes pygame library and sound mixer, sets display mode, etc.""" self.state = STATE_TITLE pygame.mixer.pre_init(buffer=SOUND_BUFFER) pygame.init() self.clock = Clock() self.scr = pygame.display.set_mode(SCREEN_SIZE, VID_MODE_FLAGS) pygame.display.set_caption(WINDOW_CAPTION) pygame.mouse.set_visible(False) LoadingScreen(self.scr).draw() sound_box.init() self.level = GameLevel() self.stats = GameStats(self.scr) self.view_pt = ViewPoint(self.scr) self.stars = Stars(self.scr, self.view_pt) self.track = Track(self.scr, self.view_pt) self.explosions = Explosions(self.scr, self.view_pt) self.ship = Ship(self.scr, self.view_pt, self.explosions) self.asteroids = Asteroids(self.scr, self.view_pt, self.explosions, self.track) self.title_screen = TitleScreen(self.scr, self.view_pt, self.stars) self.level_start_screen = LevelStartScreen(self.scr) self.level_complete_effect = LevelCompleteEffect(self.scr) self.game_over_effect = GameOverEffect(self.scr) self.pause_screen = PauseScreen(self.scr) self.ending_screen = EndingScreen(self.scr) self._init_title()
def _create_space(self): """Create the space with stars.""" # The star need to be stole in random. stars = Stars(self) numbers_stars = 20 for star_number in range(numbers_stars): stars = Stars(self) self.stars.add(stars)
def __init__(self, size): self.size = size pygame.font.init() self.score = 0 self.star_background = Stars(self.size) self.font = pygame.font.Font("res/font.ttf", 28) self.screen = pygame.display.set_mode(size) if not self.gameover: self.new_game() self.loop()
def draw(self): Stars.draw() self.s1.draw() self.effectC.draw() self.projectile.draw() self.enemyC.draw() self.player.draw() Messages.message(self.scr, str(self.wsx) + " " + str(self.wsy), (10, 40), p.Color("magenta")) Messages.message(self.scr, len(self.projectile.projectiles), (10, 70), p.Color("magenta")) Messages.message(self.scr, self.enemyC.totaldied, (10, 100), p.Color("green"))
def run_game(): pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Pick the stars") people = People(ai_settings, screen) stars = Stars(ai_settings, screen) alien = Alien(ai_settings, screen) bullets = Group() stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats) play_button = Button(ai_settings, screen, "Play") while True: gf.check_events(ai_settings, stats, sb, people, alien, bullets, play_button) bullets.update() for bullet in bullets.copy(): if bullet.rect.bottom >= ai_settings.screen_height: bullets.remove(bullet) if stats.game_active: people.update() gf.update_alien(alien) gf.update_stars(ai_settings, stats, sb, people, stars) if alien.rect.x % 120 == 0: gf.update_bullet(ai_settings, stats, screen, people, alien, bullets) gf.update_screen(ai_settings, stats, sb, screen, people, stars, alien, bullets, play_button)
def _create_stars(self, star_number, star_row_number): star = Stars(self) random_range = randint(-10, 10) random_number = randint(1, 10) # star_width, star_height = star.rect.size star.rect.x = random_range + random_number * star.rect.width * star_number star.rect.y = random_range + random_number * star.rect.height * star_row_number self.stars.add(star)
def draw(self): Stars.draw() self.s1.draw() self.effectC.draw() self.projectile.draw() self.enemyC.draw() self.player.draw() Messages.message(self.scr, str(self.wsx) + " " + str(self.wsy), (10, 40), p.Color('magenta')) Messages.message(self.scr, len(self.projectile.projectiles), (10, 70), p.Color('magenta')) Messages.message(self.scr, self.enemyC.totaldied, (10, 100), p.Color('green'))
def __init__ (self, mainMenuSound, soundMouse, soundSpace, soundGun, soundClick, takeSomething, soundCoin, soundSpaceShip): self.spaceShip = SpaceShip(width/2, height/2+150, 150, 150, 5, soundGun, takeSomething, soundCoin) self.enemy = Enemy(random(0+75/2, width-75/2), -300, 75, 75, 3) self.spaceShip.setEnemy(self.enemy) self.objects = Objects(soundGun) self.spaceShip.setSecondWeapon(self.objects.secondWeapon) self.spaceShip.setSecondWeaponTimer(self.objects.secondWeaponTimer) self.dropedObjects = DropedObjects(random(0+25, width-25), -2400, 50, 50, 2, random(0+25, width-25)) self.spaceShip.setDropedSecondWeapon(self.dropedObjects.dropedSecondWeapon) self.stars = Stars() self.gameState = False self.buttonToStartGame = StartGame(width/2, height/2, 100, 50) self.mainMenuSound = mainMenuSound self.mainMenuSound.loop() self.soundMouse = soundMouse self.soundSpace = soundSpace self.soundClick = soundClick self.soundSpaceShip = soundSpaceShip
def update(self): self.scr.fill(self.bg) self.vwsx = self.player.vx self.vwsy = self.player.vy self.wsx += self.vwsx self.wsy += self.vwsy self.entitylist = [self.player] + [e for e in self.enemyC.opponentlist] if self.main.holdingSpace: self.player.shoot( { "dad": self.player, "color": (0, 250, 100), "colorindex": (0, 100, 50), "angle": self.player.rotation, "radius": 2, "speed": 16, "damage": 1.5, "lifetime": 90, "pos": self.player.pos, } ) self.player.update() self.enemyC.update() self.effectC.update() self.projectile.udpate() self.shiftworld() Stars.update(self) self.s1.update()
def enter(): global background background = BackGround() global stars stars = Stars(400, get_canvas_height() / 2) global game_logo game_logo = GameLogo() global font font = load_font('Font/LCD_Solid.ttf', 24) global press_sound press_sound = load_wav('Sound/Select.wav') press_sound.set_volume(64)
def _create_starry_sky(self): """Instantiate a sky full of stars for the game's background.""" # Make a star. star = Stars(self) star_width, star_height = star.rect.size available_space_stars_x = self.settings.screen_width - (star_width) number_stars_x = available_space_stars_x // (star_width) # Determine the number of rows of stars that fit on the screen. available_space_stars_y = (self.settings.screen_height - (star_height)) star_number_rows = available_space_stars_y // (star_height) # Create the full sky of stars. for star_row_number in range(star_number_rows): for star_number in range(number_stars_x): self._create_stars(star_number, star_row_number)
def enter(): background = BackGround() gameworld.add_object(background, 0) ui = UI_Manager() gameworld.register_ui(ui) global stars stars = Stars(300, get_canvas_height() / 2) gameworld.add_object(stars, 0) global font font = load_font('Font/LCD_Solid.ttf', 24) global sound sound = load_wav("Sound/StageEnter.wav") sound.play()
def enter(): global sound sound = load_music('Sound/Credits.wav') sound.repeat_play() global new_records new_records = [] global score ui = gameworld.get_ui() score = ui.get_score() save_score() get_current_rank() gameworld.clear() global background background = BackGround() global stars stars = Stars(400, get_canvas_height() / 2)
def __init__(self, width=640, height=400, fps=60, stars=200): self.running = True self.score = 0 # CONSTANT self.FPS = fps self.PLAYTIME = 0.0 self.TOTAL_STARS = stars self.WIDTH = width self.HEIGHT = height # INITIALIZE SCREEN, CLOCK, FONT self.screen = pygame.display.set_mode((self.WIDTH, self.HEIGHT), pygame.DOUBLEBUF) self.background = pygame.Surface(self.screen.get_size()).convert(self.screen) self.clock = pygame.time.Clock() self.font = pygame.font.SysFont('mono', 20, bold=True) # INITIALIZE SCREEN OBJECTS self.stars = Stars(self.background, self.WIDTH, self.HEIGHT, self.TOTAL_STARS) self.asteroid = Asteroid() self.spaceship = Spaceship() self.main()
class Game: size = None screen = None star_background = None game_field = None game_speed = 1 game_thread = None player = None fps = 60 running = True gameover = False waiting = True font = None padding = 20 score = 0 random_color = [255, 0, 0] milestone = 2000 hit = 0 highscore = 0 fpsClock = pygame.time.Clock() def __init__(self, size): self.size = size pygame.font.init() self.score = 0 self.star_background = Stars(self.size) self.font = pygame.font.Font("res/font.ttf", 28) self.screen = pygame.display.set_mode(size) if not self.gameover: self.new_game() self.loop() def new_game(self): self.running = True self.waiting = True self.gameover = False self.milestone = 100 self.game_speed = 1 self.lives = 4 self.game_field = GameField(self.size) self.player = Player( [self.size[0] / 2 - Player.size[0] / 2, self.size[1] - 80], [255, 255, 255]) def draw_score(self): fps = self.font.render("x" + str(round(self.game_speed, 2)), False, (255, 255, 255)) self.screen.blit(fps, (self.padding, self.padding)) lives = self.font.render( str(self.lives) + " Lives", False, (255, 255, 255)) self.screen.blit( lives, (self.size[0] - lives.get_width() - self.padding, self.padding)) score = self.font.render(str(int(self.score)), False, (255, 255, 100)) self.screen.blit( score, ((self.size[0] / 2) - score.get_width() / 2, self.padding)) if self.waiting: start = self.font.render("Press any key to start", False, self.random_color) self.screen.blit( start, ((self.size[0] / 2) - start.get_width() / 2, (self.size[1] - start.get_height()) - self.padding - 140)) if self.gameover or self.waiting: highscore = self.font.render( "Highscore: " + str(int(self.highscore)), False, (255, 255, 255)) self.screen.blit(highscore, ((self.size[0] / 2) - highscore.get_width() / 2, self.padding + self.size[1] / 2)) def render_game(self): self.star_background.render(self.screen) self.game_field.render(self.screen) self.player.render(self.screen) self.draw_score() def update_score(self): if not self.gameover: self.score += self.game_speed * 0.1 if self.score > self.highscore: self.highscore = self.score def game_over_animation(self): if self.game_speed > 0.5: self.game_speed -= 0.01 if self.player.pos[1] < self.size[1]: self.player.pos[1] += 0.5 else: new = True for obj in self.game_field.objects: if obj.pos[1] < self.size[1]: new = False if new: self.new_game() def update_game(self): self.star_background.update(2 * self.game_speed) if self.score > self.milestone and not self.waiting: self.milestone += 250 * self.game_speed * self.game_speed print(self.milestone) self.game_speed += 0.5 if not self.waiting: self.game_field.update(4 * self.game_speed, self.gameover) self.update_score() if self.lives <= 0: self.gameover = True if self.game_field.is_colliding(self.player): if not self.lives <= 0: self.lives -= 1 self.hit = 10 self.player.update(4 * self.game_speed, self.size[0]) def event_handling(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False if not self.waiting and not self.gameover: if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: self.player.move_left = True if event.key == pygame.K_RIGHT: self.player.move_right = True if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: self.player.move_left = False if event.key == pygame.K_RIGHT: self.player.move_right = False if self.waiting: if event.type == pygame.KEYDOWN: self.score = 0 self.game_speed = 1 self.waiting = False def animation_handling(self): if self.gameover: self.game_over_animation() if self.hit > 0: self.hit -= 1 def calc_colors(self): j = 0 while j < len(self.random_color): self.random_color[j] += (j + 1) * 10 if self.random_color[j] > 255: self.random_color[j] = 0 j += 1 def loop(self): while self.running: if self.hit == 0: self.screen.fill((0, 0, 0)) else: self.screen.fill(self.random_color) self.animation_handling() self.calc_colors() self.event_handling() self.update_game() self.render_game() pygame.display.flip() self.fpsClock.tick(self.fps)
class SpaceRacer(): """Represents the game itself""" def __init__(self): """Creates all game objects needed, loads resources, initializes pygame library and sound mixer, sets display mode, etc.""" self.state = STATE_TITLE pygame.mixer.pre_init(buffer=SOUND_BUFFER) pygame.init() self.clock = Clock() self.scr = pygame.display.set_mode(SCREEN_SIZE, VID_MODE_FLAGS) pygame.display.set_caption(WINDOW_CAPTION) pygame.mouse.set_visible(False) LoadingScreen(self.scr).draw() sound_box.init() self.level = GameLevel() self.stats = GameStats(self.scr) self.view_pt = ViewPoint(self.scr) self.stars = Stars(self.scr, self.view_pt) self.track = Track(self.scr, self.view_pt) self.explosions = Explosions(self.scr, self.view_pt) self.ship = Ship(self.scr, self.view_pt, self.explosions) self.asteroids = Asteroids(self.scr, self.view_pt, self.explosions, self.track) self.title_screen = TitleScreen(self.scr, self.view_pt, self.stars) self.level_start_screen = LevelStartScreen(self.scr) self.level_complete_effect = LevelCompleteEffect(self.scr) self.game_over_effect = GameOverEffect(self.scr) self.pause_screen = PauseScreen(self.scr) self.ending_screen = EndingScreen(self.scr) self._init_title() def run(self): """The only public method just runs the game. It starts infinite loop where game objects are updated, drawn and interacts with each other. Also system events are processed.""" while True: self.clock.tick(FRAMERATE) # print(f"FPS: {round(self.clock.get_fps(), 2)}") self._process_events() self._update_objects() self._interact_objects() self._draw_objects() def _init_title(self): self.state = STATE_TITLE self.stats.reset() self.level.restart() self.title_screen.restart() self.title_screen.play_music() def _init_level_starting(self): self.state = STATE_LEVEL_STARTING self.level_start_screen.set_level_number(self.level.get_level()) self.level_start_screen.set_subtitle_text(self.level.get_description()) self.level_start_screen.restart() def _init_level_playing(self): self.state = STATE_LEVEL_PLAYING self.level.play_music() self.view_pt.reset() self.stars.respawn() self.track.set_tile_map(self.level.get_map()) top_limit = (self.track.get_track_height() - self.scr.get_rect().height / 2) bottom_limit = self.scr.get_rect().height / 2 self.view_pt.set_limits(top=top_limit, bottom=bottom_limit) self.explosions.items.empty() self.asteroids.set_spawn_density(self.level.get_asteroids_density()) self.asteroids.respawn(self.level.get_asteroid_spawns()) self.ship.set_speed(self.level.get_ship_speed()) self.ship.set_acceleration(self.level.get_ship_acceleration()) self.ship.restore((0, 0), reset_control=True) def _init_level_finishing(self): self.state = STATE_LEVEL_FINISHING self.stats.increase_score(LEVEL_COMPLETE_PTS) self.level_complete_effect.restart() self.ship.set_autopilot() pygame.mixer.music.fadeout(MUSIC_FADEOUT) def _init_game_over(self): self.state = STATE_GAME_OVER self.game_over_effect.restart() pygame.mixer.music.fadeout(MUSIC_FADEOUT) def _init_ending(self): self.state = STATE_ENDING self.ending_screen.set_score(self.stats.score) self.ending_screen.restart() self.ending_screen.play_music() def _init_pause(self): self.state = STATE_PAUSE self.pause_screen.refresh_background() pygame.mixer.music.pause() def _ship_control(self, key, control_status): """Returns True if the key was a ship direction control key.""" key_processed = True if key == pygame.K_UP: self.ship.moving_up = control_status elif key == pygame.K_DOWN: self.ship.moving_down = control_status elif key == pygame.K_LEFT: self.ship.moving_left = control_status elif key == pygame.K_RIGHT: self.ship.moving_right = control_status elif key == pygame.K_SPACE: self.ship.shooting = control_status else: key_processed = False return key_processed def _process_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if self.state == STATE_TITLE: if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: sys.exit() elif event.key == pygame.K_RETURN: pygame.mixer.music.fadeout(MUSIC_FADEOUT) self._init_level_starting() elif self.state == STATE_PAUSE: if event.type == pygame.KEYDOWN: if event.key in (pygame.K_ESCAPE, pygame.K_PAUSE): self.state = STATE_LEVEL_PLAYING pygame.mixer.music.unpause() elif event.key == pygame.K_RETURN: sys.exit() elif self.state == STATE_LEVEL_PLAYING: if event.type == pygame.KEYDOWN: if event.key in (pygame.K_ESCAPE, pygame.K_PAUSE): self._init_pause() else: self._ship_control(event.key, control_status=True) elif event.type == pygame.KEYUP: self._ship_control(event.key, control_status=False) if self.state == STATE_ENDING: if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: sys.exit() elif event.key == pygame.K_RETURN: self._init_title() def _update_objects(self): if self.state == STATE_TITLE: self.title_screen.update() if self.state == STATE_LEVEL_STARTING: self.level_start_screen.update() if self.state in (STATE_LEVEL_PLAYING, STATE_LEVEL_FINISHING, STATE_GAME_OVER): self.view_pt.update() self.stars.update() self.track.update() self.asteroids.update() self.ship.update() self.explosions.update() if self.state == STATE_LEVEL_FINISHING: self.level_complete_effect.update() if self.state == STATE_GAME_OVER: self.game_over_effect.update() if self.state == STATE_ENDING: self.ending_screen.update() def _crossed_finish_line(self): finish_line_y = (self.track.get_track_height() - self.scr.get_rect().height / 2) return self.ship.y > finish_line_y def _interact_objects(self): if self.state == STATE_LEVEL_STARTING: if self.level_start_screen.finished(): self._init_level_playing() elif self.state == STATE_LEVEL_PLAYING: if self.stats.game_over(): self._init_game_over() elif self._crossed_finish_line(): self._init_level_finishing() elif self.ship.status == SHIP_STATUS_NORMAL: self._check_collisions() elif self.ship.status == SHIP_STATUS_INACTIVE: self._ship_restore() elif self.state == STATE_LEVEL_FINISHING: if self.level_complete_effect.finished(): if self.level.last_level(): self._init_ending() else: self.level.next_level() self._init_level_starting() elif self.state == STATE_GAME_OVER: if self.game_over_effect.finished(): self._init_title() def _draw_objects(self): if self.state == STATE_TITLE: self.title_screen.draw() if self.state == STATE_PAUSE: self.pause_screen.draw() if self.state == STATE_LEVEL_STARTING: self.level_start_screen.draw() if self.state in (STATE_LEVEL_PLAYING, STATE_LEVEL_FINISHING, STATE_GAME_OVER): self.scr.blit(self.level.get_background(), (0, 0)) self.stars.draw() self.track.draw() self.asteroids.draw() self.ship.draw() self.explosions.draw() self.stats.draw() if self.state == STATE_LEVEL_FINISHING: self.level_complete_effect.draw() if self.state == STATE_GAME_OVER: self.game_over_effect.draw() if self.state == STATE_ENDING: self.ending_screen.draw() pygame.display.flip() def _ship_explode(self, collide_point=None): """collide_point is a tuple of absolute coordinates: (x, y)""" self.stats.lost_life() self.ship.explode(collide_point) def _ship_restore(self): restore_x, restore_y = self.ship.get_center() borders = self.track.get_track_borders(restore_y) if borders: restore_x = mean(borders) if self.ship.restore((restore_x, restore_y)): self.asteroids.explode_nearest(self.ship.get_center()) def _check_ship_penalty(self): borders = self.track.get_track_borders(self.ship.get_center()[1]) if borders: left = self.ship.x right = left + self.ship.rect.width if right < borders[0] or left > borders[1]: self._ship_explode() return True return False def _check_collisions(self): collide_point = self.track.collidemask(self.ship.mask, self.ship.rect) if collide_point: self._ship_explode(collide_point) return True collide_point = self.asteroids.collidemask(self.ship.mask, self.ship.rect, explode=True) if collide_point: self._ship_explode(collide_point) return True if self.ship.laser.shooting(): if self.asteroids.collidemask(self.ship.laser.mask, self.ship.laser.rect, explode=True): self.stats.increase_score(ASTEROID_HIT_PTS) return self._check_ship_penalty()
def run(tk): s = Canvas(tk, width = 800, height = 800, background = "blue") s.grid(row = 0, column = 0) pond = PhotoImage(file = "pond.gif") pondO = None queue = Queue() shared = Array('i', [0, 0, 0]) paused = Array('i', [1, 1, 0, 1]) stars = Stars(queue, shared, paused) stars.start() sleep(0.01) main = MainThread(queue, shared, paused) main.start() sleep(0.01) rain = Rain(queue, shared, paused) rain.start() sleep(0.01) clouds = Clouds(queue, shared, paused) clouds.start() while True: contA = [] while len(contA) < 4: try: task = queue.get(block = False) except: pass else: try: if task.oper == "create": object = s._create(task.object, task.coords, task.kw) task.pipeSend.send(object) elif task.oper == "config": s.config(task.kw) elif task.oper == "coords": s.coords(task.object, task.coords) elif task.oper == "itemconfig": s.itemconfig(task.object, task.kw) elif task.oper == "cont": contA.append(1) except: break if pondO == None: pondO = s.create_image(150, 700, image = pond) try: s.update() except: break paused[0] = 0 paused[1] = 0 paused[2] = 0 paused[3] = 0
if event.key == K_ESCAPE: self.gameEnd = True def gameLoop(self): self.getScreen() contador = 0 while self.gameEnd == False: if contador > 20: self.controllerAnimation = True if contador >= 20 and contador < 40: self.controllerAnimation = False if contador > 40: contador = 0 contador += 1 print(contador) self.getClock() self.input(player) self.update() self.render(stars, player) gamePlay = GamePlay() gamePlay.makeMatrix() player = Player(gamePlay.getScreenSize(), gamePlay.getScreenSize()[0] * 0.5, gamePlay.getScreenSize()[1] * 0.95, 100) stars = Stars(400, gamePlay.getScreenSize()) gamePlay.gameLoop()
class Screen(object): def __init__(self, width=640, height=400, fps=60, stars=200): self.running = True self.score = 0 # CONSTANT self.FPS = fps self.PLAYTIME = 0.0 self.TOTAL_STARS = stars self.WIDTH = width self.HEIGHT = height # INITIALIZE SCREEN, CLOCK, FONT self.screen = pygame.display.set_mode((self.WIDTH, self.HEIGHT), pygame.DOUBLEBUF) self.background = pygame.Surface(self.screen.get_size()).convert(self.screen) self.clock = pygame.time.Clock() self.font = pygame.font.SysFont('mono', 20, bold=True) # INITIALIZE SCREEN OBJECTS self.stars = Stars(self.background, self.WIDTH, self.HEIGHT, self.TOTAL_STARS) self.asteroid = Asteroid() self.spaceship = Spaceship() self.main() def exit(self): pygame.quit() sys.exit() def fps_and_playtime_caption(self): text = "FPS: {0:.2f} Playtime: {1:.2f} SCORE: {}".format(self.clock.get_fps(), self.PLAYTIME, self.score) pygame.display.set_caption(text) def is_valid_move(self): return self.spaceship.x in range(0, self.WIDTH) and self.spaceship.y in range(0, self.HEIGHT) def main(self): while self.running: # PLAYTIME milliseconds = self.clock.tick(self.FPS) self.PLAYTIME += milliseconds / 1000.0 # MOVEMENT for event in pygame.event.get(): self.spaceship.move_route(pygame.key.get_pressed()) # DRAW SPACESHIP if self.is_valid_move: self.spaceship.draw(self.screen) # INITIALIZE BACKGROUND, DRAW STARS self.background.fill((0, 0, 0)) for star in self.stars.positions: self.stars.draw(star) # UPDATE CAPTION self.fps_and_playtime_caption() # MAKE SCREEN self.screen.blit(self.background, (0, 0)) # DRAW ASTEROIDS, PROJECTILES self.asteroid.asteroid_list.draw(self.screen) for comet in self.asteroid.asteroid_list: comet.update() self.projectile.projectile_list.draw(self.screen) for ammo in self.projectile.projectile_list: ammo.update() # COLLIDE CHECK asteroid_hit_list = pygame.sprite.spritecollide(ammo, self.asteroid.asteroid_list, True) self.score = len(asteroid_hit_list) pygame.display.update()
class MainConstructor(): def __init__ (self, mainMenuSound, soundMouse, soundSpace, soundGun, soundClick, takeSomething, soundCoin, soundSpaceShip): self.spaceShip = SpaceShip(width/2, height/2+150, 150, 150, 5, soundGun, takeSomething, soundCoin) self.enemy = Enemy(random(0+75/2, width-75/2), -300, 75, 75, 3) self.spaceShip.setEnemy(self.enemy) self.objects = Objects(soundGun) self.spaceShip.setSecondWeapon(self.objects.secondWeapon) self.spaceShip.setSecondWeaponTimer(self.objects.secondWeaponTimer) self.dropedObjects = DropedObjects(random(0+25, width-25), -2400, 50, 50, 2, random(0+25, width-25)) self.spaceShip.setDropedSecondWeapon(self.dropedObjects.dropedSecondWeapon) self.stars = Stars() self.gameState = False self.buttonToStartGame = StartGame(width/2, height/2, 100, 50) self.mainMenuSound = mainMenuSound self.mainMenuSound.loop() self.soundMouse = soundMouse self.soundSpace = soundSpace self.soundClick = soundClick self.soundSpaceShip = soundSpaceShip def game(self, mouseState): if self.gameState == False: self.soundClick.rewind() self.soundSpace.rewind() self.buttonToStartGame.run() newGameState = self.buttonToStartGame.pressed(mouseState) self.soundSpaceShip.pause() if newGameState: self.mainMenuSound.pause() self.soundSpaceShip.loop() self.gameState = newGameState self.spaceShip.score.timer.workTimer(self.spaceShip.score.bestScore, self.buttonToStartGame.x, self.buttonToStartGame.y) self.enemy.spawn() aiming = self.buttonToStartGame.aiming() if aiming: self.soundMouse.play() else: self.soundMouse.rewind() self.soundMouse.pause() else: self.soundClick.play() self.soundSpace.play() self.spaceShip.score.timer.restartOptions() self.run() def run(self): self.stars.run() self.spaceShip.run() self.enemy.run(self.spaceShip.firstWeapon.listOfBullets, self.objects.secondWeapon.listOfBullets) self.objects.run() self.dropedObjects.run() newGameState = self.spaceShip.setGameState(self.gameState) if newGameState == False: self.mainMenuSound.rewind() self.mainMenuSound.loop() self.gameState = newGameState def shootWithFirstWeapon(self): if self.gameState: if self.spaceShip.state == 'ShootWithFirstGun': self.spaceShip.firstWeapon.runToShoot(self.spaceShip.x) def shootWithSecondWeapon(self): if self.gameState: if self.spaceShip.state == 'ShootWithSecondGun': self.objects.secondWeapon.shoot(self.spaceShip.x)
def run_game(): pygame.init() numberOfLives = 3 clock = pygame.time.Clock() ai_settings = Settings() screen_height = ai_settings.screen_height screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height), pygame.FULLSCREEN | pygame.DOUBLEBUF | pygame.HWSURFACE) screen.fill(ai_settings.bg_color, (0, 0, ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") ship = Ship(ai_settings, screen) stars = Stars(ai_settings, screen) bullet = Bullet(ai_settings, screen, ship) starIndex = 0 star_list = [Stars(ai_settings, screen) for i in range(200)] alienFrequency = 0 alienIndex = 0 aliens = [Alien(ai_settings, screen) for i in range(200)] bullets = [bullet] reload = Timer(ai_settings, screen) alien_odds = ai_settings.alien_frequency explosions = [] refreshFPS = 10 avgFPS = 0 delay = 0 pygame.mixer.music.load('Assets/Sounds/explosion.mp3') myfont = pygame.font.SysFont("monospace", 10) livesfont = pygame.font.SysFont("monospace", 30) gameOver = pygame.font.SysFont("monospace", 60) UI_color = (100, 100, 110) pause = 0 paused = False gameOverMessage = "" while True: gf.update_screen(ai_settings, screen, ship, star_list, bullets, aliens, explosions, reload, delay) alienFrequency = int(pygame.time.get_ticks() / 1000) clock.tick() delay = clock.get_time() gf.check_events(ai_settings, screen, ship, bullets, reload) if pause <= 0 and paused: paused = False numberOfLives = 3 ship.reset() gameOverMessage = "" screen.fill(ai_settings.bg_color, (700, 450, 600, 200)) alienFrequency = 0 else: pause -= delay if paused == False: oddsStar = randint(0, 10) oddsAlien = randint(0, alienFrequency) for alien in aliens: if pygame.sprite.collide_rect(ship, alien): alien.erase() alien.reset() pygame.mixer.music.play(0) explosions.append(Explosion(ship)) numberOfLives -= 1 if numberOfLives == 0: ship.erase() ship.centerX[0] = -10000 gameOverMessage = "GAME OVER!!!" for alien in aliens: explosions.append(Explosion(alien)) alien.erase() alien.reset() pause = 3000 paused = True for alien in aliens: for bullet in bullets: if alien.rect.collidepoint(bullet.rect.x, bullet.rect.y): pygame.mixer.music.play(0) explosions.append(Explosion(alien)) bullets.remove(bullet) alien.erase() alien.reset() reload.update(delay) if oddsStar == 10: star_list[starIndex % 200].activate() starIndex += 1 if oddsAlien >= 100: aliens[alienIndex % 200].activate() alienIndex += 1 if bullets: if bullets[0].y < 0: bullets[0].erase() bullets.pop(0) screen.fill(UI_color, (0, 0, 100, 100)) label = myfont.render(str(int(clock.get_fps())), 1, (255, 255, 0)) lives = myfont.render("LIVES REMAINING :", 1, (255, 255, 0)) remaining = livesfont.render(str(numberOfLives), 1, (255, 255, 0)) gg = gameOver.render(gameOverMessage, 1, (255, 255, 0)) screen.blit(label, (0, 0)) screen.blit(lives, (0, 30)) screen.blit(remaining, (20, 45)) screen.blit(gg, (700, 450)) pygame.display.flip()