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=-5*x+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():
新聞熱點
疑難解答