• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

使用Python开发简单的小游戏

python 搞代码 4年前 (2022-01-09) 26次浏览 已收录 0个评论

这次给大家带来使用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其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:使用Python开发简单的小游戏
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址