pygame实现外星人大战小游戏——飞船创建
生活随笔
收集整理的這篇文章主要介紹了
pygame实现外星人大战小游戏——飞船创建
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
參考資料:Python編程從入門到實踐
#alien_invasion.py import pygame from settings import Settings from ship import Ship import game_functions as gf 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("Alien Invasion")ship = Ship(ai_settings,screen)#bg_color = (ai_settings.bg_color)#screen.fill(bg_color)while True:gf.check_events(ship)ship.update()gf.update_screen(ai_settings,screen,ship)run_game() #settings.py import sys import pygame def check_keydown_events(event,ship):if event.key == pygame.K_RIGHT:ship.moving_right = Trueelif event.key == pygame.K_LEFT:ship.moving_left = True def check_keyup_events(event,ship):if event.key == pygame.K_RIGHT:ship.moving_right = Falseelif event.key == pygame.K_LEFT:ship.moving_left = False def check_events(ship):for event in pygame.event.get():if event.type == pygame.QUIT:sys.exit()elif event.type == pygame.KEYDOWN:check_keydown_events(event,ship)elif event.type == pygame.KEYUP:check_keyup_events(event,ship) def update_screen(ai_settings,screen,ship):screen.fill(ai_settings.bg_color)ship.blitme()pygame.display.flip() #game_functions.py class Settings():def __init__(self):self.screen_width = 1200self.screen_height = 800self.bg_color = (230,230,230)self.ship_speed_factor = 1.5 #ship.py import pygame class Ship():def __init__(self,ai_settings,screen):self.screen = screenself.ai_settings = ai_settingsself.image = pygame.image.load('images/ship.bmp')self.rect = self.image.get_rect()self.screen_rect = screen.get_rect()self.rect.centerx = self.screen_rect.centerxself.center = float(self.rect.centerx)self.rect.bottom = self.screen_rect.bottomself.moving_right = Falseself.moving_left = Falsedef update(self):if self.moving_right and self.rect.right < self.screen_rect.right:self.center += self.ai_settings.ship_speed_factorif self.moving_left and self.rect.left > 0:self.center -= self.ai_settings.ship_speed_factorself.rect.centerx = self.centerdef blitme(self):self.screen.blit(self.image,self.rect)
這樣,一個可以左右移動但不會超出邊界的飛船就做好了。
總結
以上是生活随笔為你收集整理的pygame实现外星人大战小游戏——飞船创建的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 游戏开发中,如何将配置表xlsx转lua
- 下一篇: “百视通”实习日记