使用Python写一个小游戏


Posted in Python onApril 02, 2018

引言

最近python语言大火,除了在科学计算领域python有用武之地之外,在游戏、后台等方面,python也大放异彩,本篇博文将按照正规的项目开发流程,手把手教大家写个python小游戏,来感受下其中的有趣之处。本次开发的游戏叫做alien invasion。

安装pygame并创建能左右移动的飞船

安装pygame

本人电脑是windows 10、python3.6,pygame下载地址: 传送门

请自行下载对应python版本的pygame 运行以下命令

$ pip install wheel
$ pip install pygame‑1.9.3‑cp36‑cp36m‑win_amd64.whl

创建Pygame窗口及响应用户输入

新建一个文件夹alien_invasion,并在文件夹中新建alien_invasion.py文件,输入如下代码。

import sys
import pygame
def run_game():
  #initialize game and create a dispaly object
  pygame.init()
  screen = pygame.display.set_mode((1200,800))
  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(bg_color)
    # visualiaze the window
    pygame.display.flip()
run_game()

运行上述代码,我们可以得到一个灰色界面的窗口:

$ python alien_invasion.py

使用Python写一个小游戏

创建设置类

为了在写游戏的过程中能便捷地创建一些新功能,下面额外编写一个settings模块,其中包含一个Settings类,用于将所有设置存储在一个地方。这样在以后项目增大时修改游戏的外观就更加容易。 我们首先将alien_invasion.py中的显示屏大小及显示屏颜色进行修改。 首先在alien_invasion文件夹下新建python文件settings.py,并向其中添加如下代码:

class Settings(object):
  """docstring for Settings"""
  def __init__(self):
    # initialize setting of game
    # screen setting
    self.screen_width = 1200
    self.screen_height = 800
    self.bg_color = (230,230,230)

然后再alien_invasion.py中导入Settings类,并使用相关设置,修改如下:

import sys
import pygame
from settings import Settings
def 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))
  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)
    # visualiaze the window
    pygame.display.flip()
run_game()

添加飞船图像

接下来,我们需要将飞船加入游戏中。为了在屏幕上绘制玩家的飞船,我们将加载一幅图像,再使用Pygame()方法blit()绘制它。 在游戏中几乎可以使用各种类型的图像文件,但是使用位图(.bmp)文件最为简单,这是因为Pygame默认加载位图。虽然其他类型的图像也能加载,但是需要安装额外的库。我们推荐去免费的图片素材网站上去找图像: 传送门 。我们在主项目文件夹(alien_invasion)中新建一个文件夹叫images,将如下bmp图片放入其中。

使用Python写一个小游戏

接下来,我们创建飞船类ship.py:

import pygame
class 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 sys
import pygame
from settings import Settings
from ship import Settings
def 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))
  ship = 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 sys
import pygame
def 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 sys
import pygame
from settings import Settings
from ship import Ship
import game_functions as gf
def run_game():
  #initialize game and create a dispaly object
  pygame.init()
  ai_settings = Settings()

总结

以上所述是小编给大家介绍的Python写一个小游戏,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!

Python 相关文章推荐
python3编码问题汇总
Sep 06 Python
python中文件变化监控示例(watchdog)
Oct 16 Python
python实现BackPropagation算法
Dec 14 Python
Python实现PS图像调整之对比度调整功能示例
Jan 26 Python
Python如何调用JS文件中的函数
Aug 16 Python
python队列原理及实现方法示例
Nov 27 Python
Python如何把多个PDF文件合并代码实例
Feb 13 Python
Pycharm的Available Packages为空的解决方法
Sep 18 Python
python3.7中安装paddleocr及paddlepaddle包的多种方法
Nov 27 Python
Python+Xlwings 删除Excel的行和列
Dec 19 Python
Python3使用Selenium获取session和token方法详解
Feb 16 Python
Python selenium绕过webdriver监测执行javascript
Apr 12 Python
Python3.5.3下配置opencv3.2.0的操作方法
Apr 02 #Python
Ubuntu16.04/树莓派Python3+opencv配置教程(分享)
Apr 02 #Python
Linux-ubuntu16.04 Python3.5配置OpenCV3.2的方法
Apr 02 #Python
浅谈配置OpenCV3 + Python3的简易方法(macOS)
Apr 02 #Python
Window10+Python3.5安装opencv的教程推荐
Apr 02 #Python
Python浅复制中对象生存周期实例分析
Apr 02 #Python
python基础教程项目五之虚拟茶话会
Apr 02 #Python
You might like
谨慎使用PHP的引用原因分析
2012/09/06 PHP
php不允许用户提交空表单(php空值判断)
2013/11/12 PHP
php使用curl出现Expect:100-continue解决方法
2015/03/03 PHP
Yii获取当前url和域名的方法
2015/06/08 PHP
Yii1.1中通过Sql查询进行的分页操作方法
2017/03/16 PHP
PHP使用第三方即时获取物流动态实例详解
2017/04/27 PHP
PHP使Laravel为JSON REST API返回自定义错误的问题
2018/10/16 PHP
PHP chr()函数讲解
2019/02/11 PHP
jQuery基本选择器选择元素使用介绍
2013/04/18 Javascript
js中Math之random,round,ceil,floor的用法总结
2013/12/26 Javascript
javascript判断是手机还是电脑访问网页的简单实例分享
2014/06/03 Javascript
jquery中ajax使用error调试错误的方法
2015/02/08 Javascript
jQuery获得包含margin的outerWidth和outerHeight的方法
2015/03/25 Javascript
超详细的javascript数组方法汇总
2015/11/21 Javascript
nodejs对express中next函数的一些理解
2017/09/08 NodeJs
Vue之mixin全局的用法详解
2018/08/22 Javascript
vue 登录滑动验证实现代码
2018/08/24 Javascript
Vue.js 中 axios 跨域访问错误问题及解决方法
2018/11/21 Javascript
angula中使用iframe点击后不执行变更检测的问题
2020/05/10 Javascript
JavaScript实现简易计算器小功能
2020/10/22 Javascript
Python中用函数作为返回值和实现闭包的教程
2015/04/27 Python
python查看模块安装位置的方法
2018/10/16 Python
Python 获取numpy.array索引值的实例
2019/12/06 Python
Python+appium框架原生代码实现App自动化测试详解
2020/03/06 Python
python re的findall和finditer的区别详解
2020/11/15 Python
突袭HTML5之Javascript API扩展5—其他扩展(应用缓存/服务端消息/桌面通知)
2013/01/31 HTML / CSS
HTML5之语义标签介绍
2016/07/07 HTML / CSS
夏威夷咖啡公司:Hawaii Coffee Company
2019/09/19 全球购物
烹饪自我鉴定
2014/03/01 职场文书
亮剑精神演讲稿
2014/05/23 职场文书
敬老月活动总结
2014/08/28 职场文书
2014院党委领导班子及其成员群众路线对照检查材料思想汇报
2014/10/04 职场文书
离婚协议书怎样才有法律效力
2014/10/10 职场文书
捐款通知怎么写
2015/04/24 职场文书
Python实现拼音转换
2021/06/07 Python
Docker容器harbor私有仓库部署和管理
2022/08/05 Servers