这篇文章给大家分享的是有关如何使用Python写一个小游戏的方法的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
<强>安装pygame 强>
本人电脑是windows 10, python3.6, pygame下载地址:传送门
请自行下载对Python版应本的pygame运行以下命令
,美元pip install 轮 1.9.3美元,pip install  pygame ? ? cp36 ? cp36m ? win_amd64.whl
创建pygame窗口及响应用户输入
新建一个文件夹alien_invasion,并在文件夹中新建alien_invasion。py文件,输入如下代码。
import 系统 import pygame def run_game (): #才能initialize game 以及create a dispaly 对象 pygame.init才能() 时间=screen 才能;pygame.display.set_mode ((1200、800)) pygame.display.set_caption才能(“Alien Invasion") #,才能set backgroud 颜色 bg_color 才能=,(230230230) #,才能game 循环 while 才能正确的: ,,,#,supervise keyboard 以及mouse 项目 ,,,for event 拷贝pygame.event.get (): ,,,,,if event.type ==, pygame.QUIT: ,,,,,,,sys.exit () ,,,#,fill 颜色 ,,,screen.fill (bg_color) ,,,#,visualiaze 从而窗口 ,,,pygame.display.flip () run_game ()
运行上述代码,我们可以得到一个灰色界面的窗口:
<代码> python alien_invasion美元。py 代码>
<强>创建设置类强>
为了在写游戏的过程中能便捷地创建一些新功能,下面额外编写一个设置模块,其中包含一个设置类,用于将所有设置存储在一个地方。这样在以后项目增大时修改游戏的外观就更加容易。我们首先将alien_invasion。py中的显示屏大小及显示屏颜色进行修改。首先在alien_invasion文件夹下新建python文件设置。py,并向其中添加如下代码:
class 设置(对象): “““才能docstring for Settings"““ def 才能__init__(自我): ,,,#,initialize setting of 游戏 ,,,#,screen 设置 ,,,self.screen_width =1200 ,,,self.screen_height =800 ,,,self.bg_color =, (230230230)
然后再alien_invasion。py中导入设置类,并使用相关设置,修改如下:
import 系统 import pygame 得到settings import 设置 def run_game (): #才能initialize game 以及create a dispaly 对象 pygame.init才能() ai_settings =,才能设置() 时间=screen 才能;pygame.display.set_mode ((ai_settings.screen_width ai_settings.screen_height)) pygame.display.set_caption才能(“Alien Invasion") #,才能set backgroud 颜色 bg_color 才能=,(230230230) #,才能game 循环 while 才能正确的: ,,,#,supervise keyboard 以及mouse 项目 ,,,for event 拷贝pygame.event.get (): ,,,,,if event.type ==, pygame.QUIT: ,,,,,,,sys.exit () ,,,#,fill 颜色 ,,,screen.fill (ai_settings.bg_color) ,,,#,visualiaze 从而窗口 ,,,pygame.display.flip () run_game ()
<强>添加飞船图像强>
接下来,我们需要将飞船加入游戏中。为了在屏幕上绘制玩家的飞船,我们将加载一幅图像,再使用Pygame()方法位块传输()绘制它。在游戏中几乎可以使用各种类型的图像文件,但是使用位图(。bmp)文件最为简单,这是因为Pygame默认加载位图。虽然其他类型的图像也能加载,但是需要安装额外的库。我们推荐去免费的图片素材网站上去找图像:传送门。我们在主项目文件夹(alien_invasion)中新建一个文件夹叫图像,将如下bmp图片放入其中。
接下来,我们创建飞船类船。py:
import pygame class 船(): def 才能__init__(自我、屏幕): ,,,# initialize spaceship 以及its 位置 ,,,self.screen =,屏幕上 ,,,#,load bmp image 以及get 矩形 ,,,self.image =, pygame.image.load(& # 39;图像/ship.bmp& # 39;) ,,,self.rect =, self.image.get_rect () ,,,self.screen_rect =, screen.get_rect () ,,,# put spaceship 提醒,bottom of 窗口 ,,,self.rect.centerx =self.screen_rect.centerx ,,,self.rect.bottom =self.screen_rect.bottom def 才能blitme(自我): ,,,# buld 从而spaceship at 从而specific 位置 ,,,self.screen.blit (self.image self.rect)如何使用Python写一个小游戏的方法