汇智学堂-phthon小游戏(太空阻击之三-场景创建)

5.3场景创建
现在我们来设定一下我们的游戏场景:480*700像素的画布。下面是我们要做的事情。
1、设置游戏标题、导入游戏资源。
2、更新屏幕,将游戏背景显示出来。

我们先来看代码段一:

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()

from pygame.locals import *:pygame.locals模块里面包含了很多pygame需要用到的常量,例如set_mode里面窗口的标志(flags)的类型等。另外,程序想使用pygame.locals模块里面pygame的常量的话,就需要使用“from pygame.locals import *”。

from sys import exit:我们需要用到exit函数来关闭窗口,从sys库中导入。
screen_width, screen_height = 480, 700:背景图片的分辨率实际是480*700。

pygame.display.set_mode:set_mode()函数将会创建一个显示面板(surface),在这里用来显示窗口的大小,如果没有输入或者设置为(0, 0)的话,系统将会把surface的分辨率设置成当前屏幕分辨率(pygame uses sdl version 1.2.10 or above)。

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

猜你喜欢

转载自blog.csdn.net/weixin_39593940/article/details/88414245