这次给大家带来使用Python开发简单的小游戏,使用Python开发小游戏的注意事项有哪些,下面就是实战案例,一起来看一下。
创建设置类
接下来,我们创建飞船类ship.py:
import pygameclass Ship(): def init(self,screen): #initialize spaceship and its location self.screen = screen # load bmp image and get rectangle self.image = pygame.image.load('image/ship.bmp') self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() #put spaceship on the bottom of window self.rect.centerx = self.screen_rect.centerx self.rect.bottom = self.screen_rect.bottom def blitme(self): #buld the spaceship at the specific location self.screen.blit(self.image,self.rect)
最后我们在屏幕上绘制飞船,即在alien_invasion.py文件中调用blitme方法:
import sysimport pygamefrom settings import Settingsfrom ship import Settingsdef run_game(): #initialize game and create a dispaly object pygame.init() ai_settings = Settings() screen = pygame.display.set_mode((ai_settings.screen_width,ai_settings.screen_height)) shi<b style="color:transparent">本文来源gao@!dai!ma.com搞$$代^@码网*</b>p = Ship(screen) pygame.display.set_caption("Alien Invasion") # set backgroud color bg_color = (230,230,230) # game loop while True: # supervise keyboard and mouse item for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() # fill color screen.fill(ai_settings.bg_color) ship.blitme() # visualiaze the window pygame.display.flip()run_game()
重构:模块game_functions
在大型项目中,经常需要在添加新代码前重构既有代码。重构的目的是为了简化代码的结构,使其更加容易扩展。我们将实现一个game_functions模块,它将存储大量让游戏Alien invasion运行的函数。通过创建模块game_functions,可避免alien_invasion.py太长,使其逻辑更容易理解。
函数check_events()
首先我们将管理事件的代码移到一个名为check_events()的函数中,目的是为了隔离事件循环
import sysimport pygamedef check_events(): #respond to keyboard and mouse item for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit()
然后我们修改alien_invasion.py代码,导入game_functions模块,并将事件循环替换成对函数check_events()的调用:
import sysimport pygamefrom settings import Settingsfrom ship import Shipimport game_functions as gfdef run_game(): #initialize game and create a dispaly object pygame.init() ai_settings = Settings()
相信看了本文案例你已经掌握了方法,更多精彩请关注搞代码其它相关文章!
推荐阅读:
python怎么逐行读写txt文件
Python调用mysql更新数据的方法
以上就是使用Python开发简单的小游戏的详细内容,更多请关注搞代码gaodaima其它相关文章!