我们从今天开始研发​主要的游戏部分​。前期我们学习了游戏的引入,最后再学习人工智能的项目。


为了方便我们学习,我可能会对项目进行一定的改动,不用管源代码是什么样。

一定要注意,每次课最后都有课后练习,一定要完成。


要准备些什么?

我们要准备好​开发工具、课程项目​,打开​待完成部分​。我们今天在​​game.py​​内写代码。


需要用到哪些包?

pygame
os
random
time

请妥善保存每一次课的代码进度,以免丢失!


开始写代码!

构建一个窗口

导入包:

import pygame
from random import randint,choice
from time import sleep,time
from os import system,remove
from os.path import exists
from pygame.locals import *

我们先来创建一个窗口:

pygame.init()   
canvas = pygame.display.set_mode((980,700))
canvas.fill((255,255,255))
pygame.display.set_caption('抗击病毒')

判断是否存在运行条件:

try:
if not exists('START.txt'):
pygame.quit()
system('python "抗击病毒.py"')
else:
remove('START.txt')
except:
pass

导入素材

加载图片,储存在对象中:

bg = pygame.image.load('images/hospital.jpg')
doctor = pygame.image.load('images/doctor.png')
virus1 = pygame.image.load('images/virus.png')
virus2 = pygame.image.load('images/virus.jpg')
virus3 = pygame.image.load('images/virus.jpeg')
boss1 = pygame.image.load('images/boss1.png')
boss2 = pygame.image.load('images/boss2.png')
lose = pygame.image.load('images/lose.jpg')
bullet = pygame.image.load('images/bullet.png')
win = pygame.image.load('images/win.jpg')
bag1 = pygame.image.load('images/bag.png')

导入字体对象(我们以后会学到):

font = pygame.font.Font('fonts/font.ttf',45)

组件

为了方便使用,我们使用几个组件,全局赋值如下:

十八、绘制游戏背景图片_python

我们发现,有很多​​con​​开头的函数,它们都是组件。我们把代码封装进去,最后在​​control​​中调用。


创建​​绘制组件​

在​​game.py​​​中,我们创建​​conPaint​​组件,绘制出背景图片:

def conPaint():
canvas.blit(bg,(0,0))

再创建​​control​​函数,调用绘制组件:

def control():
conPaint()
pygame.display.update()

在循环里调用​​control​​函数:

while True:
control()

别看这样麻烦,后期很方便使用。

十八、绘制游戏背景图片_封装_02

已经成功绘制,我们发现还无法关闭,我们一起来处理下关闭事件。


事件

在绘制组件下方,我们插入处理事件的代码:

def event():
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()

调用:

def control():
conPaint()
event()
pygame.display.update()

练习题

绘制出virus1的图片,位置(100,100)。