5.3场景建立
如今咱们来设定一下咱们的游戏场景:480*700像素的画布。下面是咱们要作的事情。
一、设置游戏标题、导入游戏资源。
二、更新屏幕,将游戏背景显示出来。web
咱们先来看代码段一:svg
import pygame
from pygame.locals import *
from sys import exit函数
screen_width, screen_height = 480, 700
screen=pygame.display.set_mode((screen_width, screen_height))
background=pygame.image.load(“resources/images/background.png”)
pygame.display.set_caption(‘雷雷的太空大战’)测试
pygame.init()ui
from pygame.locals import *:pygame.locals模块里面包含了不少pygame须要用到的常量,例如set_mode里面窗口的标志(flags)的类型等。另外,程序想使用pygame.locals模块里面pygame的常量的话,就须要使用“from pygame.locals import *”。code
from sys import exit:咱们须要用到exit函数来关闭窗口,从sys库中导入。
screen_width, screen_height = 480, 700:背景图片的分辨率实际是480*700。xml
pygame.display.set_mode:set_mode()函数将会建立一个显示面板(surface),在这里用来显示窗口的大小,若是没有输入或者设置为(0, 0)的话,系统将会把surface的分辨率设置成当前屏幕分辨率(pygame uses sdl version 1.2.10 or above)。blog
pygame.init():将会初始化全部导入的pygame模块。
background=pygame.image.load(“resources/images/background.png”):resources文件夹要跟你的py文件放在一块儿。游戏
如今咱们来绘制游戏场景。代码以下:图片
while 1:
screen.blit(background,(0,0))
pygame.display.update()
#测试时关闭窗口用
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == K_ESCAPE:
running = False
pygame.display.quit()
if event.type == pygame.QUIT:
pygame.quit()
exit()
screen.blit(background,(0,0)):用来绘制图像,第一个参数是图像资源,第二个参数决定图像放置的位置(左上角的坐标)。
pygame.display.update:更新屏幕。
将代码整合起来,整合后完整代码以下:
import pygame
from pygame.locals import *
from sys import exit
screen_width, screen_height = 480, 700
screen=pygame.display.set_mode((screen_width, screen_height))
background=pygame.image.load(“resources/images/background.png”)
pygame.display.set_caption(‘雷雷的太空大战’)
pygame.init()
while 1:
screen.blit(background,(0,0))
pygame.display.update()
#测试时关闭窗口用
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == K_ESCAPE:
running = False
pygame.display.quit()
if event.type == pygame.QUIT:
pygame.quit()
exit()
运行这段代码,在画布上,咱们看到深蓝色的太空中星星点点。见下图5-1。
图5-1