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("YAKS! in Space") # Create an instance to store game statistics. self.stats = GameStats(self) self.ship = Ship(self) self.bullets = pygame.sprite.Group() self.boomerangs = pygame.sprite.Group() self.aliens = pygame.sprite.Group() self._create_fleet() # set the background color self.bg_color = self.settings.bg_color # Make the Play Button self.play_button = Button(self, "Play") # Create an instance to store game statistics and create a scoreboard. self.stats = GameStats(self) self.sb = Scoreboard(self)
def __init__(self): """Inicjalizacja gry i utworzenie jej zasoboów""" pygame.init() # wyswietlanie tła self.settings = Settings() self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) # self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)# krotka definiujaca fullscrena # self.settings.screen_width = self.screen.get_rect().width # self.settings.screen_height = self.screen.get_rect().height pygame.display.set_caption("Inwazja obcych") #utworzenie egzemplarza do przechowywania danych #dane statystyczne w grze self.stats = GameStats(self) self.sb = Scoreboard(self) self.ship = Ship( self ) # utworzenie egemplrza klasy SHIP, wymaga przekazania obiektu klasy alieninvasion self.bullets = pygame.sprite.Group() self.aliens = pygame.sprite.Group() self._create_fleet() #utworzenie przycisku self.play_button = Button(self, msg="Graj")
def run_game(): pygame.init() ai_setting = Setting() screen = pygame.display.set_mode((ai_setting.screen_width, ai_setting.screen_height)) pygame.display.set_caption('alien invasion') bg_color = ai_setting.bg_color ship = Ship(screen,ai_setting) bullets = Group() allion = Alion(ai_setting, screen) allions = Group() gf.create_fleet(ai_setting, screen, allions, ship) stats = gs(ai_setting) play_btn = Button(ai_setting, screen, 'Play') sb = Scoreboard(ai_setting, screen, stats) # def update_bullet(bullets, allions, ai_setting, screen, ship): while 1: # def check_events(ai_setting, screen, ship, bullets, stats, play_button, allions): gf.check_events(ai_setting, screen, ship, bullets, stats, play_btn, allions) if stats.game_active: ship.update() bullets.update() gf.update_aliens(ai_setting, allions, ship, screen, stats, bullets) gf.update_bullet(bullets, allions, ai_setting, screen, ship, stats, sb) else : print('game is done') gf.update_screen(ai_setting, screen, ship, bullets, allions, stats, play_btn, sb)
def run_game(): # Инициализирует игру и создает объект экрана pygame.init() ai_settings = Settings(bg_url) screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height), pygame.FULLSCREEN) pygame.display.set_caption("Alien Invasion") # Создание кнопки Play play_button = Button(ai_settings, screen, "Play") # Создание корабля ship = Ship(ai_settings, screen, spaceraft_url) # создание экземпляра для хранение игровой статистик stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats, life_ship_url) # Создание группы для хранения пуль bullets = Group() aliens = Group() # Создание флота пришельцев gf.create_fleet(ai_settings, screen, ship, aliens, alien_url) while True: gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, life_ship_url, alien_url) if stats.game_active: ship.update() gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets, life_ship_url, alien_url) gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button)
def run_game(): pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) ship = Ship(ai_settings, screen) bullets = Group() aliens = Group() gf.creat_fleet(ai_settings, screen, ship, aliens) pygame.display.set_caption("Alien Invasion") play_button = Button(ai_settings, screen, "Play") stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats) while True: gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets) if stats.game_active: ship.update() gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button)
def run_game(): # initialize pygame ,settings and screen object pygame.init() ai_settings = Settings() ai_settings.default_settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") # make ship ship = Ship(ai_settings, screen) bullets = Group() aliens = Group() # Create the fleet of aliens gf.create_fleet(ai_settings, screen, ship, aliens) # start the main loop for the game #stats = GameStats(ai_settings) stats = GameStats(ai_settings) play_button = Button(ai_settings, screen, "Play") sb = Scoreboard(ai_settings, screen, stats) while True: # watch for the keyword and mouse events gf.get_events(ai_settings, screen, stats, sb, play_button, ship, bullets) if stats.game_active: pygame.mouse.set_visible(False) ship.update() gf.update_bullets(ai_settings, screen, ship, stats, sb, aliens, bullets) gf.update_aliens(ai_settings, stats, screen, sb, ship, aliens, bullets) gf.update_screen(ai_settings, screen, stats, ship, aliens, sb, bullets, play_button)
def run_game(): # Initialize game and create a screen object. pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") # Make the Play button. play_button = Button(ai_settings, screen, "Play") # Create an instance to store game statistics and create scoreboard. stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats) # Make a ship, a group of bullets, and a group of aliens. ship = Ship(ai_settings, screen) # Make a group to store bullets in. bullets = Group() aliens = Group() # Create the fleet of aliens. gf.create_fleet(ai_settings, screen, ship, aliens) # Make an alien. # Start the main loop for the game. while True: gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets) if stats.game_active: ship.update() gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button)
def run_game(): """初始化游戏并创建屏幕对象""" pygame.init() ai_setting = settings.Settings() screen = pygame.display.set_mode((ai_setting.screen_width, ai_setting.screen_height)) pygame.display.set_caption("Alien Invasion") play_button = Button(ai_setting, screen, "Play") # 创建一艘飞船 ship = Ship(ai_setting, screen) # 创建一个用于存储子弹的编组 bullets = Group() # 创建外星人编组 aliens = Group() game_functions.create_fleet(ai_setting, screen, aliens, ship) # 创建游戏数据 game_status = GameStatus(ai_setting) scoreboard = Scoreboard(ai_setting, screen, game_status) # 游戏主循环 while True: game_functions.check_events(ai_setting, screen, aliens, ship, bullets, game_status, play_button, scoreboard) if game_status.game_active: ship.update() game_functions.update_bullet(aliens, bullets, ai_setting, screen, ship, game_status, scoreboard) game_functions.update_aliens(aliens, ai_setting, ship, game_status, screen, bullets, scoreboard) game_functions.update_screen(ai_setting, screen, ship, aliens, bullets, game_status, play_button, scoreboard)
def __init__(self): self._screen = None self.settings = Settings() self.stats = GameStats(self.settings) self.play_button = Button(self.settings, self.screen, 'Play') self.scoreboard = Scoreboard(self.settings, self.screen, self.stats) self.ship = Ship(self.settings, self.screen) self.bullets = Group() self.aliens = Group()
def __init__(self): ''' Start the game''' pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption("Alien Invasion") #instance to store game stats self.stats = GameStats(self) self.sb = Scoreboard(self) self.ship = Ship(self) self.bullets = pygame.sprite.Group() self.aliens = pygame.sprite.Group() self.alien_bullet = pygame.sprite.Group() self._create_fleet() self.play_button = Button(self, 'Start')
def run_game(): pygame.init() # Initializes background settings for Pygame to work ai_settings = Settings() # we call pygame.display.set_mode to create a display window(screen), arguments are access to file Settings screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") play_button = Button(ai_settings, screen, "Play") stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats) #make a shipSC ship = Ship(ai_settings, screen) bullets = Group() aliens = Group() gf.create_fleet(ai_settings, screen, ship, aliens) while True: #the game is controlled by a this loop. It contains event loop and code that manages screen updates gf.check_events( ai_settings, screen, stats, sb, play_button, ship, aliens, bullets ) #everything is in game_functions kur yra event loop called check_events #tikrinam paspaudimus nors zaidimas neveikia, gali paspausti quit pvz if stats.game_active: #ijungti tik kai True ship.update() #pirma tikrina kulkas, tada ateivius #nes tikrinsim ar kulkos paliete ateivius gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets) #referuoja i skilti apie bullets in game_functions imported as gf gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button) ship.blitme() pygame.display.flip() # Make the most recently drawn screen visible
def run_game(): # Initialize pygame, settings and screen object. pygame.init() ai_settings = settings() screen = pygame.display.set_mode((ai_settings.width, ai_settings.height)) pygame.display.set_caption("Alien Invasion") play_button = Button(ai_settings, screen, "Play") stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats) bg = pygame.image.load('images\space.bmp') bg_image = pygame.transform.scale(bg, (1280, 720)) # make a ship ship = Ship(ai_settings, screen) #make group to store bullets bullets = Group() aliens = Group() alien = Alien(ai_settings, screen) gf.create_fleet(ai_settings, screen, ship, aliens) # Start the main loop for the game. while True: screen.blit(bg_image, (0, 0)) gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets) if stats.game_active: ship.update() gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button)
def run_game(): """ Initialize a game screen """ # Game screen setup pygame.init() game_settings = Settings() screen = pygame.display.set_mode( (game_settings.screen_width, game_settings.screen_height)) pygame.display.set_caption("Alien Invasion") # Create a object to store game stats stats = GameStats(game_settings) # Create a button and score board play_button = Button(game_settings, screen, "Play") score = Scoreboard(game_settings, screen, stats) # Create a ship, alien and bullet ship = Ship(game_settings, screen) bullets = Group() aliens = Group() # Create a group of alien g_func.create_fleet(game_settings, screen, ship, aliens) # Start the game main loop: check keyboard and mouse event, update ship, update bullet and screen while True: g_func.check_events(game_settings, stats, score, screen, play_button, ship, aliens, bullets) if stats.game_active: ship.update() g_func.update_bullets(game_settings, stats, score, screen, ship, aliens, bullets) g_func.update_aliens(game_settings, stats, score, screen, ship, aliens, bullets) g_func.update_screen(game_settings, stats, score, screen, play_button, ship, aliens, bullets)
def run_game(): #初始化游戏并创建一个屏幕对象 pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) # caption :标题 pygame.display.set_caption("Alien chou") # 创建按钮 play_button = Button(ai_settings, screen, 'Play') ship = Ship(ai_settings, screen) # 创建外星人的空编组 aliens = Group() # 创建一个用于存储子弹的编组 # Group类 类似于列表,但提供了有助于开发游戏的额外功能,了解即可class 'pygame.sprite.Group bullets = Group() # 创建外星人群 gf.create_fleet(ai_settings, screen, aliens, ship) # 创建一个用于存储游戏统计信息的实例 history_highest_score = gf.GetHistoryHighestScore(ai_settings) stats = GameStats(ai_settings, history_highest_score) sb = Scoreboard(ai_settings, screen, stats) #开始游戏的 主循环 while True: #监视键盘和鼠标事件 gf.check_events(ai_settings, screen, ship, bullets, stats, play_button, aliens, sb) if stats.game_active: ship.update() gf.update_bullets(ai_settings, aliens, bullets, screen, ship, stats, sb) gf.update_aliens(ai_settings, aliens, ship, stats, screen, bullets, sb) gf.update_screen(ai_settings, screen, ship, bullets, aliens, stats, play_button, sb)
def run_game(): # initialize a game window pygame.init() ai_settings = Settings() screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") # create Play button play_button = Button(ai_settings, screen, "Play") # create initial data object stats = GameStats(ai_settings) # create a ship ship = Ship(ai_settings, screen) # create bullet's group bullets = Group() # create an alien guoup aliens = Group() # create a group alien gf.create_fleet(ai_settings, screen, ship, aliens) # create statistic instance and score board stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats) # start game main loop while True: # verify keyboard and mouse event gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets) if stats.game_active: ship.update() gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button)
import time from turtle import Screen from player import Player from car_manager import CarManager from score_board import Scoreboard screen = Screen() screen.setup(600, 600) screen.title("Turtle Crossing Game") screen.tracer(0) turtle = Player() level = 1 car_manager = CarManager() score = Scoreboard() screen.listen() screen.onkey(turtle.move, "Up") game_is_on = True while game_is_on: time.sleep(0.1) car_manager.create_car() car_manager.move_cars(level) # detect when player hits the top edge if turtle.ycor() > 280: turtle.reset_position() level += 1 score.update_score(level) # detect when player collides with a car for car in car_manager.cars:
from turtle import Turtle, Screen from paddle import Paddle from ball import Ball from score_board import Scoreboard import time screen = Screen() screen.bgcolor("black") screen.setup(width=800, height=600) screen.title("Pong") screen.tracer(0) r_paddle = Paddle((350, 0)) l_paddle = Paddle((-350, 0)) ball = Ball() scoreboard = Scoreboard() screen.listen() screen.onkey(r_paddle.go_up, "Up") screen.onkey(r_paddle.go_down, "Down") screen.onkey(l_paddle.go_up, "w") screen.onkey(l_paddle.go_down, "z") game_on = True while game_on: time.sleep(0.1) screen.update() ball.move()
class AlienInvasion: """Klasa służaca do zarzadzania zasobami i sposobem działania gry """ def __init__(self): """Inicjalizacja gry i utworzenie jej zasoboów""" pygame.init() # wyswietlanie tła self.settings = Settings() self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) # self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)# krotka definiujaca fullscrena # self.settings.screen_width = self.screen.get_rect().width # self.settings.screen_height = self.screen.get_rect().height pygame.display.set_caption("Inwazja obcych") #utworzenie egzemplarza do przechowywania danych #dane statystyczne w grze self.stats = GameStats(self) self.sb = Scoreboard(self) self.ship = Ship( self ) # utworzenie egemplrza klasy SHIP, wymaga przekazania obiektu klasy alieninvasion self.bullets = pygame.sprite.Group() self.aliens = pygame.sprite.Group() self._create_fleet() #utworzenie przycisku self.play_button = Button(self, msg="Graj") def run_game(self): """Rozpoczecie petli głownej gry.""" while True: self._check_events() if self.stats.game_active: self.ship.update() self._bullet_update() self._update_aliens() self._update_screen() def _ship_hit(self): """reakcaj na uderzenie obcego w statek""" if self.stats.ships_left > 0: #zmniejszenie wartosci ships_left self.stats.ships_left -= 1 self.sb.prep_ships() #usuniecie obcych i pociskow self.aliens.empty() self.bullets.empty() #utworzenie zawartosci listy aliens i bullets self._create_fleet() self.ship.center_ship() sleep(0.5) else: self.stats.ships_left -= 1 self.sb.prep_ships() self.stats.game_active = False pygame.mouse.set_visible(True) def _create_fleet(self): """Utworzenie pelnej floty obcych""" #utworzenie obcego, i okreslenei ile obcych miesci sie w rzedzie alien = Alien(self) alien_width, alien_height = alien.rect.size available_space_x = self.settings.screen_width - (4 * alien_width) number_aliens_x = available_space_x // (2 * alien_width) #usalenie ile rzedow obcych zmiesci sie na ekranie ship_height = self.ship.rect.height available_space_y = (self.settings.screen_height - (5 * alien_height) - ship_height) number_rows = available_space_y // (2 * alien_height) #pierwszy rzad obcych for row_number in range(number_rows): for alien_number in range(number_aliens_x): #tworzymy obecego i umieszczamy w rzedzie self._create_alien(alien_number, row_number) def _create_alien(self, alien_number, row_number): """Utworzenie obcego i umieszczenie go w rzedzie""" alien = Alien(self) alien_width, alien_height = alien.rect.size alien.x = alien_width + 2 * alien_width * alien_number alien.rect.x = alien.x alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number self.aliens.add(alien) def _bullet_update(self): """Uaktualnienie polozenia pociskow i usniecie tych nie widocznych""" # uaktualnia polozenie self.bullets.update() # usuniecie pociskow poza ekranem for bullet in self.bullets.copy(): if bullet.rect.bottom <= 0: self.bullets.remove(bullet) self._check_bullet_alien_collisins() def _check_aliens_bottom(self): """sprawdzenie czy ktory kolwiek obcy dotarl do dolnej krawedzi ekranu""" screen_rect = self.screen.get_rect() for alien in self.aliens.sprites(): if alien.rect.bottom >= screen_rect.bottom: self._ship_hit() break def _check_bullet_alien_collisins(self): # sprawdzanie czy pocisk trafil obcego, jesli tak osuwamy i pocisk i obcego collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True) if collisions: for aliens in collisions.values(): self.stats.score += self.settings.alien_points * len(aliens) self.sb.prep_score() self.sb.check_high_score() print(self.sb.stats.score) if not self.aliens: # pozbycie sie pociskow i utworzenie nowej floty self.bullets.empty() self._create_fleet() self.settings.increase_speed() #inkrementacja numeru poziomu self.stats.level += 1 self.sb.prep_level() def _check_events(self): """_metoda pomocnicza nie do wywołania dla egemplarza klasy""" """Reakcja na zdarzenie klawiatury i myszy""" for event in pygame.event.get(): # petla zdarzen if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() self._check_play_button(mouse_pos) elif event.type == pygame.KEYDOWN: # sprawdzamy nacisniecie klawisz self._check_keydown_events(event) elif event.type == pygame.KEYUP: # jesli klawisz podniesiony t # o nie przesuwamy self._check_keyup_events(event) def _check_keydown_events(self, event): """Reakacja na nacisniecie klawisza""" if event.key == pygame.K_RIGHT: # czy nacisniety klawisz to prawy kursor 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_SPACE: self._fire_bullet() elif event.key == pygame.K_q: # zamkniecie w przypadku wcisniecia q sys.exit() def _check_keyup_events(self, event): """Reakcja na zwolnienie klawisz""" 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 _check_play_button(self, mouse_pos): """rozpoczecie nowej gry po wcisnieciu przycisku""" button_clicked = self.play_button.rect.collidepoint(mouse_pos) if button_clicked and not self.stats.game_active: #wyzerowanie ustawien gry self.settings.initialize_dynamic_settings() self.stats.reset_stats() self.stats.game_active = True self.sb.prep_score() self.sb.prep_level() self.sb.prep_ships() #usuniecie listy aliens i bullets self.aliens.empty() self.bullets.empty() #utworzenie nowej floty i wysrodkowanie statku self._create_fleet() self.ship.center_ship() #ukrycie kursora myszy pygame.mouse.set_visible(False) def _fire_bullet(self): """Utworzenie nowego pocisku i dodanie go do grupy pociskow""" if len(self.bullets) < self.settings.bullet_alowed: new_bullet = Bullet(self) self.bullets.add(new_bullet) def _update_screen(self): """Uaktualnianie obrazu na ekranie""" # odswiezanie ekranu self.screen.fill(self.settings.bg_color) # definicja tła self.ship.blitme() # wyswietlenie statkum nad tłem for bullet in self.bullets.sprites(): bullet.draw_bullet() self.aliens.draw(self.screen) #wyswietlenie inf o punktach self.sb.show_score() #wyswietlenie przycisku tylko gdy gra nie aktywna if not self.stats.game_active: self.play_button.draw_button() # wyswietlenie ostatnio zmodyfikowanego ekranu, odswiezanie ekranu pygame.display.flip() def _update_aliens(self): """Uaktualnienie polozenie wszystkich obcych we flocie""" self._check_fleet_edges() self.aliens.update() #wykrywanie kolizji miedzy obcym i statkiem if pygame.sprite.spritecollideany(self.ship, self.aliens): self._ship_hit() #wyszukanie obcych uderzajcych w dolna krawedz self._check_aliens_bottom() def _check_fleet_edges(self): """Odpowiednia reakcja gdy opcy dotrze do krawedzi ekranu""" for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _change_fleet_direction(self): """przesuniecie floty w dol i zmiana kierunku""" for alien in self.aliens.sprites(): alien.rect.y += self.settings.fleet_drop_speed self.settings.fleet_direction *= -1
import time from turtle import Screen, Turtle from player import Player from car_manager import CarManager from score_board import Scoreboard screen = Screen() screen.setup(width=600, height=600) screen.title("Car Turtle Game") screen.tracer(0) player = Player() car = CarManager() time.sleep(0.001) screen.listen() score = Scoreboard() TIMES = 1 LEVEL = 6 game_is_on = True while game_is_on: time.sleep(0.1) screen.update() if TIMES % LEVEL == 0: car.new_car() car.move() screen.onkey(key="Up", fun=player.up) if player.ycor() >= 280: player.goto(0, -280)
difference = 2 timer_game_difficulty_increase = time.time() difference_to_increase_difficulty = 25 number_bullets = 2 number_ships_left_to_increase_diff = 18 # Enemy ships movement control variables index_movement = 0 enemy_movement = [10, 10, -10, -10, -10, -10, 10, 10] # The enemy ships can only move left (- negative values) or right (positive values) # by the following values # player lives lives = 3 points = 0 score = Scoreboard(lives, points) game_is_on = True while game_is_on: time.sleep(0.02) game_screen.update() player_ship_x_position = player_ship.xcor() # check if player bullet reach end of screen and delete them if so for bullet in player_bullets: if bullet.ycor() >= Y_WALL: player_bullets.remove(bullet) else: bullet.bullet_moving() # shoot enemy bullets and move the ships
def run_game(): # 初始化游戏并创建一个屏幕对象 pygame.init() # 将设置赋给ai_settings ai_settings = Settings() # (没有settings版本)screen = pygame.display.set_mode((1200,800)) screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("外星人入侵") # 创建Play按钮实例 play_button = Button(ai_settings, screen, "Play") # 设置背景色 # (没有settings版本)bg_color = (230,230,230) # 创建飞船实例 ship = Ship(ai_settings, screen) # 创建一个用于存储游戏统计信息的实例,并创建记分牌 stats = GameStats(ai_settings) score_board = Scoreboard(ai_settings, screen, stats) '''不再创建 # 创建外星人实例 alien = Alien(ai_settings,screen) ''' # 创建一个用于存储子弹的编组 bullets = Group() # 创建一个用于存储外星人的编组 aliens = Group() # 创建外星人群 gf.creat_fleet(ai_settings, screen, ship, aliens) # 开始游戏的主循环 while True: """ #监视键盘和鼠标事件 for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() """ # 上面可简化为 ↓ gf.check_events(ai_settings, screen, stats, score_board, play_button, ship, aliens, bullets) if stats.game_active: # 在每次循环时都调用飞船移动标志的判断 ship.update() # 子弹 # bullets.update() # 删除已消失的子弹 ''' ######重构至game_functions中的update_bullets()###### for bullet in bullets.copy(): if bullet.rect.bottom <= 0: bullets.remove(bullet) #下面这个语句是检验当子弹到达顶部后是否将子弹从bullets中删除 #print(len(bullets)) ''' gf.update_bullets(ai_settings, screen, stats, score_board, ship, aliens, bullets) # 外星人位置 gf.update_aliens(ai_settings, stats, score_board, screen, ship, aliens, bullets) """ #每次循环都重绘屏幕 #(没有settings版本)screen.fill(bg_color) screen.fill(ai_settings.bg_color) #显示飞船 ship.blitme() #让最近绘制的屏幕可见 pygame.display.flip() """ # 上面代码可简化为 ↓ gf.update_screen(ai_settings, screen, stats, score_board, ship, aliens, bullets, play_button)
class AlienInvasion: '''Class to manage game assesst''' def __init__(self): ''' Start the game''' pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption("Alien Invasion") #instance to store game stats self.stats = GameStats(self) self.sb = Scoreboard(self) self.ship = Ship(self) self.bullets = pygame.sprite.Group() self.aliens = pygame.sprite.Group() self.alien_bullet = pygame.sprite.Group() self._create_fleet() self.play_button = Button(self, 'Start') def run_game(self): ''' Start the main loop for the game''' while True: self._check_events() if self.stats.game_active: self.ship.update() self._update_bullets() self._update_aliens() self._update_screen() def _check_events(self): ''' Respond to keypress and moust 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._check_play_button(mouse_pos) def _check_keydown_events(self, event): ''' Updating for keydown events''' if event.key == pygame.K_RIGHT: # move the ship to the right self.ship.moving_right = True elif event.key == pygame.K_LEFT: self.ship.moving_left = True elif event.key == pygame.K_q: old_high_score = self.stats.high_score self.sb.save_high_score(str(old_high_score)) #print(old_high_score) sys.exit() elif event.key == pygame.K_SPACE: self._fire_bullet() elif event.key == pygame.K_p: self._restart_game() def _check_keyup_events(self, event): ''' Updating for keyup events''' if event.key == pygame.K_RIGHT: self.ship.moving_right = False elif event.key == pygame.K_LEFT: self.ship.moving_left = False def _fire_bullet(self): '''creates a new bullet and adds it to the bullets group''' if len(self.bullets) < self.settings.bullet_allowed: new_bullet = Bullet(self) self.bullets.add(new_bullet) def _update_screen(self): ''' Updating images on the screen and flip to the new screen''' # Redraw screen with for the background color self.screen.fill(self.settings.bg_color) self.ship.blitme() for bullet in self.bullets.sprites(): bullet.draw_bullet() self.aliens.draw(self.screen) #draw score info self.sb.show_score() if not self.stats.game_active: self.play_button.draw_button() # make the most recently drawn screen visible pygame.display.flip() def _update_bullets(self): ''' updating the position of the bullet and getting ride of those at the top of the screen''' #updating bullets position self.bullets.update() #remove the disappeared bullets for bullet in self.bullets.copy(): if bullet.rect.bottom <= 0: self.bullets.remove(bullet) #print(len(self.bullets)) self._check_bullet_alien_collision() def _check_bullet_alien_collision(self): '''response to impacts''' # check if any bullets hit the aliens # if so lets remove the bullet and alien collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True) if collisions: for aliens in collisions.values(): self.stats.score += self.settings.alien_points + len(aliens) self.sb.prep_score() self.sb.check_high_score() if not self.aliens: self._start_new_level() def _create_fleet(self): '''creating the fleet of aliens!''' #creating an alien and find the number of of aliens in a row #spacing between each alien is the width of one alien alien = Alien(self) alien_width, alien_height = alien.rect.size alien_width = alien.rect.width available_space_x = self.settings.screen_width - (2 * alien_width) num_aliens_x = available_space_x // (2 * alien_width) #determine how many rows we can add ship_height = self.ship.rect.height available_space_y = (self.settings.screen_height - (3 * alien_height) - ship_height) num_rows = available_space_y // (3 * alien_height) #create the full fleet! for row_num in range(num_rows): for alien_num in range(num_aliens_x): self._create_alien(alien_num, row_num) def _create_alien(self, alien_num, row_num): # creating an alien and then placing it in a row alien = Alien(self) alien_width, alien_height = alien.rect.size alien.x = alien_width + 2 * alien_width * alien_num alien.rect.x = alien.x alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_num self.aliens.add(alien) def _update_aliens(self): '''Check if the fleet is at the edge and Update the position of the aliens in the fleet''' self._check_fleet_edges() self.aliens.update() #look for alien-ship collisions if pygame.sprite.spritecollideany(self.ship, self.aliens): #print('Ship hit!!!') self._ship_hit() self._check_aliens_bottom() def _check_fleet_edges(self): '''respond to the event of the fleet hitting the edge of the screen''' for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _change_fleet_direction(self): '''drop the fleet and change its direction''' for alien in self.aliens.sprites(): alien.rect.y += self.settings.fleet_drop_speed self.settings.fleet_direction *= -1 def _ship_hit(self): '''response if ship is hit by alien''' if self.stats.ships_left > 0: # you lose a ship self.stats.ships_left -= 1 self.sb.prep_ships() # get rid of any remaining aliens and bullets self.aliens.empty() self.bullets.empty() # create a new fleet and center the ship self._create_fleet() self.ship.center_ship() #pause sleep(0.5) else: self.stats.game_active = False pygame.mouse.set_visible(True) def _check_aliens_bottom(self): '''see if there are any aliens on the bottom''' screen_rect = self.screen.get_rect() for alien in self.aliens.sprites(): if alien.rect.bottom >= screen_rect.bottom: self._ship_hit() break def _check_play_button(self, mouse_pos): ''' start a new game when play is clicked''' button_clicked = self.play_button.rect.collidepoint(mouse_pos) if button_clicked and not self.stats.game_active: self.settings.initialize_dynamic_settings() self._restart_game() def _restart_game(self): # reset game stats self.stats.reset_stats() self.stats.game_active = True #load the images for score, level, ships lives, and high score self.sb.prep_images() # remove any of the bullets and aliens self.aliens.empty() self.bullets.empty() # create new fleet self._create_fleet() self.ship.center_ship() # hide mouse cursor pygame.mouse.set_visible(False) def _start_new_level(self): # destroy existing bullets and create new fleet self.bullets.empty() self._create_fleet() self.settings.increase_speed() # increase the level indication self.stats.level += 1 self.sb.prep_level()
# Screen Setup screen = Screen() screen.setup(width=800, height=600) screen.bgcolor('Black') screen.title('Asteroids') screen.tracer(0) #Instantiant the Spaceship spaceship = Spaceship() #Instantiant the Asteroid asteroid = Asteroid() #Instantiant the Scoreboard scoreboard = Scoreboard() #Create the player's bullet bullet = Bullet() bullet_is_ready = True direction = spaceship.heading() def setup_bullet(): #Move the bullet to be just above the player x = spaceship.xcor() y = spaceship.ycor() bullet.setheading(spaceship.heading()) bullet.setposition(x, y)
class AlienInvasion: """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("YAKS! in Space") # Create an instance to store game statistics. self.stats = GameStats(self) self.ship = Ship(self) self.bullets = pygame.sprite.Group() self.boomerangs = pygame.sprite.Group() self.aliens = pygame.sprite.Group() self._create_fleet() # set the background color self.bg_color = self.settings.bg_color # Make the Play Button self.play_button = Button(self, "Play") # Create an instance to store game statistics and create a scoreboard. self.stats = GameStats(self) self.sb = Scoreboard(self) def run_game(self): """Start the main loop for the game""" while True: # Watch for keyboard and mouse events self._check_events() if self.stats.game_active: self.ship.update() self._update_bullets() self._update_aliens() self._update_boomerangs() self._update_screen() def _change_fleet_direction(self): """Drop the entire fleet and change the fleet's direction.""" for alien in self.aliens.sprites(): alien.rect.y += self.settings.fleet_drop_speed self.settings.fleet_direction *= -1 def _check_aliens_bottom(self): """Check if any aliens have reached the bottom of the screen.""" screen_rect = self.screen.get_rect() for alien in self.aliens: if alien.rect.bottom >= screen_rect.bottom: # Treat this the same as if the ship got hit. self._ship_hit() break def _check_bullet_alien_collions(self): """respond to bullet-alien collisions.""" # Check for any bullets that have hit aliens. # if so, get rid of the bullet and the alien. bullet_collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True) if bullet_collisions: for aliens in bullet_collisions.values(): self.stats.score += self.settings.alien_points * len(aliens) self.sb.prep_score() self.sb.check_high_score() # do the same thing for the boomerangs boomerang_collisions = pygame.sprite.groupcollide( self.boomerangs, self.aliens, False, True) if boomerang_collisions: for aliens in boomerang_collisions.values(): self.stats.score += self.settings.alien_points * len(aliens) self.sb.prep_score() self.sb.check_high_score() if not self.aliens: # Destroy existing bullets and create new fleet. self.bullets.empty() self._create_fleet() self.settings.increase_speed() # Increase the level self.stats.level += 1 self.sb.prep_level() def _check_events(self): """response to keypress 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._check_play_button(mouse_pos) def _check_fleet_edges(self): """Response appropriately if any aliens have reached an edge.""" for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _check_keydown_events(self, event): """respond to keypresses""" 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_q: sys.exit() def _check_keyup_events(self, event): 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_SPACE: self._fire_bullet() elif event.key == pygame.K_b: self._fire_boomerang() def _check_play_button(self, mouse_pos): """Start a new game when the player clicks play.""" button_clicked = self.play_button.rect.collidepoint(mouse_pos) if button_clicked and not self.stats.game_active: # Reset the game statistics self.stats.reset_stats() self.stats.game_active = True self.sb.prep_score() self.sb.prep_level() self.sb.prep_ships() # Reset the game settings self.settings.initialize_dynamic_settings() # Get rid of any remaining aliens and bullets self.aliens.empty() self.bullets.empty() # Create a new fleet and center the ship self._create_fleet() self.ship.center_ship() # Hide the mouse cursor pygame.mouse.set_visible(False) def _create_alien(self, alien_number, row_number): """Create an alien and place it in the row""" alien = Alien(self) alien_width, alien_height = alien.rect.size alien.x = alien_width + 2 * alien_width * alien_number alien.rect.x = alien.x alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number self.aliens.add(alien) def _create_fleet(self): """Create the fleet of aliens.""" # Create an alien and find the number of aliens in a row # Spacing between each alien is equal to one alien width alien = Alien(self) alien_width, alien_height = alien.rect.size available_space_x = self.settings.screen_width - (2 * alien_width) number_aliens_x = available_space_x // (2 * alien_width) # Determine the number of rows of aliens that fit on the screen. ship_height = self.ship.rect.height available_space_y = (self.settings.screen_height - (3 * alien_height) - ship_height) number_rows = available_space_y // (2 * alien_height) # Create teh full fleet of aliens for row_number in range(number_rows): for alien_number in range(number_aliens_x): self._create_alien(alien_number, row_number) def _fire_boomerang(self): """Creates a boomerang and sends it out""" if len(self.boomerangs) < self.settings.boomerang_allowed: new_boomerang = Boomerang(self) self.boomerangs.add(new_boomerang) 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 _ship_hit(self): """Respond to the ship being hit by an alien.""" # Confirm the player still has ships, otherwise the game over if self.stats.ships_left > 0: # Decrement ships_left. self.stats.ships_left -= 1 self.sb.prep_ships() # Get rid of any remaining aliens and bullets self.aliens.empty() self.bullets.empty() self.boomerangs.empty() #Create a new fleet and center the ship self._create_fleet() self.ship.center_ship() #pause sleep(0.5) else: self.stats.game_active = False pygame.mouse.set_visible(True) def _update_aliens(self): """Update the position of all aliens in the fleet.""" self._check_fleet_edges() self.aliens.update() if pygame.sprite.spritecollideany(self.ship, self.aliens): self._ship_hit() # look for aliens hitting the bottom of the screen. self._check_aliens_bottom() def _update_boomerangs(self): """update the position of the boomerangs and get rid of any off the map""" # update boomerang positions self.boomerangs.update() # Get rid of boomerangs that have returned below the ship screen_rect = self.screen.get_rect() for boomerang in self.boomerangs.copy(): if boomerang.rect.top > screen_rect.bottom: self.boomerangs.remove(boomerang) if pygame.sprite.spritecollideany(self.ship, self.boomerangs): self._ship_hit() def _update_bullets(self): """Update position of bullets and get rid of old bullets""" # update bullet positions self.bullets.update() # Get rid of bullets that have disappeared. for bullet in self.bullets.copy(): if bullet.rect.bottom <= 0: self.bullets.remove(bullet) self._check_bullet_alien_collions() def _update_screen(self): """Update images on the scren, and flip to the new screen.""" self.screen.fill(self.bg_color) self.ship.blitme() for bullet in self.bullets.sprites(): bullet.draw_bullet() self.aliens.draw(self.screen) self.boomerangs.draw(self.screen) # Draw the play button if the game is inactive. if not self.stats.game_active: self.play_button.draw_button() # Draw the score information. self.sb.show_score() # Make the most recent drawn screen visible. pygame.display.flip()
from turtle import Turtle, Screen from player import Player from ball import Ball import time from score_board import Scoreboard scn = Screen() scn.bgcolor("black") scn.setup(width=800, height=600) scn.title("Pong") scn.tracer(0) # remove default square animation left_player = Player((-380, 0)) right_player = Player((380, 0)) ball = Ball() score = Scoreboard() scn.listen() scn.onkey(right_player.go_up, "Up") scn.onkey(right_player.go_down, "Down") scn.onkey(left_player.go_up, "w") scn.onkey(left_player.go_down, "s") game_over = False while not game_over: time.sleep(ball.ball_speed) scn.update() ball.move() # Detect Upper and Lower wall collisions
high_score_button = Button( screen, "HIGHSCORES", (ai_settings.screen_width / 2, ai_settings.screen_height - 300), (255, 255, 255), (0, 0, 0)) score_table = HighScoreTable(screen) # used to control fps clock = pygame.time.Clock() # max fps MAX_PFS = 30 # game intro object intro = GameIntro(screen, play_button, high_score_button, ai_settings) score_board = Scoreboard(ai_settings, screen, stats, score_table) fruit = Fruit(0, 0, 19, 19, pac.maze, screen, stats, pac) portal = Portal(screen, pac, pac.rect.x, pac.rect.y, 32, 32, os.getcwd() + '/images/invis_portal.png') fire = False def gameloop(): # temporary fix for variables will create classes and clean the code global fire while not stats.game_exit: # debugging # print(str(pac.rect.x) + ", " + str(pac.rect.y))
from turtle import Screen import time from Snake import Snake from food import Food from score_board import Scoreboard screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.title("Snake Game") screen.tracer(0) game_on = True snake = Snake() food = Food() score_board = Scoreboard() screen.listen() screen.onkey(snake.up, "Up") screen.onkey(snake.down, "Down") screen.onkey(snake.left, "Left") screen.onkey(snake.right, "Right") while game_on: screen.update() time.sleep(.1) snake.move() #score = 0 if snake.head.distance(food) < 15: score_board.update() food.refresh()
from turtle import Screen from snake import Snake from food import Food from score_board import Scoreboard import time screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.title("My Snake Game") screen.tracer(0) snake = Snake() food = Food() scoreboard = Scoreboard() screen.listen() screen.onkey(snake.up, "Up") screen.onkey(snake.down, "Down") screen.onkey(snake.left, "Left") screen.onkey(snake.right, "Right") game_is_on = True while game_is_on: screen.update() time.sleep(0.1) snake.move() if snake.head.distance(food) < 15: food.refresh() snake.extend()
from turtle import Screen from snake import Snake from food import Food from score_board import Scoreboard import time screen = Screen() screen.setup(width=600, height=600) screen.bgcolor('black') screen.title("Snake Game") screen.tracer(0) snake = Snake() food = Food() score = Scoreboard() screen.listen() screen.onkey(snake.up, "Up") screen.onkey(snake.down, "Down") screen.onkey(snake.left, "Left") screen.onkey(snake.right, "Right") game_is_on = True while game_is_on: screen.update() time.sleep(0.1) snake.move() # collision with food if snake.head.distance(food) < 13: food.refresh()
from score_board import Scoreboard import time STARTING_POSITION = [(350, 0), (-350, 0)] screen = Screen() screen.setup(800, 600) screen.bgcolor("black") screen.title("Pong") screen.listen() screen.tracer(0) paddle_l = Paddle(STARTING_POSITION[1]) paddle_r = Paddle(STARTING_POSITION[0]) ball = Ball() score_board = Scoreboard() screen.onkeypress(paddle_r.up, "Up") screen.onkeypress(paddle_r.down, "Down") screen.onkeypress(paddle_l.up, "w") screen.onkeypress(paddle_l.down, "s") game_is_on = True while game_is_on: screen.update() time.sleep(ball.move_speed) ball.move_cars() if abs(ball.ycor()) > 270: ball.bounce_y()