使用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 相关文章推荐
用Python实现协同过滤的教程
Apr 08 Python
讲解Python的Scrapy爬虫框架使用代理进行采集的方法
Feb 18 Python
Python的Socket编程过程中实现UDP端口复用的实例分享
Mar 19 Python
Python操作SQLite数据库的方法详解
Jun 16 Python
Python使用sorted排序的方法小结
Jul 28 Python
python lxml中etree的简单应用
May 10 Python
对python特殊函数 __call__()的使用详解
Jul 02 Python
python3 线性回归验证方法
Jul 09 Python
python利用Excel读取和存储测试数据完成接口自动化教程
Apr 30 Python
jupyter notebook 写代码自动补全的实现
Nov 02 Python
Django多数据库联用实现方法解析
Nov 12 Python
如何用 Python 子进程关闭 Excel 自动化中的弹窗
May 07 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对图像的各种处理函数代码小结
2013/07/08 PHP
不同浏览器对回车提交表单的处理办法
2010/02/13 Javascript
js面向对象之静态方法和静态属性实例分析
2015/01/10 Javascript
jquery插件NProgress.js制作网页加载进度条
2015/06/05 Javascript
JavaScript forEach()遍历函数使用及介绍
2015/07/08 Javascript
javascript中判断json的方法总结
2015/08/27 Javascript
jQuery+CSS3实现3D立方体旋转效果
2015/11/10 Javascript
带有定位当前位置的百度地图前端web api实例代码
2016/06/21 Javascript
JS用斜率判断鼠标进入DIV四个方向的方法
2016/11/07 Javascript
使用Math.max,Math.min获取数组中的最值实例
2017/04/25 Javascript
基于hover的用法实例(推荐)
2017/07/04 Javascript
js实现随机点名小功能
2017/08/17 Javascript
详解Webpack+Babel+React开发环境的搭建的方法步骤
2018/01/09 Javascript
jQuery动态移除与增加onclick属性的方法详解
2018/06/07 jQuery
JS实现的冒泡排序,快速排序,插入排序算法示例
2019/03/02 Javascript
详解如何模拟实现node中的Events模块(通俗易懂版)
2019/04/15 Javascript
微信小程序获取用户信息的两种方法wx.getUserInfo与open-data实例分析
2019/05/03 Javascript
java和js实现的洗牌小程序
2019/09/30 Javascript
Vue实现多标签选择器
2019/11/28 Javascript
[05:05]第三天的dota2
2013/07/29 DOTA
[39:07]LGD vs VP 2018国际邀请赛淘汰赛BO3 第二场 8.21
2018/08/22 DOTA
Python中使用MELIAE分析程序内存占用实例
2015/02/18 Python
Python实现的多进程和多线程功能示例
2018/05/29 Python
python实现学员管理系统
2019/02/26 Python
利用python numpy+matplotlib绘制股票k线图的方法
2019/06/26 Python
python实现大文本文件分割
2019/07/22 Python
Python3读写Excel文件(使用xlrd,xlsxwriter,openpyxl3种方式读写实例与优劣)
2020/02/13 Python
利用 PyCharm 实现本地代码和远端的实时同步功能
2020/03/23 Python
基于Python共轭梯度法与最速下降法之间的对比
2020/04/02 Python
采购员的工作职责
2013/12/26 职场文书
找工作求职信
2014/07/07 职场文书
大学生自荐材料范文
2014/12/30 职场文书
司考复习计划
2015/01/19 职场文书
《草虫的村落》教学反思
2016/02/20 职场文书
MySQL 百万级数据的4种查询优化方式
2021/06/07 MySQL
SQL Server中的游标介绍
2022/05/20 SQL Server