python场景建立_【汇智学堂】-python小游戏(太空阻击之三-场景建立)

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值