使用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中os和shutil模块实用方法集锦
May 13 Python
Python编程入门之Hello World的三种实现方式
Nov 13 Python
利用python解决mysql视图导入导出依赖的问题
Dec 17 Python
Python+matplotlib实现计算两个信号的交叉谱密度实例
Jan 08 Python
python 解压pkl文件的方法
Oct 25 Python
Python如何获得百度统计API的数据并发送邮件示例代码
Jan 27 Python
python打包成so文件过程解析
Sep 28 Python
使用PyTorch将文件夹下的图片分为训练集和验证集实例
Jan 08 Python
python相对企业语言优势在哪
Jun 12 Python
通过cmd进入python的步骤
Jun 16 Python
Python3 搭建Qt5 环境的方法示例
Jul 16 Python
python获取系统内存占用信息的实例方法
Jul 17 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 获取select下拉列表框的值
2010/05/08 PHP
sphinx增量索引的一个问题
2011/06/14 PHP
CI框架学习笔记(一) - 环境安装、基本术语和框架流程
2014/10/26 PHP
php下foreach提示Warning:Invalid argument supplied for foreach()的解决方法
2014/11/11 PHP
Laravel中任务调度console使用方法小结
2017/05/07 PHP
php curl上传、下载、https登陆实现代码
2017/07/23 PHP
PHP Socket网络操作类定义与用法示例
2017/08/30 PHP
javascript动画之圆形运动,环绕鼠标运动作小球
2010/07/20 Javascript
js中document.getElementByid、document.all和document.layers区分介绍
2011/12/08 Javascript
jquery图片轮播插件仿支付宝2013版全屏图片幻灯片
2014/04/03 Javascript
jQuery ui 利用 datepicker插件实现开始日期(minDate)和结束日期(maxDate)
2014/05/22 Javascript
兼容主流浏览器的JS复制内容到剪贴板
2014/12/12 Javascript
Javascript创建类和对象详解
2017/05/31 Javascript
VueJs使用Amaze ui调整列表和内容页面
2017/11/30 Javascript
vuex 解决报错this.$store.commit is not a function的方法
2018/12/17 Javascript
小程序扫描普通链接二维码跳转小程序指定界面方法
2019/05/07 Javascript
Vue过渡效果之CSS过渡详解(结合transition,animation,animate.css)
2020/02/05 Javascript
关于你不想知道的所有Python3 unicode特性
2014/11/28 Python
Python扫描IP段查看指定端口是否开放的方法
2015/06/09 Python
Python实现的排列组合、破解密码算法示例
2019/04/12 Python
Python CSV文件模块的使用案例分析
2019/12/21 Python
python 将dicom图片转换成jpg图片的实例
2020/01/13 Python
python设置表格边框的具体方法
2020/07/17 Python
Python新建项目自动添加介绍和utf-8编码的方法
2020/12/26 Python
高中体育教学反思
2014/01/24 职场文书
小学数学教学经验交流材料
2014/05/22 职场文书
建设工地安全标语
2014/06/07 职场文书
科长个人四风问题整改措施思想汇报
2014/10/13 职场文书
市场营销计划书
2015/01/17 职场文书
2015年英语教研组工作总结
2015/05/23 职场文书
2015年中学团委工作总结
2015/07/22 职场文书
运动会开幕式致辞
2015/07/29 职场文书
导游带团欢迎词
2015/09/30 职场文书
求职信如何撰写?
2019/05/22 职场文书
什么是求职信?求职信应包含哪些内容?
2019/08/14 职场文书
光之国的四大叛徒:第一贝利亚导致宇宙毁灭,赛文奥特曼在榜
2022/03/18 日漫