pygame学习笔记(3):运动速率、时间、事件、文字

473次阅读  |  发布于5年以前

1、运动速率

上节中,实现了一辆汽车在马路上由下到上行驶,并使用了pygame.time.delay(200)来进行时间延迟。看了很多参考材料,基本每个材料都会谈到不同配置机器下运动速率的问题,有的是通过设定频率解决,有的是通过设定速度解决,自己本身水平有限,看了几篇,觉得还是《Beginning Game Development with Python and Pygame》这里面提到一个方法比较好。代码如下,代码里更改的地方主要是main里的代码,其中利用clock=pygame.time.Clock()来定义时钟,speed=250.0定义了速度,每秒250像素,time_passed=clock.tick()为上次运行时间单位是毫秒,time_passed_seconds=time_passed/1000.0将单位改为秒,distance_moved=time_passed_seconds*speed时间乘以速度得到移动距离,这样就能保证更加流畅。

复制代码 代码如下:

import pygame,sys
def lineleft():
plotpoints=[]
for x in range(0,640):
y=-5x+1000
plotpoints.append([x,y])
pygame.draw.lines(screen,[0,0,0],False,plotpoints,5)
pygame.display.flip()
def lineright():
plotpoints=[]
for x in range(0,640):
y=5
x-2000
plotpoints.append([x,y])
pygame.draw.lines(screen,[0,0,0],False,plotpoints,5)
pygame.display.flip()
def linemiddle():
plotpoints=[]
x=300
for y in range(0,480,20):
plotpoints.append([x,y])
if len(plotpoints)==2:
pygame.draw.lines(screen,[0,0,0],False,plotpoints,5)
plotpoints=[]
pygame.display.flip()
def loadcar(yloc):
my_car=pygame.image.load('ok1.jpg')
locationxy=[310,yloc]
screen.blit(my_car,locationxy)
pygame.display.flip()

if name=='main':
pygame.init()
screen=pygame.display.set_caption('hello world!')
screen=pygame.display.set_mode([640,480])
screen.fill([255,255,255])
lineleft()
lineright()
linemiddle()

clock=pygame.time.Clock()  
looper=480  
speed=250.0  
while True:  
    for event in pygame.event.get():  
        if event.type==pygame.QUIT:  
            sys.exit()

    pygame.draw.rect(screen,[255,255,255],[310,(looper+132),83,132],0)  
    time_passed=clock.tick()  
    time_passed_seconds=time_passed/1000.0  
    distance_moved=time_passed_seconds*speed  
    looper-=distance_moved  

    if looper<-480:  
        looper=480    
    loadcar(looper)  

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8