def run_game(): """Initialize game.""" pygame.init() ai_settings = Settings() screen = pygame.display.set_mode(( ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Domination") rocket = Rocket(screen) # 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() # Redraw the screen during each pass through the loop. screen.fill(ai_settings.bg_color) rocket.blitme() # Make the most recently drawn screen visible. pygame.display.flip()
class Rocket_Game(): ''' simple rocket on screen that can move up down left right ''' def __init__(self): pygame.init() self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) self.screen_width = self.screen.get_rect().width self.screen_height = self.screen.get_rect().height self.settings = Settings() self.settings.screen_width = self.screen.get_rect().width self.settings.screen_height = self.screen.get_rect().height self.bg_color = self.settings.bg_color self.ship = Rocket(self) def run_game(self): '''Start main loop for game''' while True: self._check_events() self.ship.update() self._update_screen() def _update_screen(self): self.screen.fill(self.bg_color) self.ship.blitme() # Make most recently drawn screen visible pygame.display.flip() def _check_events(self): # Watch for events for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._self_check_key_down(event) elif event.type == pygame.KEYUP: self._self_check_key_up(event) def _self_check_key_down(self, event): ''' Checks key down events ''' if event.key == pygame.K_RIGHT: self.ship.moving_right = True elif event.key == pygame.K_LEFT: self.ship.moving_left = True elif event.key == pygame.K_UP: self.ship.moving_up = True elif event.key == pygame.K_DOWN: self.ship.moving_down = True elif event.key == pygame.K_q: sys.exit() def _self_check_key_up(self, event): ''' Checks the key up events ''' if event.key == pygame.K_RIGHT: self.ship.moving_right = False elif event.key == pygame.K_LEFT: self.ship.moving_left = False elif event.key == pygame.K_UP: self.ship.moving_up = False elif event.key == pygame.K_DOWN: self.ship.moving_down = False
def run_game(): pygame.init() screen = pygame.display.set_mode((800, 400)) pygame.display.set_caption('Rocket Fire!!!') bg_color = (66, 106, 175) screen.fill(bg_color) rocket = Rocket(screen) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: rocket.moving_up = True elif event.key == pygame.K_DOWN: rocket.moving_down = True elif event.type == pygame.KEYUP: if event.key == pygame.K_UP: rocket.moving_up = False elif event.key == pygame.K_DOWN: rocket.moving_down = False rocket.update() rocket.blitme() pygame.display.flip()
class RocketGame: """Overall class to manage game assets and behavior.""" def __init__(self): """Initialize the game, and create game resources.""" pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption("Rocket Game") self.rocket = Rocket(self) def run_game(self): """Start the main loop for the game.""" while True: self._check_events() self.rocket.update() self._update_screen() def _check_events(self): """Respond to keypresses and mouse events.""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) def _check_keydown_events(self, event): """Respond to keypresses.""" if event.key == pygame.K_RIGHT: self.rocket.moving_right = True elif event.key == pygame.K_LEFT: self.rocket.moving_left = True if event.key == pygame.K_UP: self.rocket.moving_up = True elif event.key == pygame.K_DOWN: self.rocket.moving_down = True elif event.key == pygame.K_q: sys.exit() def _check_keyup_events(self, event): """Respond to key releases.""" if event.key == pygame.K_RIGHT: self.rocket.moving_right = False elif event.key == pygame.K_LEFT: self.rocket.moving_left = False if event.key == pygame.K_UP: self.rocket.moving_up = False elif event.key == pygame.K_DOWN: self.rocket.moving_down = False def _update_screen(self): """Update images on the screen, and flip to the new screen.""" self.screen.fill(self.settings.bg_color) self.rocket.blitme() pygame.display.flip()
def move_rocket(): pygame.init() screen = pygame.display.set_mode((1200, 800)) pygame.display.set_caption("Rocket Moves") rocket = Rocket(screen) moving_right = False moving_left = False moving_up = False moving_down = False while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: moving_right = True moving_left = False moving_up = False moving_down = False elif event.key == pygame.K_LEFT: moving_right = False moving_left = True moving_down = False moving_up = False elif event.key == pygame.K_UP: moving_right = False moving_left = False moving_up = True moving_down = False elif event.key == pygame.K_DOWN: moving_right = False moving_left = False moving_up = False moving_down = True elif event.type == pygame.KEYUP: moving_right = False moving_left = False moving_up = False moving_down = False if moving_right and rocket.rect.right < rocket.screen_rect.right: rocket.rect.centerx = rocket.rect.centerx + 1 elif moving_left and rocket.rect.left > 0: rocket.rect.centerx = rocket.rect.centerx - 1 elif moving_up and rocket.rect.top > 0: print(rocket.rect.top) rocket.rect.bottom = rocket.rect.bottom - 1 elif moving_down and rocket.rect.bottom < rocket.screen_rect.bottom: rocket.rect.bottom = rocket.rect.bottom + 1 #print("Rocket top - "+str(rocket.rect.bottom)+" screen top - "+str(rocket.screen_rect.bottom)) screen.fill((255, 255, 255)) rocket.blitme() pygame.display.flip()
class FlyingRocket: def __init__(self): pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption("Flying a Rocket East West South and North") self.bg_color = self.settings.bgcolor self.rocket = Rocket(self) def fly_rocket(self): while True: self._check_events() self.rocket.update() self._update_screen() def _check_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: self._check_keydown_events(event) if event.type == pygame.KEYUP: self._check_keyup_events(event) def _update_screen(self): self.screen.fill(self.bg_color) self.rocket.blitme() pygame.display.flip() def _check_keydown_events(self, event): """Respond to keypress -- KeyDown""" if event.key == pygame.K_RIGHT: self.rocket.moving_right = True elif event.key == pygame.K_LEFT: self.rocket.moving_left = True elif event.key == pygame.K_UP: self.rocket.moving_up = True elif event.key == pygame.K_DOWN: self.rocket.moving_down = True elif event.key == pygame.K_q: sys.exit() def _check_keyup_events(self, event): if event.key == pygame.K_RIGHT: self.rocket.moving_right = False elif event.key == pygame.K_LEFT: self.rocket.moving_left = False elif event.key == pygame.K_UP: self.rocket.moving_up = False elif event.key == pygame.K_DOWN: self.rocket.moving_down = False
class RocketGame: """Contains the basic functionality of the rocket""" def __init__(self): pygame.init() self.setting = RocketSettings() self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) pygame.display.set_caption("Rocket Game") self.rocket = Rocket(self) def game_loop(self): while True: self._check_events() self.rocket.update() self._update_screen() def _check_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: self._keydown_events(event) if event.type == pygame.KEYUP: self._keyup_events(event) def _update_screen(self): self.screen.fill(self.setting.bg_color) self.rocket.blitme() pygame.display.flip() def _keydown_events(self, event): if event.key == pygame.K_q: sys.exit() if event.key == pygame.K_RIGHT: self.rocket.moving_right = True if event.key == pygame.K_LEFT: self.rocket.moving_left = True if event.key == pygame.K_UP: self.rocket.moving_top = True if event.key == pygame.K_DOWN: self.rocket.moving_bottom = True def _keyup_events(self, event): if event.key == pygame.K_RIGHT: self.rocket.moving_right = False if event.key == pygame.K_LEFT: self.rocket.moving_left = False if event.key == pygame.K_UP: self.rocket.moving_top = False if event.key == pygame.K_DOWN: self.rocket.moving_bottom = False
class RocketGame: """Create a game with a rocket that can move around the window""" def __init__(self): pygame.init() self.screen = pygame.display.set_mode((1200, 800)) self.rocket = Rocket(self) def run_game(self): while True: self._check_events() self.rocket.update() self._update_screen() def _check_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) def _check_keydown_events(self, event): """Check for keydown events""" if event.key == pygame.K_RIGHT: self.rocket.moving_right = True elif event.key == pygame.K_LEFT: self.rocket.moving_left = True elif event.key == pygame.K_UP: self.rocket.moving_up = True elif event.key == pygame.K_DOWN: self.rocket.moving_down = True elif event.key == pygame.K_q: sys.exit() def _check_keyup_events(self, event): """Check for keyup events""" if event.key == pygame.K_RIGHT: self.rocket.moving_right = False elif event.key == pygame.K_LEFT: self.rocket.moving_left = False elif event.key == pygame.K_UP: self.rocket.moving_up = False elif event.key == pygame.K_DOWN: self.rocket.moving_down = False def _update_screen(self): """Update images on the screen, and flip to the new screen""" self.screen.fill((250, 250, 250)) self.rocket.blitme() pygame.display.flip()
def run_game(): pygame.init() pygame.display.set_caption("Rocket Game") screen = pygame.display.set_mode((1600, 900)) rocket = Rocket(screen) while True: rocket.listen_movement() rocket.update() # Redraw screen screen.fill((255, 255, 255)) rocket.blitme() pygame.display.flip()
class Space: def __init__(self): pygame.init() self.screen = pygame.display.set_mode((1200, 800)) pygame.display.set_caption("Rocket in Space") self.bg_color = (0, 0, 0) self.rocket = Rocket(self) def _event_keypressed(self, event): if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: self.rocket.moving_right = True elif event.key == pygame.K_LEFT: self.rocket.moving_left = True elif event.key == pygame.K_DOWN: self.rocket.moving_down = True elif event.key == pygame.K_UP: self.rocket.moving_up = True elif event.key == pygame.K_ESCAPE: sys.exit() def _event_keyreleased(self, event): if event.key == pygame.K_RIGHT: self.rocket.moving_right = False elif event.key == pygame.K_LEFT: self.rocket.moving_left = False elif event.key == pygame.K_DOWN: self.rocket.moving_down = False elif event.key == pygame.K_UP: self.rocket.moving_up = False def run_game(self): while True: for event in pygame.event.get(): if event.type == pygame.KEYUP: self._event_keyreleased(event) elif event.type == pygame.KEYDOWN: self._event_keypressed(event) self.screen.fill(self.bg_color) self.rocket.update_movement() self.rocket.blitme() pygame.display.flip()
class AlienInvasion: """Overall class to manage game assets and behavior.""" def __init__(self): """Initialize the game, and create game resources.""" pygame.init() # General settings self.settings = Settings() # Screen self.screen = pygame.display.set_mode( (self.settings.width, self.settings.height)) pygame.display.set_caption(self.settings.title) # Rocket self.rocket = Rocket(self) def run_game(self): """Start the main loop for the game.""" while True: # Get events self.get_events() self.rocket.update() self.update_screen() def get_events(self): # Watch for keyboard and mouse events. for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: # Move to the right. self.rocket.moving_right = True elif event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT: self.rocket.moving_right = False def update_screen(self): # Redraw the screen during each pass through the loop. self.screen.fill(self.settings.color) self.rocket.blitme() # Make the most recently drawn screen visible. pygame.display.flip()
def run_game(): # Initialize pygame pygame.init() # Set title of screen pygame.display.set_caption("STO") #Set settings from settings.py ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) #create rocket rocket_1 = Rocket(screen) # 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 == K_ESKAPE: done = True""" # Set the screen background screen.fill(ai_settings.bg_color) rocket_1.blitme() # Limit to 60 frames per second clock.tick(60) # Go ahead and update the screen with what we've drawn. pygame.display.flip()
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("圣诞大战") # 创建一艘火箭 rocket = Rocket(screen) # 开始游戏的主循环 while True: # 监视键盘和鼠标事件 for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() # 每次循环时都重绘屏幕 screen.fill(ai_settings.bg_color) rocket.blitme() # 让最近绘制的屏幕可见 pygame.display.flip()
def run_window(): """Initialize game window, and make background blue.""" pygame.init screen = pygame.display.set_mode((1200, 800)) pygame.display.set_caption("rocket...") # Set the background color bg_color = (199, 199, 199) # Make rocket rocket = Rocket(screen) # Game's main loop. while True: rf.check_events(rocket) rocket.update() # Redraw the screen during each pass of the loop screen.fill(bg_color) rocket.blitme() # Make the most recently drawn screen visible. pygame.display.flip()
class Game: def __init__(self): pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode(self.settings.scr_sz) self.bullets = pygame.sprite.Group() self.aliens = pygame.sprite.Group() self.rocket = Rocket(self) pygame.display.set_caption("Sideways Shooter") self._create_fleet() def run_game(self): while True: self._check_events() self.rocket.update() self._update_aliens() self._update_bullets() self._update_screen() def _check_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit(0) elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) def _check_keydown_events(self, event): if event.key == pygame.K_q: sys.exit(0) elif event.key == pygame.K_UP: self.rocket.moving_up = True elif event.key == pygame.K_DOWN: self.rocket.moving_down = True elif event.key == pygame.K_SPACE: self._fire_bullet() def _check_keyup_events(self, event): if event.key == pygame.K_UP: self.rocket.moving_up = False elif event.key == pygame.K_DOWN: self.rocket.moving_down = False def _update_bullets(self): self.bullets.update() screen_rect = self.screen.get_rect() for bullet in self.bullets.copy(): if bullet.rect.left > screen_rect.right: self.bullets.remove(bullet) # 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 not self.aliens: # Destroy existing bullets and create new fleet self.bullets.empty() self._create_fleet() # print(len(self.bullets)) def _fire_bullet(self): """Create a new bullet and add it to the bullets group.""" if len(self.bullets) < self.settings.bullets_allowed: new_bullet = Bullet(self) self.bullets.add(new_bullet) def _create_fleet(self): alien = Alien(self) alien_width, alien_height = alien.rect.size available_space_y = self.settings.scr_sz[1] - (alien_height) number_aliens_y = available_space_y // (2 * alien_height) rocket_width = self.rocket.rect.width available_space_x = (self.settings.scr_sz[0] - (4 * alien_width) - rocket_width) number_lines = available_space_x // (2 * alien_width) for line_number in range(number_lines): for alien_number in range(number_aliens_y): self._create_alien(alien_number, line_number) def _create_alien(self, alien_number, line_number): alien = Alien(self) alien_width, alien_height = alien.rect.size alien.y = alien_height + 2 * alien_height * alien_number alien.rect.y = alien.y alien.rect.x = self.settings.scr_sz[0] - \ (alien.rect.width + 2 * alien.rect.width * line_number) self.aliens.add(alien) def _update_aliens(self): """Updates the positions of all aliens in the fleet.""" self._check_fleet_edges() self.aliens.update() def _check_fleet_edges(self): """Respond appropriately if any aliens have reached an edge.""" for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _change_fleet_direction(self): """Drop the entire fleet and change the fleet's direction.""" for alien in self.aliens.sprites(): alien.rect.x -= self.settings.fleet_left_speed self.settings.fleet_direction *= -1 def _update_screen(self): """Updates images on the screen, and flip to the new screen.""" # Redraw the screen during each pass through the loop. self.screen.fill(self.settings.bg_color) self.rocket.blitme() for bullet in self.bullets.sprites(): bullet.draw_bullet() self.aliens.draw(self.screen) # Make the mose recently drawn screen visible pygame.display.flip()
class SidewaysRocket: """overrall class to manage assets and behavior""" def __init__(self): """intialize the game, and create resources""" pygame.init() self.settings = Settings() #Sets the window size and caption self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption("Sideways Rocket Game") #Create an instance to store game statistics self.stats = GameStats(self) #import the rocket and make an instance of it self.rocket = Rocket(self) #import the laser sprites self.lasers = pygame.sprite.Group() #import the enemy sprites self.enemies = pygame.sprite.Group() self._create_enemies() def run_game(self): """Start the main loop of the game.""" while True: #watch for keyboard and mouse events self._check_events() if self.stats.game_active: self.rocket.update() self._update_lasers() self._update_enemy() self._update_screen() def _check_events(self): """Respond to keypresses and mouse events.""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) def _update_screen(self): """Update images on the screen and flip to a new screen""" #Redraw the screen during each pass through the loop self.screen.fill(self.settings.bg_color) #draw the rocket self.rocket.blitme() #draw lasers for laser in self.lasers.sprites(): laser.draw_laser() #draw the enemies self.enemies.draw(self.screen) #Make the most recently drawn screen visible pygame.display.flip() def _check_keydown_events(self, event): """Respond to keypress down events""" if event.key == pygame.K_w: #move the rocket up self.rocket.moving_up = True elif event.key == pygame.K_s: #move the rocket down self.rocket.moving_down = True #move the rocket to the right elif event.key == pygame.K_d: self.rocket.moving_right = True #move the rocket to the left elif event.key == pygame.K_a: self.rocket.moving_left = True elif event.key == pygame.K_SPACE: self._fire_laser() elif event.key == pygame.K_q: sys.exit() def _check_keyup_events(self, event): """Respond to keypress releases""" #stop moving the rocket if event.key == pygame.K_w: self.rocket.moving_up = False if event.key == pygame.K_s: self.rocket.moving_down = False if event.key == pygame.K_d: self.rocket.moving_right = False if event.key == pygame.K_a: self.rocket.moving_left = False def _fire_laser(self): """Create a new laser and add it to the lasers group""" if len(self.lasers) < self.settings.lasers_allowed: new_laser = Laser(self) self.lasers.add(new_laser) def _update_lasers(self): """Update the position of lasers and get rid of old lasers""" #update laser positions self.lasers.update() #Get rid of bullets that have disappeared for laser in self.lasers.copy(): if laser.rect.left >= self.rocket.screen_rect.right: self.lasers.remove(laser) self._check_laser_enemy_collisons() def _create_enemies(self): """Create an enemy ship""" enemy_number = random.randint(1,5) for _ in range(enemy_number): enemy = Enemy(self) enemy.rect.y = random.randint(1, self.settings.screen_height - 50) self.enemies.add(enemy) def _update_enemy(self): """move the enemy to the left""" self.enemies.update() for enemy in self.enemies.copy(): if enemy.rect.right <= 0: self.enemies.remove(enemy) #look for enemy-rocket collision if pygame.sprite.spritecollideany(self.rocket, self.enemies): self._rocket_hit() def _check_laser_enemy_collisons(self): #check for any lasers that have hit enemies #if so get rid of the alien and the bullet collisions = pygame.sprite.groupcollide(self.lasers, self.enemies, True, True) if not self.enemies: #destroy lasers and create a new fleet. self.lasers.empty() self._create_enemies() def _rocket_hit(self): if self.stats.rockets_left > 0: #decreaset the remaining rockets self.stats.rockets_left -= 1 #get rid of any remaining self.enemies.empty() self.lasers.empty() #Pause sleep(0.5) #restore the ship self.rocket.center_rocket() self._create_enemies() else: self.stats.game_active = False
class RocketShip: """Overall class to manage a cartoon rocket's assets and behavior.""" def __init__(self): """Initialize the game and create game resources.""" pygame.init() self.settings = RocketSettings() self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) self.screen_rect = self.screen.get_rect() pygame.display.set_caption("Exercise 12-3") self.rocket = Rocket(self) self.bullets = pygame.sprite.Group() def run_game(self): """Start the main loop for the game.""" while True: self._check_events() self.rocket.update() self._update_bullets() self._update_screen() def _check_events(self): """Respond to keypresses and mouse events.""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) def _check_keydown_events(self, event): """Respond to keypresses""" if event.key == pygame.K_RIGHT: self.rocket.decelerating_right = False self.rocket.moving_right = True elif event.key == pygame.K_LEFT: self.rocket.decelerating_left = False self.rocket.moving_left = True elif event.key == pygame.K_UP: self.rocket.decelerating_up = False self.rocket.moving_up = True elif event.key == pygame.K_DOWN: self.rocket.decelerating_down = False self.rocket.moving_down = True elif (event.key == pygame.K_q) or (event.key == pygame.K_ESCAPE): sys.exit() elif event.key == pygame.K_e: self.rocket.rotating_ccw = True elif event.key == pygame.K_r: self.rocket.rotating_cw = True elif event.key == pygame.K_SPACE: self._fire_bullet() def _check_keyup_events(self, event): """Respond to key releases.""" if event.key == pygame.K_RIGHT: self.rocket.decelerating_right = True elif event.key == pygame.K_LEFT: self.rocket.decelerating_left = True elif event.key == pygame.K_UP: self.rocket.decelerating_up = True elif event.key == pygame.K_DOWN: self.rocket.decelerating_down = True elif event.key == pygame.K_e: self.rocket.rotating_ccw = False elif event.key == pygame.K_r: self.rocket.rotating_cw = False def _fire_bullet(self): """Create a new bullet and add it to the bullets group.""" if len(self.bullets) < self.settings.bullets_allowed: new_bullet = RocketBullet(self) self.bullets.add(new_bullet) new_bullet.calculate_movement() def _update_bullets(self): """Update positions of bullets and get rid of old bullets.""" self.bullets.update() # Get rid of bullets that have disappeared. for bullet in self.bullets.copy(): if bullet.direction == 'up': if bullet.rect.bottom <= 0: self.bullets.remove(bullet) elif bullet.direction == 'upright': if (bullet.rect.bottomleft[0] >= self.screen_rect.right or bullet.rect.bottomleft[1] <= 0): self.bullets.remove(bullet) elif bullet.direction == 'right': if bullet.rect.left >= self.screen_rect.right: self.bullets.remove(bullet) elif bullet.direction == 'downright': if (bullet.rect.topleft[0] >= self.screen_rect.right or bullet.rect.topleft[1] >= self.screen_rect.bottom): self.bullets.remove(bullet) elif bullet.direction == 'down': if bullet.rect.top >= self.screen_rect.bottom: self.bullets.remove(bullet) elif bullet.direction == 'downleft': if (bullet.rect.topright[1] >= self.screen_rect.bottom or bullet.rect.topright[0] <= 0): self.bullets.remove(bullet) elif bullet.direction == 'left': if bullet.rect.right <= 0: self.bullets.remove(bullet) elif bullet.direction == 'upleft': if (bullet.rect.bottomright[0] <= 0 or bullet.rect.bottomright[1] <= 0): self.bullets.remove(bullet) def _update_screen(self): # Update images on the screen and flip to the new screen. self.screen.fill(self.settings.bg_color) self.screen.blit(self.settings.bg_image, (0, 0)) for bullet in self.bullets.sprites(): bullet.draw_bullet() self.rocket.blitme() pygame.display.flip()
def run_game(): '''initilize pygame''' pygame.init() '''settings of window''' video = pygame.display.Info() #объект с разрешением экрана # Set title of screen image_icon = pygame.image.load("icon.ico") pygame.display.set_caption("STR") pygame.display.set_icon(image_icon) WIDTH = video.current_w HEIGHT = video.current_h if video.current_w < 1600: WIDTH = 1200 HEIGHT = 900 if video.current_w == 1440: WIDTH = 1440 HEIGHT = 900 if video.current_w >= 1600: WIDTH = 1600 HEIGHT = 900 screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.FULLSCREEN) #Инициализация окна screen_rect = screen.get_rect() #координаты экрана s = pygame.Surface((WIDTH, HEIGHT)) # the size of your rect s.set_alpha(230) # alpha level s.fill((0, 0, 0)) # this fills the entire surface '''Constants and verables, flags and constants - big words''' global_time = 0.0 #счетчик времени if WIDTH == 1440 or WIDTH == 1600: GLOBAL_L = 340 #длина ракеты расстояние между столбами в покое if WIDTH == 1200: GLOBAL_L = 256 alpha = 0 # относительная скорость GLOBAL_C = 400 # скорость света frame_count = 0 #счетчик фреймов if WIDTH == 1600: border = 70 #граница окон в пикселях if WIDTH == 1440 or WIDTH == 1200: border = 30 '''Флаги''' RUSENG = True #изменение языка GALILEO = True #преобразования галилео DONE = False #флаг главного цикла MOUSE_KLICK = False #обработка клика мышкой LEFT_KLICK = False RIGHT_KLICK = False MENU = True #флаг меню INSTRUCTION = False AUTORS = False mouse_x = 0 mouse_y = 0 frame_rate = 0.0 frame1_ind = 0 frame1_rocket_length = 340 #length of moving rocket RED = (255, 0, 0) WHITE = (255, 255, 255) BLACK = (0, 0, 0) #Background and menu gerb = pygame.image.load('images/Gerb_MGTU_imeni_Baumana.png') gerb = pygame.transform.scale(gerb, (170, 200)) gerb = gerb.convert_alpha() selph = pygame.image.load('images/logo.png') selph = pygame.transform.scale(selph, (368, 200)) selph = selph.convert_alpha() if WIDTH == 1440 or WIDTH == 1200: background = pygame.image.load('images/background_1440.png') background = pygame.transform.scale(background, (WIDTH, HEIGHT)) background = background.convert_alpha() background2 = pygame.image.load('images/background2_1440.png') background2 = pygame.transform.scale(background2, (WIDTH, HEIGHT)) background2 = background2.convert() if WIDTH == 1600: background = pygame.image.load('images/background.png') background = pygame.transform.scale(background, (WIDTH, HEIGHT)) background = background.convert_alpha() background2 = pygame.image.load('images/background2.png') background2 = pygame.transform.scale(background2, (WIDTH, HEIGHT)) background2 = background2.convert() back_menu = pygame.image.load('images/menu.jpg') back_menu = pygame.transform.scale(back_menu, (WIDTH, HEIGHT)) back_menu = back_menu.convert() back_left = pygame.image.load('images/background_left.png') back_left = pygame.transform.scale(back_left, (30, HEIGHT)) back_left = back_left.convert_alpha() back_centr = pygame.image.load('images/background_centr.png') back_centr = pygame.transform.scale(back_centr, (770, HEIGHT)) back_centr = back_centr.convert_alpha() back_right = pygame.image.load('images/background_right.png') back_right = pygame.transform.scale(back_right, (400, HEIGHT)) back_right = back_right.convert_alpha() '''шрифты''' font_1 = pygame.font.SysFont("arial", 18, bold=True) font_2 = pygame.font.Font('fonts\courbd.ttf', 19) font_3 = pygame.font.Font('fonts\mpus.ttf', 22) font_4 = pygame.font.Font('fonts\courierstd-bold.otf', 22) font_5 = pygame.font.Font('fonts\mpus.ttf', 56) def text_1(Ttext, Tcolor, Tlocation): text = font_1.render(Ttext, True, Tcolor) screen.blit(text, Tlocation) def text_2(Ttext, Tcolor, Tlocation): text = font_2.render(Ttext, True, Tcolor) screen.blit(text, Tlocation) def text_3(Ttext, Tcolor, Tlocation): text = font_3.render(Ttext, True, Tcolor) screen.blit(text, Tlocation) def text_4(Ttext, Tcolor, Tlocation): text = font_4.render(Ttext, True, Tcolor) screen.blit(text, Tlocation) def text_5(Ttext, Tcolor, Tlocation): text = font_5.render(Ttext, True, Tcolor) screen.blit(text, Tlocation) '''buttons from module button, arrows ''' if WIDTH == 1600: bt_1 = Change_velocity(screen, 1135, 270, 'images/speed_change.png', '', (200, 100)) #ползунок bt_start = Start(screen, 1200, 420, 'images/start.png', 'images/start_light.png', (140, 50)) bt_pause = Pause(screen, 1350, 420, 'images/pause.png', 'images/pause_light.png', (140, 50)) bt_stop = Stop(screen, 1500, 420, 'images/stop.png', 'images/stop_light.png', (140, 50)) bt_left = Scroll(screen, 1295, 490, 'images/bt_scroll_left_light.png', 'images/bt_scroll_left.png', (100, 60)) bt_right = Scroll(screen, 1405, 490, 'images/bt_scroll_right_light.png', 'images/bt_scroll_right.png', (100, 60)) bt_galileo = Galileo(screen, 1350, 790, 'images/Galileo_off.png', 'images/Galileo_on.png', (360, 50)) bt_ruseng = Ruseng(screen, WIDTH - 100, HEIGHT - 50, 'images/ruseng.png', 'images/ruseng2.png', (50, 25)) if WIDTH == 1440 or WIDTH == 1200: bt_1 = Change_velocity(screen, WIDTH - 350, 270, 'images/speed_change.png', '', (200, 100)) #ползунок bt_start = Start(screen, WIDTH - 305, 420, 'images/start.png', 'images/start_light.png', (120, 40)) bt_pause = Pause(screen, WIDTH - 185, 420, 'images/pause.png', 'images/pause_light.png', (120, 40)) bt_stop = Stop(screen, WIDTH - 65, 420, 'images/stop.png', 'images/stop_light.png', (120, 40)) bt_left = Scroll(screen, WIDTH - 240, 490, 'images/bt_scroll_left_light.png', 'images/bt_scroll_left.png', (100, 60)) bt_right = Scroll(screen, WIDTH - 130, 490, 'images/bt_scroll_right_light.png', 'images/bt_scroll_right.png', (100, 60)) bt_galileo = Galileo(screen, WIDTH - 190, 790, 'images/Galileo_off.png', 'images/Galileo_on.png', (360, 50)) bt_ruseng = Ruseng(screen, WIDTH - 100, HEIGHT - 50, 'images/ruseng.png', 'images/ruseng2.png', (50, 25)) '''create objects''' #function of pillars----------------------------------------------------------------- img_pillar = pygame.image.load('images/pillar3.png') img_pillar = pygame.transform.scale(img_pillar, (102, 192)) img_pillar = img_pillar.convert_alpha() img_pillar_2 = img_pillar rect_pillar = img_pillar.get_rect() #rectangle of image of pillar rect_pillar.bottom = 870 rect_pillar.centerx = 0 x = 0 #coordinate arrow of pillar watches y = 0 def img_load(beta, img_pillar, img_pillar_2): scale = 1 / beta img_pillar = img_pillar_2 img_pillar = pygame.transform.scale(img_pillar, (int(102 / scale), 192)) rect = img_pillar.get_rect() rect.bottom = 870 return (img_pillar, rect) def update_watchup(global_time): x = 25 * math.cos(math.pi / 2 - math.pi / 30 * global_time) y = 25 * math.sin(math.pi / 2 - math.pi / 30 * global_time) return (x, y) def update_watchdown(t, beta): x = 25 * beta * math.cos(math.pi / 2 - math.pi / 30 * t) y = 25 * math.sin(math.pi / 2 - math.pi / 30 * t) return (x, y) def blitme_pillar(screen, color, img, rect, x, y): screen.blit(img, rect) pygame.draw.line(screen, color, (rect.centerx, rect.bottom - 143), (rect.centerx + x, rect.bottom - 143 - y), 2) #-------------------------------------------------------------------------------------------- if WIDTH == 1600: watch1 = Watch(screen, 1200, 150, 'images/watch.png') #часы watch2 = Watch(screen, 1350, 150, 'images/watch.png') watch3 = Watch(screen, 1500, 150, 'images/watch.png') watch4 = Watch(screen, 1200, 670, 'images/watch.png') watch5 = Watch(screen, 1350, 670, 'images/watch.png') watch6 = Watch(screen, 1500, 670, 'images/watch.png') if WIDTH == 1440 or WIDTH == 1200: watch1 = Watch(screen, WIDTH - 315, 150, 'images/watch_1440.png') #часы watch2 = Watch(screen, WIDTH - 190, 150, 'images/watch_1440.png') watch3 = Watch(screen, WIDTH - 65, 150, 'images/watch_1440.png') watch4 = Watch(screen, WIDTH - 315, 670, 'images/watch_1440.png') watch5 = Watch(screen, WIDTH - 190, 670, 'images/watch_1440.png') watch6 = Watch(screen, WIDTH - 65, 670, 'images/watch_1440.png') rocket_1 = Rocket(screen, border + 1.5 * GLOBAL_L, 150, GLOBAL_L) #ракеты rocket_2 = Rocket(screen, border + 1.5 * GLOBAL_L, 580, GLOBAL_L) #watches icons---------------------------------------- img_watchpick = pygame.image.load('images/watchpick.png') img_watchpick = pygame.transform.scale(img_watchpick, (20, 20)) img_watchpick = img_watchpick.convert_alpha() img_watchpick2 = img_watchpick rect_icon = img_watchpick.get_rect() def img_load_icons(beta, img_watchpick, img_watchpick2): scale = 1 / beta img_watchpick = img_watchpick2 img_watchpick = pygame.transform.scale(img_watchpick, (int(20 / scale), 20)) rect = img_watchpick.get_rect() rect.centery = 150 return (img_watchpick, rect) #----------------------------------------------------------- img_a = pygame.image.load('images/A.png') img_a = pygame.transform.scale(img_a, (40, 40)) img_a = img_a.convert_alpha() img_b = pygame.image.load('images/B.png') img_b = pygame.transform.scale(img_b, (40, 40)) img_b = img_b.convert_alpha() img_c = pygame.image.load('images/C.png') img_c = pygame.transform.scale(img_c, (40, 40)) img_c = img_c.convert_alpha() '''timers''' clock = pygame.time.Clock() timer = pygame.time.Clock() timer.tick() '''function str watch timers''' def time_to_string(x): if x < 0: x += 60 * 60 return str(math.floor(x / 60) * 10 + 1001)[1:3] + ':' + str( math.floor(x % 60) * 10 + 1001)[1:3] + ':' + str((x - math.floor(x)) * 1000 + 1001)[1:3] # -------- Main Program Loop ----------- screen.blit(s, (0, 0)) screen.blit(gerb, (screen_rect.centerx - 300, screen_rect.centery - 100)) screen.blit(selph, (screen_rect.centerx, screen_rect.centery - 100)) pygame.display.flip() time.sleep(1.5) while not DONE: mouse_pos = pygame.mouse.get_pos() mouse_x = mouse_pos[0] mouse_y = mouse_pos[1] '''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 elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: MENU = True global_time = 0.0 rocket_1.global_rocket_x = 0.0 rocket_1.global_rocket_x_start = 0 rocket_1.global_rocket_t_start = 0 bt_pause.pause = True alpha = 0 bt_1.bt1_x = bt_1.rect.left rocket_1.img_load() rocket_1.firestop = False rocket_2.firestop = False AUTORS = False if event.key == pygame.K_RIGHT: RIGHT_KLICK = True if event.key == pygame.K_LEFT: LEFT_KLICK = True elif event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT: RIGHT_KLICK = False if event.key == pygame.K_LEFT: LEFT_KLICK = False if event.key == pygame.K_SPACE: bt_pause.pause = False elif event.type == pygame.MOUSEBUTTONDOWN: MOUSE_KLICK = True elif event.type == pygame.MOUSEBUTTONUP: MOUSE_KLICK = False '''Logic''' if not MENU: #преобразования галилео if bt_galileo.flag: GALILEO = True else: GALILEO = False frame_count += 1 frame_rate = clock.get_time() # множитель лоренцевых преобразований beta = math.sqrt(1 - alpha * alpha) #////////////////////////////////////////////////////////////////# #buttons if bt_pause.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True: bt_pause.pause = True else: rocket_1.firestop = True rocket_2.firestop = True if bt_pause.pause: frame_rate = 0 rocket_1.firestop = False rocket_2.firestop = False if bt_left.rect.collidepoint( mouse_pos) and MOUSE_KLICK == True and bt_pause.pause: if global_time > 0: rocket_1.firestop = True rocket_2.firestop = True global_time -= 0.01 / (alpha + 0.01) else: global_time = 0 if LEFT_KLICK and bt_pause.pause: if global_time > 0: rocket_1.firestop = True rocket_2.firestop = True global_time -= 0.0025 / (alpha + 0.01) else: global_time = 0 if bt_right.rect.collidepoint( mouse_pos) and MOUSE_KLICK == True and bt_pause.pause: rocket_1.firestop = True rocket_2.firestop = True global_time += 0.01 / (alpha + 0.01) if RIGHT_KLICK and bt_pause.pause: rocket_1.firestop = True rocket_2.firestop = True global_time += 0.0025 / (alpha + 0.01) if bt_start.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True: bt_pause.pause = False if alpha == 0: alpha = 0.05 rocket_1.firestop = True rocket_2.firestop = True if bt_1.rect.collidepoint( mouse_pos) and MOUSE_KLICK == True and global_time == 0: bt_1.bt1_x = mouse_x - 10 frame_rate = 0 if (mouse_x - bt_1.rect.left) / 200 > 0.98: alpha = 0.98 else: alpha = ((mouse_x - bt_1.rect.left) / 200) rocket_1.img_load() rocket_1.global_rocket_t_start = global_time rocket_1.global_rocket_x_start = rocket_1.global_rocket_x if WIDTH < 1600 and (mouse_x - bt_1.rect.left) / 200 > 0.965: alpha = 0.965 if bt_stop.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True: rocket_1.global_rocket_x_start = 0 rocket_1.global_rocket_t_start = 0 global_time = 0 bt_pause.pause = True alpha = 0 bt_1.bt1_x = bt_1.rect.left rocket_1.img_load() rocket_1.firestop = False rocket_2.firestop = False if bt_galileo.rect.collidepoint( mouse_pos ) and MOUSE_KLICK == True and bt_galileo.clickflag == True: bt_galileo.click() rocket_1.img_load() else: rocket_1.img_load() bt_galileo.clickflag == True if MOUSE_KLICK == False: bt_galileo.clickflag = True #//////////////////////////////////////////////////////////////// # --- Timer going up --- # Calculate total seconds if frame_rate != 0: # global time global_time += frame_rate / 1000 frame1_rocket_time1 = global_time * beta + alpha * GLOBAL_L * 0.5 / GLOBAL_C frame1_rocket_time2 = global_time * beta frame1_rocket_time3 = global_time * beta - alpha * GLOBAL_L * 0.5 / GLOBAL_C #rocket_1 scale with alpha if not GALILEO: rocket_1.Lx_scale(alpha, 150, GLOBAL_L) else: rocket_1.Lx_scale(0, 150, GLOBAL_L) #rocket_1 move rocket_1.update(alpha, GLOBAL_C, GLOBAL_L, frame1_rocket_length, global_time, frame1_ind, border) frame1_ind = math.floor( (rocket_1.global_rocket_x + 2 * GLOBAL_L) / (4 * GLOBAL_L)) #length_of_rocket scale with alpha frame1_rocket_length = beta * GLOBAL_L #update watches if not GALILEO: watch1.update(frame1_rocket_time1) watch2.update(frame1_rocket_time2) watch3.update(frame1_rocket_time3) watch4.update(global_time) watch5.update(global_time) watch6.update(global_time) else: watch1.update(global_time) watch2.update(global_time) watch3.update(global_time) watch4.update(global_time) watch5.update(global_time) watch6.update(global_time) #кнопка переключения языка else: if bt_ruseng.flag == True: RUSENG = True else: RUSENG = False if bt_ruseng.rect.collidepoint( mouse_pos ) and MOUSE_KLICK == True and bt_ruseng.clickflag == True: bt_ruseng.click() else: bt_ruseng.clickflag == True if MOUSE_KLICK == False: bt_ruseng.clickflag = True #***************************************************************** #///////////////////////////////////////////////////////////////// #***************************************************************** '''Draw all''' if not MENU: screen.blit(background2, screen_rect) rocket_1.blitme(frame_count) rocket_2.blitme(frame_count) if not GALILEO: pygame.draw.line( screen, (231, 115, 38), (rocket_1.rect.centerx - 0.5 * beta * GLOBAL_L, rocket_1.rect.centery - 60), (rocket_1.rect.centerx - 0.5 * beta * GLOBAL_L, rocket_1.rect.centery)) pygame.draw.line( screen, (37, 153, 42), (rocket_1.rect.centerx, rocket_1.rect.centery - 60), (rocket_1.rect.centerx, rocket_1.rect.centery)) pygame.draw.line( screen, (39, 37, 153), (rocket_1.rect.centerx + 0.5 * beta * GLOBAL_L, rocket_1.rect.centery - 60), (rocket_1.rect.centerx + 0.5 * beta * GLOBAL_L, rocket_1.rect.centery)) else: pygame.draw.line(screen, (231, 115, 38), (rocket_1.rect.centerx - 0.5 * GLOBAL_L, rocket_1.rect.centery - 60), (rocket_1.rect.centerx - 0.5 * GLOBAL_L, rocket_1.rect.centery)) pygame.draw.line( screen, (37, 153, 42), (rocket_1.rect.centerx, rocket_1.rect.centery - 60), (rocket_1.rect.centerx, rocket_1.rect.centery)) pygame.draw.line(screen, (39, 37, 153), (rocket_1.rect.centerx + 0.5 * GLOBAL_L, rocket_1.rect.centery - 60), (rocket_1.rect.centerx + 0.5 * GLOBAL_L, rocket_1.rect.centery)) pygame.draw.line(screen, (231, 115, 38), (rocket_2.rect.centerx - 0.5 * GLOBAL_L, rocket_2.rect.centery - 60), (rocket_2.rect.centerx - 0.5 * GLOBAL_L, rocket_2.rect.centery)) pygame.draw.line( screen, (37, 153, 42), (rocket_2.rect.centerx, rocket_2.rect.centery - 60), (rocket_2.rect.centerx, rocket_2.rect.centery)) pygame.draw.line(screen, (39, 37, 153), (rocket_2.rect.centerx + 0.5 * GLOBAL_L, rocket_2.rect.centery - 60), (rocket_2.rect.centerx + 0.5 * GLOBAL_L, rocket_2.rect.centery)) #watch icons #---------------------------------------------------------------------------------------------------- screen.blit( img_watchpick2, (rocket_2.rect.centerx - 10, rocket_2.rect.centery - 10)) screen.blit(img_watchpick2, (rocket_2.rect.centerx - 10 - 0.5 * GLOBAL_L, rocket_2.rect.centery - 10)) screen.blit(img_watchpick2, (rocket_2.rect.centerx - 10 + 0.5 * GLOBAL_L, rocket_2.rect.centery - 10)) if not GALILEO: img_watchpick, rect_icon = img_load_icons( beta, img_watchpick, img_watchpick2) rect_icon.centerx = rocket_1.rect.centerx screen.blit(img_watchpick, rect_icon) rect_icon.centerx = rocket_1.rect.centerx - 0.5 * beta * GLOBAL_L screen.blit(img_watchpick, rect_icon) rect_icon.centerx = rocket_1.rect.centerx + 0.5 * beta * GLOBAL_L screen.blit(img_watchpick, rect_icon) screen.blit( img_b, (rocket_1.rect.centerx - 20, rocket_1.rect.centery - 100)) screen.blit( img_a, (rocket_1.rect.centerx - 20 - 0.5 * beta * GLOBAL_L, rocket_1.rect.centery - 100)) screen.blit( img_c, (rocket_1.rect.centerx - 20 + 0.5 * beta * GLOBAL_L, rocket_1.rect.centery - 100)) else: img_watchpick, rect_icon = img_load_icons( 1, img_watchpick, img_watchpick2) rect_icon.centerx = rocket_1.rect.centerx screen.blit(img_watchpick, rect_icon) rect_icon.centerx = rocket_1.rect.centerx - 0.5 * GLOBAL_L screen.blit(img_watchpick, rect_icon) rect_icon.centerx = rocket_1.rect.centerx + 0.5 * GLOBAL_L screen.blit(img_watchpick, rect_icon) screen.blit( img_b, (rocket_1.rect.centerx - 20, rocket_1.rect.centery - 100)) screen.blit(img_a, (rocket_1.rect.centerx - 20 - 0.5 * GLOBAL_L, rocket_1.rect.centery - 100)) screen.blit(img_c, (rocket_1.rect.centerx - 20 + 0.5 * GLOBAL_L, rocket_1.rect.centery - 100)) screen.blit( img_b, (rocket_2.rect.centerx - 20, rocket_2.rect.centery - 100)) screen.blit(img_a, (rocket_2.rect.centerx - 20 - 0.5 * GLOBAL_L, rocket_2.rect.centery - 100)) screen.blit(img_c, (rocket_2.rect.centerx - 20 + 0.5 * GLOBAL_L, rocket_2.rect.centery - 100)) #---------------------------------------------------------------------------------------------------- #pillar update and draw frame1_pillar1_ind = (frame1_ind) * 4 frame1_pillar2_ind = (frame1_ind) * 4 + 1 frame1_pillar3_ind = (frame1_ind) * 4 + 2 x, y = update_watchup(global_time) blitme_pillar( screen, BLACK, img_pillar_2, pygame.Rect(border - 51 + GLOBAL_L / 2, 248, 102, 192), x, y) blitme_pillar( screen, BLACK, img_pillar_2, pygame.Rect(border - 51 + 1.5 * GLOBAL_L, 248, 102, 192), x, y) blitme_pillar( screen, BLACK, img_pillar_2, pygame.Rect(border - 51 + 2.5 * GLOBAL_L, 248, 102, 192), x, y) text_1(str(frame1_pillar1_ind % 100), BLACK, (border - 6 + GLOBAL_L / 2, 206)) text_1(str(frame1_pillar2_ind % 100), BLACK, (border - 6 + 1.5 * GLOBAL_L, 206)) text_1(str(frame1_pillar3_ind % 100), BLACK, (border - 6 + 2.5 * GLOBAL_L, 206)) str_time = time_to_string(global_time) text_1('[' + str_time + ']', BLACK, (border - 33 + GLOBAL_L / 2, 225)) text_1('[' + str_time + ']', BLACK, (border - 33 + 1.5 * GLOBAL_L, 225)) text_1('[' + str_time + ']', BLACK, (border - 33 + 2.5 * GLOBAL_L, 225)) if not GALILEO: a = math.ceil( (-2 * GLOBAL_L + alpha * GLOBAL_C * global_time) / beta / GLOBAL_L) #index of pillar b = math.floor( (2 * GLOBAL_L + alpha * GLOBAL_C * global_time) / beta / GLOBAL_L + 1) img_pillar, rect_pillar = img_load(beta, img_pillar, img_pillar_2) for ind in range(a, b + 1): frame2_pillar_x = beta * ( ind - 1 ) * GLOBAL_L - GLOBAL_C * alpha * global_time + 1.5 * GLOBAL_L + border frame2_pillar_time = beta * global_time + alpha * GLOBAL_L / GLOBAL_C * ( ind - 1) rect_pillar.centerx = frame2_pillar_x x, y = update_watchdown(frame2_pillar_time, beta) blitme_pillar(screen, BLACK, img_pillar, rect_pillar, x, y) text_1(str(ind % 1000), BLACK, (rect_pillar.centerx - 6, 636)) str_time = time_to_string(frame2_pillar_time) text_1('[' + str_time + ']', BLACK, (rect_pillar.centerx - 33, 655)) else: a = math.ceil( (-2 * GLOBAL_L + alpha * GLOBAL_C * global_time) / GLOBAL_L) #index of pillar b = math.floor((2 * GLOBAL_L + alpha * GLOBAL_C * global_time) / GLOBAL_L + 1) img_pillar, rect_pillar = img_load(1, img_pillar, img_pillar_2) for ind in range(a, b + 1): frame2_pillar_x = ( ind - 1 ) * GLOBAL_L - GLOBAL_C * alpha * global_time + 1.5 * GLOBAL_L + border frame2_pillar_time = global_time rect_pillar.centerx = frame2_pillar_x x, y = update_watchdown(frame2_pillar_time, beta) blitme_pillar(screen, BLACK, img_pillar, rect_pillar, x, y) text_1(str(ind % 1000), BLACK, (rect_pillar.centerx - 6, 636)) str_time = time_to_string(frame2_pillar_time) text_1('[' + str_time + ']', BLACK, (rect_pillar.centerx - 33, 655)) #--------------------------------------------------------------------------- if WIDTH != 1200: screen.blit(background, screen_rect) else: screen.blit(back_left, (0, 0)) screen.blit(back_centr, (30, 0)) screen.blit(back_right, (800, 0)) bt_1.blitme() if bt_start.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True: bt_start.blitme() else: bt_start.blitmeclick() if bt_pause.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True: bt_pause.blitmeclick() else: bt_pause.blitme() if bt_stop.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True: bt_stop.blitme() else: bt_stop.blitmeclick() if bt_left.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True: bt_left.blitme() else: bt_left.blitmeclick() if bt_right.rect.collidepoint(mouse_pos) and MOUSE_KLICK == True: bt_right.blitme() else: bt_right.blitmeclick() if not bt_galileo.flag: bt_galileo.blitme() else: bt_galileo.blitmeclick() watch1.blitme(BLACK) watch2.blitme(BLACK) watch3.blitme(BLACK) watch4.blitme(BLACK) watch5.blitme(BLACK) watch6.blitme(BLACK) #watches text if not GALILEO: screen.blit( img_a, (watch1.rect.centerx - 20, watch1.rect.centery - 130)) str_time = time_to_string(frame1_rocket_time1) if WIDTH == 1600: text_2( str_time, BLACK, (watch1.rect.centerx - 43, watch1.rect.centery + 53)) if WIDTH == 1440 or WIDTH == 1200: text_2( str_time, BLACK, (watch1.rect.centerx - 43, watch1.rect.centery + 48)) screen.blit( img_b, (watch2.rect.centerx - 20, watch2.rect.centery - 130)) str_time = time_to_string(frame1_rocket_time2) if WIDTH == 1600: text_2( str_time, BLACK, (watch2.rect.centerx - 43, watch2.rect.centery + 53)) if WIDTH == 1440 or WIDTH == 1200: text_2( str_time, BLACK, (watch2.rect.centerx - 43, watch2.rect.centery + 48)) screen.blit( img_c, (watch3.rect.centerx - 20, watch3.rect.centery - 130)) str_time = time_to_string(frame1_rocket_time3) if WIDTH == 1600: text_2( str_time, BLACK, (watch3.rect.centerx - 43, watch3.rect.centery + 53)) if WIDTH == 1440 or WIDTH == 1200: text_2( str_time, BLACK, (watch3.rect.centerx - 43, watch3.rect.centery + 48)) screen.blit( img_a, (watch4.rect.centerx - 20, watch4.rect.centery - 130)) str_time = time_to_string(global_time) if WIDTH == 1600: text_2( str_time, BLACK, (watch4.rect.centerx - 43, watch4.rect.centery + 53)) if WIDTH == 1440 or WIDTH == 1200: text_2( str_time, BLACK, (watch4.rect.centerx - 43, watch4.rect.centery + 48)) screen.blit( img_b, (watch5.rect.centerx - 20, watch5.rect.centery - 130)) if WIDTH == 1600: text_2( str_time, BLACK, (watch5.rect.centerx - 43, watch5.rect.centery + 53)) if WIDTH == 1440 or WIDTH == 1200: text_2( str_time, BLACK, (watch5.rect.centerx - 43, watch5.rect.centery + 48)) screen.blit( img_c, (watch6.rect.centerx - 20, watch6.rect.centery - 130)) if WIDTH == 1600: text_2( str_time, BLACK, (watch6.rect.centerx - 43, watch6.rect.centery + 53)) if WIDTH == 1440 or WIDTH == 1200: text_2( str_time, BLACK, (watch6.rect.centerx - 43, watch6.rect.centery + 48)) else: screen.blit( img_a, (watch1.rect.centerx - 20, watch1.rect.centery - 130)) str_time = time_to_string(global_time) if WIDTH == 1600: text_2( str_time, BLACK, (watch1.rect.centerx - 43, watch1.rect.centery + 53)) if WIDTH == 1440 or WIDTH == 1200: text_2( str_time, BLACK, (watch1.rect.centerx - 43, watch1.rect.centery + 48)) screen.blit( img_b, (watch2.rect.centerx - 20, watch2.rect.centery - 130)) if WIDTH == 1600: text_2( str_time, BLACK, (watch2.rect.centerx - 43, watch2.rect.centery + 53)) if WIDTH == 1440 or WIDTH == 1200: text_2( str_time, BLACK, (watch2.rect.centerx - 43, watch2.rect.centery + 48)) screen.blit( img_c, (watch3.rect.centerx - 20, watch3.rect.centery - 130)) if WIDTH == 1600: text_2( str_time, BLACK, (watch3.rect.centerx - 43, watch3.rect.centery + 53)) if WIDTH == 1440 or WIDTH == 1200: text_2( str_time, BLACK, (watch3.rect.centerx - 43, watch3.rect.centery + 48)) screen.blit( img_a, (watch4.rect.centerx - 20, watch4.rect.centery - 130)) if WIDTH == 1600: text_2( str_time, BLACK, (watch4.rect.centerx - 43, watch4.rect.centery + 53)) if WIDTH == 1440 or WIDTH == 1200: text_2( str_time, BLACK, (watch4.rect.centerx - 43, watch4.rect.centery + 48)) screen.blit( img_b, (watch5.rect.centerx - 20, watch5.rect.centery - 130)) if WIDTH == 1600: text_2( str_time, BLACK, (watch5.rect.centerx - 43, watch5.rect.centery + 53)) if WIDTH == 1440 or WIDTH == 1200: text_2( str_time, BLACK, (watch5.rect.centerx - 43, watch5.rect.centery + 48)) screen.blit( img_c, (watch6.rect.centerx - 20, watch6.rect.centery - 130)) if WIDTH == 1600: text_2( str_time, BLACK, (watch6.rect.centerx - 43, watch6.rect.centery + 53)) if WIDTH == 1440 or WIDTH == 1200: text_2( str_time, BLACK, (watch6.rect.centerx - 43, watch6.rect.centery + 48)) #текст на кнопках if RUSENG: text_4("START", BLACK, (bt_start.rect.centerx - 30, bt_start.rect.centery - 7)) text_4("PAUSE", BLACK, (bt_pause.rect.centerx - 30, bt_pause.rect.centery - 7)) text_4("STOP", BLACK, (bt_stop.rect.centerx - 30, bt_stop.rect.centery - 7)) text_2("Galilean", BLACK, (bt_galileo.rect.centerx - 168, bt_galileo.rect.centery - 18)) text_2("Transformation", BLACK, (bt_galileo.rect.centerx - 168, bt_galileo.rect.centery + 3)) text_2("Lorentz", BLACK, (bt_galileo.rect.centerx + 15, bt_galileo.rect.centery - 18)) text_2("Transformation", BLACK, (bt_galileo.rect.centerx + 15, bt_galileo.rect.centery + 3)) else: text_2( "СТАРТ", BLACK, (bt_start.rect.centerx - 30, bt_start.rect.centery - 10)) text_2( "ПАУЗА", BLACK, (bt_pause.rect.centerx - 30, bt_pause.rect.centery - 10)) text_2("СТОП", BLACK, (bt_stop.rect.centerx - 25, bt_stop.rect.centery - 10)) text_2("Трансформация", BLACK, (bt_galileo.rect.centerx - 165, bt_galileo.rect.centery - 18)) text_2( "Галилея", BLACK, (bt_galileo.rect.centerx - 165, bt_galileo.rect.centery)) text_2("Трансформация", BLACK, (bt_galileo.rect.centerx + 15, bt_galileo.rect.centery - 18)) text_2("Лоренца", BLACK, (bt_galileo.rect.centerx + 15, bt_galileo.rect.centery)) #text if RUSENG: if WIDTH == 1600: text_4("Velocity:", BLACK, (1370, 270)) text_4(str(round(alpha, 3)), BLACK, (1370, 310)) text_4("of light speed", BLACK, (1370, 350)) if WIDTH == 1440 or WIDTH == 1200: text_4("Velocity:", BLACK, (WIDTH - 140, 270)) text_4(str(round(alpha, 3)), BLACK, (WIDTH - 140, 310)) text_4("of light", BLACK, (WIDTH - 140, 350)) else: if WIDTH == 1600: text_1("Скорость:", BLACK, (1370, 270)) text_1(str(round(alpha, 3)), BLACK, (1370, 310)) text_1("скорости света", BLACK, (1370, 350)) if WIDTH == 1440 or WIDTH == 1200: text_1("Скорость:", BLACK, (WIDTH - 140, 270)) text_1(str(round(alpha, 3)), BLACK, (WIDTH - 140, 310)) text_1("скорости света", BLACK, (WIDTH - 140, 350)) else: screen.blit(back_menu, screen_rect) if INSTRUCTION: os.startfile(r'STR_laba.pdf') INSTRUCTION = False if RUSENG: text_5("New experiment", BLACK, (WIDTH - 498, 282)) text_5("New experiment", WHITE, (WIDTH - 500, 280)) if mouse_x >= WIDTH - 500 and mouse_x <= 1400 and mouse_y >= 280 and mouse_y <= 350: text_5("New experiment", RED, (WIDTH - 500, 280)) if MOUSE_KLICK: MENU = False text_5("Instruction", BLACK, (WIDTH - 498, 382)) text_5("Instruction", WHITE, (WIDTH - 500, 380)) if mouse_x >= WIDTH - 500 and mouse_x <= 1400 and mouse_y >= 380 and mouse_y <= 450: text_5("Instruction", RED, (WIDTH - 500, 380)) if MOUSE_KLICK: INSTRUCTION = True text_5("Autors", BLACK, (WIDTH - 498, 482)) text_5("Autors", WHITE, (WIDTH - 500, 480)) if mouse_x >= WIDTH - 500 and mouse_x <= 1400 and mouse_y >= 480 and mouse_y <= 550: text_5("Autors", RED, (WIDTH - 500, 480)) if MOUSE_KLICK: AUTORS = True text_5("Quit", BLACK, (WIDTH - 498, 582)) text_5("Quit", WHITE, (WIDTH - 500, 580)) if mouse_x >= WIDTH - 500 and mouse_x <= 1400 and mouse_y >= 580 and mouse_y <= 650: text_5("Quit", RED, (WIDTH - 500, 580)) if MOUSE_KLICK: DONE = True else: text_5("Новый эксперимент", BLACK, (WIDTH - 548, 282)) text_5("Новый эксперимент", WHITE, (WIDTH - 550, 280)) if mouse_x >= WIDTH - 500 and mouse_x <= 1400 and mouse_y >= 280 and mouse_y <= 350: text_5("Новый эксперимент", RED, (WIDTH - 550, 280)) if MOUSE_KLICK: MENU = False text_5("Инструкция", BLACK, (WIDTH - 548, 382)) text_5("Инструкция", WHITE, (WIDTH - 550, 380)) if mouse_x >= WIDTH - 550 and mouse_x <= 1400 and mouse_y >= 380 and mouse_y <= 450: text_5("Инструкция", RED, (WIDTH - 550, 380)) if MOUSE_KLICK: INSTRUCTION = True text_5("Авторы", BLACK, (WIDTH - 548, 482)) text_5("Авторы", WHITE, (WIDTH - 550, 480)) if mouse_x >= WIDTH - 550 and mouse_x <= 1400 and mouse_y >= 480 and mouse_y <= 550: text_5("Авторы", RED, (WIDTH - 550, 480)) if MOUSE_KLICK: AUTORS = True text_5("Выход", BLACK, (WIDTH - 548, 582)) text_5("Выход", WHITE, (WIDTH - 550, 580)) if mouse_x >= WIDTH - 550 and mouse_x <= 1400 and mouse_y >= 580 and mouse_y <= 650: text_5("Выход", RED, (WIDTH - 550, 580)) if MOUSE_KLICK: DONE = True if bt_ruseng.flag: bt_ruseng.blitme() else: bt_ruseng.blitmeclick() text_1("РУС", BLACK, (bt_ruseng.rect.centerx - 55, bt_ruseng.rect.centery - 10)) text_1("ENG", BLACK, (bt_ruseng.rect.centerx + 30, bt_ruseng.rect.centery - 10)) if bt_ruseng.rect.collidepoint(mouse_pos): text_1( "РУС", RED, (bt_ruseng.rect.centerx - 55, bt_ruseng.rect.centery - 10)) text_1( "ENG", RED, (bt_ruseng.rect.centerx + 30, bt_ruseng.rect.centery - 10)) if AUTORS: screen.blit(s, (0, 0)) # (0,0) are the top-left coordinates if not RUSENG: text_1( "Программирование", WHITE, (screen_rect.centerx - 50, screen_rect.centery - 150)) text_3( "Кашников Александр МГТУ им. Н.Э. Баумана", WHITE, (screen_rect.centerx - 150, screen_rect.centery - 120)) text_3( "Киктенко Евгений МГТУ им. Н.Э. Баумана", WHITE, (screen_rect.centerx - 150, screen_rect.centery - 90)) text_1( "Расчеты", WHITE, (screen_rect.centerx - 50, screen_rect.centery - 60)) text_3( "Киктенко Евгений", WHITE, (screen_rect.centerx - 150, screen_rect.centery - 30)) text_3("Кашников Александр", WHITE, (screen_rect.centerx - 150, screen_rect.centery)) text_3( "Гусманова Анастасия МГТУ им. Н.Э. Баумана", WHITE, (screen_rect.centerx - 150, screen_rect.centery + 30)) text_1( "Графика", WHITE, (screen_rect.centerx - 50, screen_rect.centery + 60)) text_3( "Кашников Александр", WHITE, (screen_rect.centerx - 150, screen_rect.centery + 90)) else: text_1( "programming", WHITE, (screen_rect.centerx - 50, screen_rect.centery - 150)) text_3( "Kashnikov Alexander BMSTU", WHITE, (screen_rect.centerx - 150, screen_rect.centery - 120)) text_3( "Kiktenko Evgeniy BMSTU", WHITE, (screen_rect.centerx - 150, screen_rect.centery - 90)) text_1( "Calculations", WHITE, (screen_rect.centerx - 50, screen_rect.centery - 60)) text_3( "Kiktenko Evgeniy", WHITE, (screen_rect.centerx - 150, screen_rect.centery - 30)) text_3("Kashnikov Alexander", WHITE, (screen_rect.centerx - 150, screen_rect.centery)) text_3( "Gusmanova Anastasiya BMSTU", WHITE, (screen_rect.centerx - 150, screen_rect.centery + 30)) text_1( "Design", WHITE, (screen_rect.centerx - 50, screen_rect.centery + 60)) text_3( "Kashnikov Alexander", WHITE, (screen_rect.centerx - 150, screen_rect.centery + 90)) clock.tick(60) '''Go ahead and update the screen with what we've drawn.''' pygame.display.flip()
class RocketFly: """Overall class to manage game assets and behavior.""" def __init__(self): """Initialize the game, and create game resources.""" pygame.init() self.settings = Settings() # display.set_mode() zwraca obiekt zwany powierzchnią reprezentujący okno całej gry self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) self.settings.screen_width = self.screen.get_rect().width self.settings.screen_height = self.screen.get_rect().height pygame.display.set_caption("Rocket Fly") self.rocket = Rocket(self) def run_game(self): """Start the main loop for the game.""" while True: self._check_events() self.rocket.update() self._update_screen() def _check_events(self): """Respond to keyboard and mouse events.""" # funkcja get() zwraca listę zdarzeń, które miały miejsce od czasu jej poprzedniego wywołania for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) def _check_keydown_events(self, event): """Respond to keypresses""" if event.key == pygame.K_RIGHT: self.rocket.moving_right = True elif event.key == pygame.K_LEFT: self.rocket.moving_left = True elif event.key == pygame.K_UP: self.rocket.moving_up = True elif event.key == pygame.K_DOWN: self.rocket.moving_down = True elif event.key == pygame.K_c: self.rocket.go_to_center() elif event.key == pygame.K_q: sys.exit() def _check_keyup_events(self, event): """Respond to key releases""" if event.key == pygame.K_RIGHT: self.rocket.moving_right = False elif event.key == pygame.K_LEFT: self.rocket.moving_left = False elif event.key == pygame.K_UP: self.rocket.moving_up = False elif event.key == pygame.K_DOWN: self.rocket.moving_down = False def _update_screen(self): """Update images on the screen, and flip to the new screen.""" self.screen.fill(self.settings.bg_color) self.rocket.blitme() # Make the most recently drawn screen visible. pygame.display.flip()
class RocketLauncher: """Overall class to manage the rocket game""" def __init__(self): """Initialize the game, and create game resources.""" pygame.init() # Inherit Settings class self.settings = Settings() # Set up main screen. self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) # self.settings.screen_width = self.screen.get_rect().width # self.settings.screen_height = self.screen.get_rect().height # Game title pygame.display.set_caption("Rocket") # Inherit the Ship class self.rocket = Rocket(self) def _check_events(self): """Respond to keypresses and mouse events.""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) def _check_keydown_events(self, event): """Respond to keypresses.""" if event.key == pygame.K_RIGHT: self.rocket.moving_right = True elif event.key == pygame.K_LEFT: self.rocket.moving_left = True elif event.key == pygame.K_UP: self.rocket.moving_up = True elif event.key == pygame.K_DOWN: self.rocket.moving_down = True elif event.key == pygame.K_q: sys.exit() def _check_keyup_events(self, event): """Respond to key releases.""" if event.key == pygame.K_RIGHT: # Stop moving self.rocket.moving_right = False elif event.key == pygame.K_LEFT: # Stop moving self.rocket.moving_left = False elif event.key == pygame.K_UP: # Stop moving self.rocket.moving_up = False elif event.key == pygame.K_DOWN: # Stop moving self.rocket.moving_down = False def _update_screen(self): """Update images on the screen, and flip to the new screen.""" # Redraw the screen during each pass through the loop. self.screen.fill(self.settings.bg_color) # Draw ship at its current location self.rocket.blitme() # Make the most revently drawn screen visible. pygame.display.flip() def run_game(self): """Main loop for the game.""" while True: self._check_events() self.rocket.update() self._update_screen()
class SpaceBattle: """Main class that manages game's assets""" def __init__(self): """Initialize the game, and create game resources.""" pygame.init() # Get game's settings self.settings = Settings() # Create a main display self.screen = pygame.display.set_mode((1200, 800)) # Set a main display's name pygame.display.set_caption("Space Battle") # Create an instance to store game statistics self.stats = GameStats(self) # Create a scoreboard self.scoreboard = Scoreboard(self) # Create a rocket self.rocket = Rocket(self) # Create a list of bullets self.bullets = pygame.sprite.Group() # Create a fleet of spaceships self.spaceships = pygame.sprite.Group() self._create_fleet() # Make the Start button. self.start_button = PlayButton(self, "Start") def run_game(self): """Start game's main loop.""" while True: # Monitors key presses and releases self._check_key_mouse_events() # Updates positions of game's moving elements self._update_positions() # Flipping the main screen self._update_screen() def _update_positions(self): """Update the position of a rocket, bullets, and spaceships.""" if self.stats.game_active: self.rocket.update() self._update_bullets() self._update_spaceships() def _check_key_mouse_events(self): """Respond to key presses and mouse events.""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) elif event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() self._press_play_button(mouse_pos) def _press_play_button(self, mouse_pos): """Start a new game when the player clicks Play.""" # Returns true if the point of a mouse click overlaps # with the start button button_clicked = self.start_button.rect.collidepoint(mouse_pos) # If the button is clicked and the game has not started yet, # it means player starts a new game. So, reset the game. if button_clicked and not self.stats.game_active: self._reset_dynamic_settings() self._reset_games_stats() # Get rid of any remaining spaceships self.spaceships.empty() # Get rid of any remaining bullets self.bullets.empty() # Create a new fleet self._create_fleet() # Center the rocket self.rocket.center_rocket() # Hide the mouse cursor. pygame.mouse.set_visible(False) def _reset_games_stats(self): """Reset the game statistics.""" self.stats.reset_stats() self.stats.game_active = True self.scoreboard.set_score() self.scoreboard.set_level() self.scoreboard.set_rockets() def _reset_dynamic_settings(self): """Reset the game's dynamic settings.""" self.settings.initialize_dynamic_settings() def _check_keydown_events(self, event): """Respond to keypresses.""" if event.key == pygame.K_RIGHT: self.rocket.moving_right = True elif event.key == pygame.K_LEFT: self.rocket.moving_left = True elif event.key == pygame.K_UP: self.rocket.moving_up = True elif event.key == pygame.K_DOWN: self.rocket.moving_down = True elif event.key == pygame.K_q: sys.exit() elif event.key == pygame.K_SPACE: self._fire_bullet() def _check_keyup_events(self, event): """Respond to key releases.""" if event.key == pygame.K_RIGHT: self.rocket.moving_right = False elif event.key == pygame.K_LEFT: self.rocket.moving_left = False elif event.key == pygame.K_UP: self.rocket.moving_up = False elif event.key == pygame.K_DOWN: self.rocket.moving_down = False def _fire_bullet(self): """ If the number of current bullets on the screen is less than number of bullets allowed to be fired, then create a new bullet and add it to the bullets group. """ if len(self.bullets) < self.settings.bullets_allowed: new_bullet = Bullet(self) self.bullets.add(new_bullet) def _update_bullets(self): """Update position of bullets and get rid of old bullets.""" # Update bullet positions. self.bullets.update() self._clean_off_screen_bullets() self._check_bullet_spaceship_collisions() def _clean_off_screen_bullets(self): """Get rid of bullets that are off screen.""" for bullet in self.bullets.copy(): if bullet.rect.bottom <= 0: self.bullets.remove(bullet) def _check_bullet_spaceship_collisions(self): """Respond to bullet-spaceship collisions.""" # Returns dictionary containing bullets (key) and spaceships (values) that # were hit collisions = pygame.sprite.groupcollide( self.bullets, self.spaceships, True, True) self._update_total_score(collisions) self._increase_difficulty() def _increase_difficulty(self): """ If there are no more spaceships on the screen, the increase the difficulty of the game """ if not self.spaceships: # Destroy existing bullets and create new fleet. self.bullets.empty() self._create_fleet() self.settings.increase_speed() # Increase level. self.stats.level += 1 self.scoreboard.set_level() def _update_total_score(self, collisions): """Update the total score on the game's screen""" # If collision dictionary exists, then add spaceships' total value to # a score. if collisions: for spaceships in collisions.values(): self.stats.score += self.settings.spaceship_points * len(spaceships) # Create new image of updated total score self.scoreboard.set_score() self.scoreboard.check_high_score() def _update_spaceships(self): """ Check if the fleet is at an border of a screen, then update the positions of spaceships' fleet. """ self._check_fleet_edges() self.spaceships.update() # If the rocket touches an spaceship, then rocket is hit if pygame.sprite.spritecollideany(self.rocket, self.spaceships): self._rocket_hit() self._check_spaceships_bottom() def _check_spaceships_bottom(self): """Check if any spaceships have reached the bottom of the screen.""" screen_rect = self.screen.get_rect() for spaceship in self.spaceships.sprites(): if spaceship.rect.bottom >= screen_rect.bottom: # Treat this the same as if the rocket got hit. self._rocket_hit() break def _rocket_hit(self): """Respond to the rocket being hit by an spaceship.""" if self.stats.rockets_left > 0: # Decrement rockets_left, and update scoreboard. self.stats.rockets_left -= 1 self.scoreboard.set_rockets() # Get rid of any remaining spaceships and bullets. self.spaceships.empty() self.bullets.empty() # Create a new fleet and center the rocket. self._create_fleet() self.rocket.center_rocket() # Pause a game to let player see what happened sleep(0.5) else: self.stats.game_active = False pygame.mouse.set_visible(True) def _create_fleet(self): """Create the fleet of spaceships.""" # Create an spaceship and find the number of spaceships in a row. # Spacing between each spaceship is equal to one spaceship width. spaceship = SpaceShip(self) spaceship_width, spaceship_height = spaceship.rect.size # Calculate the number of spaceships in a row # (2 * spaceship_width) creates margins on either side of a screen available_space_x = self.settings.screen_width - (2 * spaceship_width) number_spaceships_x = available_space_x // (2 * spaceship_width) # Determine the number of rows of spaceships that fit on the screen. rocket_height = self.rocket.rect.height available_space_y = (self.settings.screen_height - (18 * spaceship_height) - rocket_height) number_rows = available_space_y // (2 * spaceship_height) # Create the full fleet of spaceships. for row_number in range(number_rows): for spaceship_number in range(number_spaceships_x): self._create_spaceship(spaceship_number, row_number) def _create_spaceship(self, spaceship_number, row_number): """Create an spaceship and place it in the row.""" spaceship = SpaceShip(self) spaceship_width, spaceship_height = spaceship.rect.size spaceship.x = spaceship_width + 2 * spaceship_width * spaceship_number spaceship.rect.x = spaceship.x spaceship.rect.y = 3.5 * spaceship.rect.height + 2 * spaceship.rect.height * row_number self.spaceships.add(spaceship) def _check_fleet_edges(self): """ If any spaceship touches screen's edges, then change the direction of a fleet. """ for spaceship in self.spaceships.sprites(): if spaceship.check_edges(): self._change_fleet_direction() break def _change_fleet_direction(self): """Drop the entire fleet and change the fleet's direction.""" for spaceship in self.spaceships.sprites(): spaceship.rect.y += self.settings.fleet_drop_speed self.settings.fleet_direction *= -1 def _update_screen(self): """Update images on the screen, and flip to the new screen.""" self.screen.fill(self.settings.bg_color) # Draw a rocket self.rocket.blitme() # Draw bullets for bullet in self.bullets.sprites(): bullet.draw_bullet() # Draw spaceships self.spaceships.draw(self.screen) # Draw the score information. self.scoreboard.show_score() # Draw the play button if the game is inactive. if not self.stats.game_active: self.start_button.draw_button() pygame.display.flip()
class RocketGame: """overrall Class to manage assets and behavior""" def __init__(self): """initialize the game, and create resources""" pygame.init() self.settings = Settings() #Sets the window size and caption self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption("Rocket Game") #import the rocket and make an instance of it self.rocket = Rocket(self) def run_game(self): """Start the main loop of the game.""" while True: #watch for keyboard and mouse events self._check_events() self.rocket.update() self._update_screen() def _check_events(self): """Respond to keypresses and mouse events.""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) def _update_screen(self): """Update images on the screen and flip to a new screen""" #Redraw the screen during each pass through the loop self.screen.fill(self.settings.bg_color) #draw the rocket self.rocket.blitme() #Make the most recently drawn screen visible pygame.display.flip() def _check_keydown_events(self, event): """Respond to keypress down events""" if event.key == pygame.K_RIGHT: #Move the rocket to the right self.rocket.moving_right = True elif event.key == pygame.K_LEFT: #move the rocket to the left self.rocket.moving_left = True elif event.key == pygame.K_UP: #move the rocket up self.rocket.moving_up = True elif event.key == pygame.K_DOWN: #move the rocket down self.rocket.moving_down = True elif event.key == pygame.K_q: sys.exit() def _check_keyup_events(self, event): """Respond to keypress releases""" #stop moving the rocket if event.key == pygame.K_RIGHT: self.rocket.moving_right = False if event.key == pygame.K_LEFT: self.rocket.moving_left = False if event.key == pygame.K_UP: self.rocket.moving_up = False if event.key == pygame.K_DOWN: self.rocket.moving_down = False
# -*- coding: utf-8 -*- """ Created on Thu Sep 14 19:03:20 2017 @author: Leszek """ # Latanie rakietą import pygame, sys from pygame.locals import * from rocket import Rocket import rocket_game_functions as gf pygame.init() bg_color = (100, 000, 200) screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption('Rakieta w kosmosie') rocket = Rocket(screen) while True: gf.check_events(rocket) #poszczegolne zdarzenia wywołane myszą/klawiaturą rocket.update() # gf.update_screen(screen, rocket) screen.fill(bg_color) rocket.blitme() pygame.display.flip()
class SidewaysRocket: """overrall class to manage assets and behavior""" def __init__(self): """intialize the game, and create resources""" pygame.init() self.settings = Settings() #Sets the window size and caption self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption("Sideways Rocket Game") #import the rocket and make an instance of it self.rocket = Rocket(self) #import the laser sprites self.lasers = pygame.sprite.Group() def run_game(self): """Start the main loop of the game.""" while True: #watch for keyboard and mouse events self._check_events() self.rocket.update() self._update_lasers() self._update_screen() def _check_events(self): """Respond to keypresses and mouse events.""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) def _update_screen(self): """Update images on the screen and flip to a new screen""" #Redraw the screen during each pass through the loop self.screen.fill(self.settings.bg_color) #draw the rocket self.rocket.blitme() #draw lasers for laser in self.lasers.sprites(): laser.draw_laser() #Make the most recently drawn screen visible pygame.display.flip() def _check_keydown_events(self, event): """Respond to keypress down events""" if event.key == pygame.K_w: #move the rocket up self.rocket.moving_up = True elif event.key == pygame.K_s: #move the rocket down self.rocket.moving_down = True elif event.key == pygame.K_SPACE: self._fire_laser() elif event.key == pygame.K_q: sys.exit() def _check_keyup_events(self, event): """Respond to keypress releases""" #stop moving the rocket if event.key == pygame.K_w: self.rocket.moving_up = False if event.key == pygame.K_s: self.rocket.moving_down = False def _fire_laser(self): """Create a new laser and add it to the lasers group""" if len(self.lasers) < self.settings.lasers_allowed: new_laser = Laser(self) self.lasers.add(new_laser) def _update_lasers(self): """Update the position of lasers and get rid of old lasers""" #update laser positions self.lasers.update() #Get rid of bullets that have disappeared for laser in self.lasers.copy(): if laser.rect.left >= self.rocket.screen_rect.right: self.lasers.remove(laser)
class RocketCenter: """ A class to manage the general game assets and behavior """ def __init__(self): """ Initialize the game, and create game resources """ pygame.init() # Getting all the settings self.settings = Settings() # Setting fullscreen mode self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) self.settings.screen_width = self.screen.get_rect().width self.settings.screen_height = self.screen.get_rect().height # Getting a name for the title pygame.display.set_caption("Rocket Center") # Setting my rocket self.rocket = Rocket(self) self.bullets = pygame.sprite.Group() def run_game(self): """ Start the main loop for the game """ while True: # Setting the check_events, update_screen and rocket update methons""" self._check_events() self._update_screen() self.rocket.update() self._update_bullets() def _check_events(self): """ Reponding te keypresses """ for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) def _check_keydown_events(self, event): """ Respond to keypresses """ if event.key == pygame.K_UP: self.rocket.moving_up = True elif event.key == pygame.K_DOWN: self.rocket.moving_down = True elif event.key == pygame.K_q: sys.exit() elif event.key == pygame.K_SPACE: self._fire_bullet() def _check_keyup_events(self, event): """ Respond to keyup """ if event.key == pygame.K_RIGHT: self.rocket.moving_right = False elif event.key == pygame.K_LEFT: self.rocket.moving_left = False elif event.key == pygame.K_UP: self.rocket.moving_up = False elif event.key == pygame.K_DOWN: self.rocket.moving_down = False def _fire_bullet(self): """ Create a new bullet and add ti to the bullet group """ if len(self.bullets) < self.settings.bullets_allowed: new_bullet = Bullet(self) self.bullets.add(new_bullet) def _update_bullets(self): """ Update the position of bullets and get gir of old ones """ self.bullets.update() # Get rid of the bullets that have disappeared. for bullet in self.bullets.copy(): if bullet.rect.left >= self.settings.screen_width: self.bullets.remove(bullet) def _update_screen(self): """ Updating all the images in the screen """ self.screen.fill(self.settings.bg_color) self.rocket.blitme() for bullet in self.bullets.sprites(): bullet.draw_bullet() pygame.display.flip()
class RocketGame: """Overall class to manage game assets and behaviour""" def __init__(self): """Initialize the game and create game resources.""" pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) self.settings.screen_width = self.screen.get_rect().width self.settings.screen_height = self.screen.get_rect().height self.screen_bottom = self.screen.get_rect().bottom self.bg_color = self.settings.bg_color pygame.display.set_caption("Lander") # Create and instance to store game stats self.stats = GameStats(self) self.sb = Scoreboard(self) self.rocket = Rocket(self, 1) self.rocket2 = Rocket(self, 2) self.rocket2.rect.top = self.screen_bottom self.flames = Flames(self) self.terrain_group = pygame.sprite.Group() self._create_terrain_group() self.pad = Pad(self) # Make the Play button self.play_button = Button(self, "Start", 500, 500) # Make the info button self.info_button = InfoButton(self, "Instructions", 500, 600) # Set the high score file self.filename = "highscore.txt" # Make a banner of instructions self.banner = Banner(self, "Click on 'Start' or press 's'", 350, 100) self.banner2 = Banner(self, "Press 'q' to Quit", 350, 200) self.show_instructions = Banner( self, "Use up arrow for thrust and left/right arrows to rotate.", 300, 650) self.show_instructions2 = Banner( self, "Land on the platform with parameters green. " "Bonus points for fuel remaining", 300, 700) self.info_displayed = False # Make a bonus points banner bonus_points_str = "place holder" self.banner3 = Banner(self, bonus_points_str, 500, 200) # Get sound file: self.explosion_sound = pygame.mixer.Sound("explosion.wav") self.thrust_sound = pygame.mixer.Sound("thrusters.wav") self.applause_sound = pygame.mixer.Sound("applause.wav") self.alert_sound = pygame.mixer.Sound("alert.wav") pygame.mixer.music.load('lander.wav') pygame.mixer.music.set_volume(1.0) def run_game(self): """Start the main loop for the game""" while True: self._check_events() if self.stats.game_active: self.rocket.update() self.flames.update(self.rocket.x, self.rocket.y, self.settings.angle) self.settings.height = int(self.settings.screen_height - self.rocket.y - 84) # 84 is the pad height self._check_fuel() self.sb.prep_fuel_remaining() self.sb.prep_height() self.sb.prep_vel_x() self.sb.prep_vel_y() self.sb.prep_angle() self._landed_or_crashed() self._update_screen() pygame.display.flip() def _landed_or_crashed(self): """Routine to see whether landed or crashed""" self._landing() if self.settings.crashed: self._crashed() elif self.settings.landed: self._landed() def _landing(self): """Routine to check if landing and take appropriate action""" contact = pygame.sprite.spritecollideany(self.rocket, self.terrain_group) if contact and (self.settings.rocket_vel_y < self.settings.rocket_vel_y_safe)\ or contact and (self.settings.angle > self.settings.rocket_angle_safe) \ or contact and (self.settings.angle < -self.settings.rocket_angle_safe) \ or contact and ((self.settings.rocket_vel_x < -self.settings.rocket_vel_x_safe) or (self.settings.rocket_vel_x > self.settings.rocket_vel_x_safe))\ or contact and (self.rocket.x > (self.pad.x + 30) or (self.rocket.x < (self.pad.x - 30))) \ or self.settings.height < -10: self.settings.rocket_vel_y = 0 self.settings.crashed = True elif contact and self.settings.rocket_vel_y >= self.settings.rocket_vel_y_safe: self.settings.rocket_vel_y = 0 print(self.settings.rocket_vel_y) self.settings.landed = True else: self.settings.landed = False self.settings.crashed = False def _landed(self): """Routine to add points, print a logo and reset the next ship""" self._applause() # Play explosion sound if self.settings.fuel > 10: self.settings.bonus_points = self.settings.fuel * 2 self.stats.score += self.settings.landing_points + int( self.settings.bonus_points) self.settings.landings += 1 self.sb.prep_level() self.sb.prep_score() self.sb.check_high_score() self._bonus_points() self._update_screen() if self.stats.rockets_left > -1: # If you land you want to continue! # Dont decrement ships left and update scoreboard self.sb.prep_rockets() self.rocket.restart_rocket() self.settings.initialize_dynamic_settings() # Get rid of any remaining terrain. self.terrain_group.empty() # Create a new landscape. self._create_terrain_group() # Pause sleep(1.5) # Play soundtrack. pygame.mixer.music.unpause() else: self.stats.game_active = False pygame.mixer.music.stop() # Stop the music playing pygame.mouse.set_visible(True) def _crashed(self): # self.rocket2.rect.center = self.rocket.rect.center self._explosion() # Play explosion sound self._update_screen() sleep(1.5) if self.stats.rockets_left > 0: # Decrement ships left and update scoreboard self.stats.rockets_left -= 1 self.sb.prep_rockets() self.rocket.restart_rocket() self.settings.initialize_dynamic_settings() self.rocket2.rect.top = self.screen_bottom # Get rid of any remaining terrain. self.terrain_group.empty() # Create a new landscape. self._create_terrain_group() # Pause sleep(1.5) # Play soundtrack. pygame.mixer.music.unpause() else: self.stats.game_active = False pygame.mixer.music.stop() # Stop the music playing pygame.mouse.set_visible(True) def _check_events(self): """ Watch for keyboard and mouse events.""" for event in pygame.event.get(): if event.type == pygame.QUIT: with open(self.filename, 'w') as file_object: highscore = str(self.stats.high_score) print(highscore) file_object.write(highscore) sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) elif event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() self._check_play_button(mouse_pos) self._check_info_button(mouse_pos) def _check_play_button(self, mouse_pos): """Start a new game if player clicks Start""" button_clicked = self.play_button.rect.collidepoint(mouse_pos) if button_clicked and not self.stats.game_active: # Reset the game statistics. self.settings.landings = 0 self.settings.initialize_dynamic_settings() self.settings.fuel = self.settings.fuel_capacity self.rocket2.rect.top = self.screen_bottom self.stats.reset_stats() self.sb.prep_images() self.stats.game_active = True # Get rid of any remaining bugs and bullets. self.terrain_group.empty() # Create a new fleet and center the ship. self._create_terrain_group() self.rocket.restart_rocket() # Hide the mouse cursor pygame.mouse.set_visible(False) # Play soundtrack. pygame.mixer.music.play(-1) def _check_info_button(self, mouse_pos): """Show instructions if the player clicks for instructions""" info_button_clicked = self.info_button.rect.collidepoint(mouse_pos) if info_button_clicked and not self.stats.game_active and not self.info_displayed: self.info_displayed = True elif info_button_clicked and not self.stats.game_active and self.info_displayed: self.info_displayed = False #elif info_button_clicked and not self.stats.game_active and self.info_displayed: #self.show_instructions. def _check_s(self, check_s): """Start a new game if player clicks 's' to start""" if check_s and not self.stats.game_active: # Reset the game statistics. self.settings.landings = 0 self.settings.initialize_dynamic_settings() self.settings.fuel = self.settings.fuel_capacity self.rocket2.rect.top = self.screen_bottom self.stats.reset_stats() self.sb.prep_images() self.stats.game_active = True # Get rid of the old terrain self.terrain_group.empty() # Create a new fleet and center the ship. self._create_terrain_group() self.rocket.restart_rocket() # Hide the mouse cursor pygame.mouse.set_visible(False) # Play soundtrack. pygame.mixer.music.play(-1) def _check_keydown_events(self, event): """Respond to keypresses""" if event.key == pygame.K_RIGHT: # set moving right flag true. self.rocket.moving_right = True elif event.key == pygame.K_LEFT: # Set moving left flag true. self.rocket.moving_left = True elif event.key == pygame.K_UP: # set moving up flag true. if self.settings.fuel > 0: self.rocket.thrust_applied = True self._thrust() # Thrust sound elif event.key == pygame.K_s: check_s = True self._check_s(check_s) elif event.key == pygame.K_q: with open(self.filename, 'w') as file_object: highscore = str(self.stats.high_score) print(highscore) file_object.write(highscore) sys.exit() def _check_keyup_events(self, event): """"Respond to releases""" if event.key == pygame.K_RIGHT: self.rocket.moving_right = False elif event.key == pygame.K_LEFT: self.rocket.moving_left = False if event.key == pygame.K_UP: self.rocket.thrust_applied = False pygame.mixer.Sound.stop(self.thrust_sound) def _check_fuel(self): if self.settings.fuel < 200: self._alert() # Play alert sound def _thrust(self): # Pause the music, allow shot noise, unpause the music. pygame.mixer.Sound.set_volume(self.thrust_sound, 1.0) pygame.mixer.Sound.play(self.thrust_sound) def _explosion(self): # Pause any music, allow the explosion then unpause any music. pygame.mixer.music.pause() pygame.mixer.Sound.stop(self.alert_sound) pygame.mixer.Sound.play(self.explosion_sound) pygame.mixer.Sound.stop(self.alert_sound) def _applause(self): # Pause any music, allow the 'yeah' then unpause any music. pygame.mixer.music.pause() pygame.mixer.Sound.stop(self.alert_sound) pygame.mixer.Sound.play(self.applause_sound) def _alert(self): # Pause any music, allow the explosion then unpause any music. pygame.mixer.Sound.set_volume(self.alert_sound, 0.1) pygame.mixer.Sound.play(self.alert_sound) def _bonus_points(self): bonus = int(self.settings.bonus_points) bonus_points_str = f"You got {str(bonus)} fuel bonus points." self.banner3.update_banner(bonus_points_str) def _create_terrain_group(self): """Create the terrain group made up of terrain blocks""" # Create a terrain block. terrain = Terrain(self, 1) terrain_width, terrain_height = terrain.rect.size available_space_x = self.settings.screen_width number_of_terrain_blocks = available_space_x // (terrain_width - 2) pad_number = randint(2, number_of_terrain_blocks - 2) for terrain_number in range(number_of_terrain_blocks): if terrain_number == pad_number: self._create_pad(terrain_number) else: terrain_type = randint(1, 5) self._create_terrain(terrain_number, terrain_type) def _create_terrain(self, terrain_number, terrain_type): """Create a terrain block """ terrain = Terrain(self, terrain_type) terrain_width, terrain_height = terrain.rect.size terrain.x = (terrain_width - 2) * terrain_number terrain.rect.x = terrain.x terrain.rect.y = 750 self.terrain_group.add(terrain) def _create_pad(self, terrain_number): """Create a pad block """ self.pad = Pad(self) pad_width, pad_height = self.pad.rect.size self.pad.x = (pad_width - 2) * terrain_number self.pad.rect.x = self.pad.x self.pad.rect.y = 750 self.terrain_group.add(self.pad) def _update_screen(self): # Redraw the screen during each pass through the loop. self.screen.fill(self.bg_color) self.rocket.blitme() self.rocket2.blitme() self.flames.blitme() self.terrain_group.draw(self.screen) if self.settings.bonus_points > 0: self.banner3.draw_button() sleep(1.5) # Draw the score information self.sb.show_score() # Draw the Start button if the game is inactive if not self.stats.game_active: self.play_button.draw_button() self.info_button.draw_button() self.banner.draw_button() self.banner2.draw_button() if self.info_displayed: self.show_instructions.draw_button() self.show_instructions2.draw_button() # Make the most recently drawn screen visible. pygame.display.flip()
class BlueSky: """Makes a Pygame window with a blue background.""" def __init__(self): """Initialize the game.""" pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode ((0, 0), pygame.FULLSCREEN) self.settings.screen_width = self.screen.get_rect().width self.settings.screen_height = self.screen.get_rect().height pygame.display.set_caption("Blue Sky") self.stats = GameStats(self) self.rocket = Rocket(self) self.bullets = pygame.sprite.Group() self.ufos = pygame.sprite.Group() self._create_fleet() def run_game(self): """Start the main loop for the game.""" while True: self._check_events() if self.stats.game_active: self.rocket.update() self._update_bullets() self._update_ufos() self._update_screen() def _check_events(self): """Respond to keypresses and key releases.""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) def _check_keydown_events(self, event): """Respond to keypresses.""" if event.key == pygame.K_UP: self.rocket.moving_up = True elif event.key == pygame.K_DOWN: self.rocket.moving_down = True elif event.key == pygame.K_q: sys.exit() elif event.key == pygame.K_SPACE: self._fire_bullet() def _check_keyup_events(self, event): """Respond to key releases.""" if event.key == pygame.K_DOWN: self.rocket.moving_down = False elif event.key == pygame.K_UP: self.rocket.moving_up = False def _fire_bullet(self): """Create a new bullet and add it to the bullets group.""" if len(self.bullets) < self.settings.bullets_allowed: new_bullet = Bullet(self) self.bullets.add(new_bullet) def _update_bullets(self): """Update position of bullets and get rid of old bullets.""" self.bullets.update() for bullet in self.bullets.copy(): if bullet.rect.left >= self.rocket.screen_rect.right: self.bullets.remove(bullet) self._check_bullet_ufo_collisions() def _check_bullet_ufo_collisions(self): """Respond to bullet-UFO collisions.""" # Remove any bullets and aliens that have collided. collisions = pygame.sprite.groupcollide( self.bullets, self.ufos, True, True) if not self.ufos: # Destroy existing bullets and create new fleet. self.bullets.empty() self._create_fleet() def _update_ufos(self): """Update the position of all UFOs in the fleet.""" self._check_fleet_edges() self.ufos.update() # Look for UFO-rocket collisions. if pygame.sprite.spritecollideany(self.rocket, self.ufos): self._rocket_hit() self._check_ufos_left() def _rocket_hit(self): """Respond to the rocket being hit by an UFO.""" if self.stats.rockets_left > 0: # Decrement rockets left. self.stats.rockets_left -= 1 # Get rid of any remaining UFOS and bullets. self.ufos.empty() self.bullets.empty() # Create a new fleet and center the rocket. self._create_fleet() self.rocket.center_rocket() sleep(1) else: self.stats.game_active = False def _check_ufos_left(self): """Check if any UFOS have reached the left side of the sceen.""" screen_rect = self.screen.get_rect() for ufo in self.ufos.sprites(): if ufo.rect.left <= screen_rect.left: self._rocket_hit() break def _create_fleet(self): """Create the fleet of UFO.""" # Create an UFO and find the number of UFOs in a row. ufo = Ufo(self) ufo_width, ufo_height = ufo.rect.size rocket_width = self.rocket.rect.width available_space_x = (self.settings.screen_width - (3 * ufo_width) - rocket_width) number_ufo_x = available_space_x // (2 * ufo_width) # Determine the number of rows of UFOs that fit on the screen. available_space_y = self.settings.screen_height - (2 * ufo_height) number_rows = available_space_y // (2 * ufo_height) # Create the full fleet of UFOs. for row_number in range(number_rows): for ufo_number in range(number_ufo_x): self._create_ufo(ufo_number, row_number) def _create_ufo(self, ufo_number, row_number): """Create and UFO and place it in the row.""" ufo = Ufo(self) ufo_width, ufo_height = ufo.rect.size ufo.x = 5 * ufo_width + 2 * ufo_width * ufo_number ufo.rect.x = ufo.x ufo.y = ufo_height + 2 * ufo_height * row_number ufo.rect.y = ufo.y self.ufos.add(ufo) def _check_fleet_edges(self): """Respond appropriately if any UFO reached an edge.""" for ufo in self.ufos.sprites(): if ufo.check_edges(): self._change_fleet_direction() break def _change_fleet_direction(self): """Drop the entire fleet and change the fleet's direction.""" for ufo in self.ufos.sprites(): ufo.rect.x -= self.settings.fleet_drop_speed self.settings.fleet_direction *= -1 def _update_screen(self): """Update images on the screen, and flip to the new screen.""" self.screen.fill(self.settings.bg_color) self.rocket.blitme() for bullet in self.bullets.sprites(): bullet.draw_bullet() self.ufos.draw(self.screen) pygame.display.flip()