上一节我们为弹球动画增加一个新的功能,就是背景随着小球的移动不断变换,本节我们再给这个动画增加一个功能,就是键盘改变小球速度。通过上下左右四个方向键控制小球在这四个方向的速度,具体的效果是:如果小球正往右移动,此时按右键小球加速向右,如果此时按左键,则减速;反之如果小球向左移动,按左键加速向左,按右键减速,上下键的效果同理,控制向上向下的速度。

具体的方法就是,在游戏的主循环中加入对键盘事件的侦测,判断键盘事件:

1、如果方向左键按下,x方向的速度增加-1,如果小球向左,speed[0]<0,再减1,那么会向左加速,反之向右运动的话会减速:

if event.key == pygame.K_LEFT:
	speed[0] = speed[0] - 1 

2、如果方向右键按下,x方向的速度增加1,如果此时是向左移动,那么speed[0]<0给它加1也就是绝对值减1,速度就会减慢:

elif event.key == pygame.K_RIGHT:
	speed[0] =  speed[0] + 1

3、同理,如果方向右键按下,y方向的速度增加1即:

elif event.key == pygame.K_DOWN:
	speed[1] = speed[1] + 1 

4、如果方向右键按下,y方向的速度增加-1即:

elif event.key == pygame.K_UP:
	speed[1] = speed[1] - 1

完整的程序代码:

import pygame, sys  # 引入pygame sys	
pygame.init()  # 初始化  对pygame内部各功能模块进行初始化创建及变量设置,默认调用
size = width, height = 600, 400

speed = [1,1]
BLACK = 0, 0, 0
screen = pygame.display.set_mode(size)  
pygame.display.set_caption("弹球")  # 设置窗口标题
ball = pygame.image.load("img/ball.png")  # pygame.image.load(filename) 将filename路径下的图像载入游戏,支持13种常用图片格式
ballrect = ball.get_rect()              # surface对象 ball.get_rect() pygame使用内部定义
fps = 300  # Frame per second 每秒帧率参数
fclock = pygame.time.Clock()  # pygame.time.Clock() 创建一个Clock对象,用于操作时间surface对象表示所有载入的图像,其中.get_rect()方法返回一个覆盖图像的矩形(图像的外接矩形)rect对象rect中top, bottom, left, right表示上下左右,width, height表示宽度,高度
bgcolor = pygame.Color("black")
def RGBchannel(a):
	#当a<0时 返回值为0,当a>255时 返回值为255,当0255 else int(a))

while True:  # 执行死循环
    for event in pygame.event.get():  # 从事件队列中取出事件,并从队列中删除该事件
        if event.type == pygame.QUIT:  # pygame.QUIT是Pygame中定义的退出时间常量
            sys.exit()      # sys.exit()用于退出结束游戏并退出
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
               sys.exit()   # sys.exit()用于退出结束游戏并退出
            if event.key == pygame.K_LEFT:
                speed[0] = speed[0] - 1
            elif event.key == pygame.K_RIGHT:
                speed[0] = speed[0] + 1
            elif event.key == pygame.K_DOWN:
                speed[1] = speed[1] + 1 
            elif event.key == pygame.K_UP:
                speed[1] = speed[1] - 1

    if pygame.display.get_active() :     #当显示器上处于活动状态时返回True,进一步半段后可以暂停游戏,改变响应模式等
        ballrect = ballrect.move(speed[0],speed[1])  # ballrect.move(x,y) 矩形移动一个偏移量(x,y)x,y为整数
    if ballrect.left < 0 or ballrect.right > width:
            speed[0] = -speed[0] 
    if ballrect.top < 0 or ballrect.bottom > height:
            speed[1] = -speed[1]  # 碰壁后速度取反
    print(speed)	
    bgcolor.r = RGBchannel(ballrect.left*255/width)
    bgcolor.g = RGBchannel(ballrect.left * 255 / height)
    bgcolor.b = RGBchannel(min(speed[0],speed[1]) * 255 / max(speed[0],speed[1],1))
	#显示窗口背景填充为color颜色采用RGB色彩体系 由于图片不断运动,运动后原位置默认填充白色,因此需要不断刷新
    screen.fill(bgcolor)

    screen.blit(ball, ballrect)     # screnen,blit(src,dest)将图像绘制在另一个图像上,即将src绘制到dest位置上,通过rect对象引导对壁球的绘制
    pygame.display.update()      # 对显示窗口进行刷新,默认窗口全部重绘
    fclock.tick(fps)    # clock.tick(framerate) 控制帧速度,即窗口刷新速度。


本站内容未经许可,禁止任何网站及个人进行转载。

   口袋儿题库-青少儿编程自测题库