我们在python中制作一个小游戏,但我们在pygame pygame.display.update()函数中遇到了一些问题。它大大降低了我们的fps率(40.000到27),而我们只重新绘制了一个精灵。 (渲染背景和玩家并不重要,它不会下降更多)
我们做错了什么,或者只是python不是那么快?
def render():
screen.blit(background, (0,0))
fred.draw()
pygame.display.update(fred.pos)
FPS 28
def render():
#screen.blit(background, (0,0))
fred.draw()
pygame.display.update(fred.pos)
FPS 31
你可以看到从渲染过程中删除背景只会稍微增加fps。但是当只重绘1或2个精灵时,仍然会从40.000降到28?
完整代码:
import pygame, sys, time
from pygame.locals import *
pygame.init()
size = width, height = 1024, 500
fps = 60
speed = 10
beginTime = time.clock()
screen = pygame.display.set_mode(size)
background = pygame.image.load('/pathtosprite/background.png').convert()
class Fred(object):
strength = 0
pos = 0
sprite = 0
def __init__(self, strength, position):
self.sprite = pygame.image.load('/pathtosprite/fred.png').convert()
self.strength = strength
self.pos = pygame.Rect(10, 10, position[0], position[1])
def draw(self):
screen.blit(self.sprite, self.pos)
def walk(self, direction):
self.pos = self.pos.move(direction)
def tick(): #doet de berekeningen per stap
lastTime = time.clock()
keys = pygame.key.get_pressed()
if keys[K_UP]:
fred.walk([0,-speed])
if keys[K_DOWN]:
fred.walk([0,speed])
if keys[K_RIGHT]:
fred.walk([speed,0])
if keys[K_LEFT]:
fred.walk([-speed,0])
render()
def render(): #updatet het scherm
screen.blit(background, (0,0))
fred.draw()
pygame.display.update(fred.pos)
def run(): #zorgt dat fps gehandhaafd blijft
startTime = time.clock()
ticks = 0
frames = 0
while 1:
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
now = time.clock()
if now-startTime > 1/fps:
ticks += 1
print(ticks/(now-beginTime))
startTime = now
tick()
fred = Fred(10000000, (10, 10))
run()
答案 0 :(得分:0)
执行from pygame.locals import *
表示time
指的是pygame的时间模块,而不是标准的库时间模块。