编程语言
首页 > 编程语言> > Python壁球小游戏(展示型)与图像的基本使用

Python壁球小游戏(展示型)与图像的基本使用

作者:互联网

一,壁球小游戏(展示型)

 

四处碰壁且求索的小球 

 

二,壁球小游戏(展示型)的关键要素

从需求到实现的三个关键要素:

        (1)壁球︰游戏需要一个壁球,通过图片引入

        (2)壁球运动∶壁球要能够上下左右运动 

        (3)壁球反弹︰壁球要能够在上下左右边缘反弹

三,壁球小游戏(展示型)     (源代码来了!)

import pygame,sys

pygame.init()
size = width,height = 600,400
speed = [1,1]
BLACK = 0,0,0
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Pygame壁球")
ball = pygame.image.load("PYG02-ball.gif")
ballrect = ball.get_rect()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    ballrect = ballrect.move(speed[0],speed[1])
    if ballrect.left < 0 or ballrect.right >width:
        speed[0] = - speed[0]
    if ballrect.top < 0 or ballrect.bottom > height:
        speed[1] = - speed[1]
    
    screen.fill(BLACK)
    screen.blit(ball,ballrect)
    pygame.display.update()

老师老师,这个壁球太快了,怎么看都看不清?想控制壁球的节奏,且听老师继续讲解..

四,壁球小游戏(节奏型)与屏幕的帧率设置

需求:

        壁球可以按照一定速度运动

从需求到实现的关键要素:

        壁球速度︰如何控制壁球的运动速度呢?

 源代码来了!

import pygame,sys 

pygame.init()
size = width,height = 600,400
speed = [1,1]
BLACK = 0,0,0
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Pygame壁球")
ball = pygame.image.load("PYG02-ball.gif")
ballrect = ball.get_rect()
fps = 300 #Frames per Second每秒帧率参数
fclock = pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    ballrect = ballrect.move(speed[0],speed[1])
    if ballrect.left < 0 or ballrect.right >width:
        speed[0] = - speed[0]
    if ballrect.top < 0 or ballrect.bottom > height:
        speed[1] = - speed[1]

    screen.fill(BLACK)
    screen.blit(ball,ballrect)
    pygame.display.update()
    fclock.tick(fps)

五,代码讲解

pygame.image.load(filename)

将filename路径下的图像载入游戏,支持JPG、PNG、GIF(非动画)等13种常用图片格式

ball = pygame.image.load("PYG02-ball.gif")
ball.get_rect()

Pygame使用内部定义的Surface对象表示所有载入的图像,其中.get_rect()方法返回一个覆盖图像的矩形Rect对象

 Rect对象有一些重要属性,例如∶

 top,bottom,left,right表示上下左右width, height表示宽度、高度

ballrect = ballrect.move(speed[0],speed[1])

 ballrect.move(x , y)
矩形移动一个偏移量(x,y),即在横轴方向移动x像素,纵轴方向移动y像素,xy为整数

    if ballrect.left < 0 or ballrect.right >width:
        speed[0] = - speed[0]
    if ballrect.top < 0 or ballrect.bottom > height:
        speed[1] = - speed[1]

壁球的反弹运动

遇到左右两侧,横向速度取反;

遇到上下两侧,纵向速度取反。

screen.fill(BLACK)   
screen.blit(ball,ballrect)
pygame.display.update()

 screen.fill(color)

显示窗口背景填充为color颜色,采用RGB色彩体系。由于壁球不断运动,运动后原有位置将默认填充白色,因此需要不断刷新背景色

screen. blit( src, dest)

将一个图像绘制在另一个图像上,即将src绘制到dest位置上。通过Rect对象引导对壁球的绘制。

fps = 300 #Frames per Second每秒帧率参数
fclock = pygame.time.Clock()

 pygame .time.Clock()       创建一个clock对象,用于操作时间

fclock.tick(fps)

 clock.tick ( framerate)

控制帧速度,即窗口刷新速度,例如∶clock.tick (100)表示每秒钟100次帧刷新视频中每次展示的静态图像称为帧

 

标签:壁球,ball,ballrect,Python,screen,小游戏,pygame,speed
来源: https://blog.csdn.net/weixin_54822781/article/details/121067934