【问题标题】:My pygame code is running horribly slow, how can I fix it?我的 pygame 代码运行速度非常慢,我该如何解决?
【发布时间】:2020-07-16 02:38:13
【问题描述】:

所以我尝试在 pygame 中制作俄罗斯方块,但运行速度非常慢。我隔离了绘制所有内容的函数,即使它运行得很慢,我该如何解决这个问题? (通过运行我的意思是我得到一个黑屏,并且所需的图像只是在几分钟的过程中从底部缓慢加载。)

附:有一些未使用的变量,因为我懒得注释掉它们,但我不认为几个变量会有很大的不同

import random
import time
import pygame
pygame.init()
win=pygame.display.set_mode((420, 840))
clock= pygame.time.Clock()

score= 0
level= 0
lines= 0
field= [[1]*10 for _ in range(22)]


run= True
play= True
setState= False
t= 48
frameCounter= 0
font= pygame.font.SysFont('arial', 30)

def drawWin():
        tempY= 40
        for y in range(2 ,22):
            tempX= 10
            for x in field[y]:
                if(x==1):
                    win.fill((255, 255, 255), (tempX, tempY, 40, 40))
                    pygame.draw.rect(win, (0, 0, 255), (tempX, tempY, 40, 40), 5)
                tempX+=40
            tempY+=40
        pygame.draw.rect(win, (255, 255, 255), (10, 40, 400, 800), 2)
        text= font.render('Score: '+ str(score)+ '\nLevel: '+ str(level), 1, (255, 255, 255))

while True:
    drawWin()
    for event in pygame.event.get():
        if event.type== pygame.QUIT:
            break
    time.sleep(1)
    clock.tick(t)

pygame.quit()

【问题讨论】:

  • 尝试将 pygame.display.update() 添加到 while 循环的末尾,但不确定 time.sleep(1) 的用途
  • @Andy 是的,关于更新的事情你是对的,不敢相信我忘记了,谢谢。睡眠只是为了测试。
  • 我对此感到困惑的是“所需的图像只是在几分钟内从底部缓慢加载”的说法。没有update(),我根本看不到屏幕上显示的任何内容!
  • @AdvaitM nw!这是有道理的 - 已经正式添加了我的答案,所以我们可以关闭这个 Q(加上总是等待 SO 代表)

标签: python pygame game-development


【解决方案1】:

尝试将 pygame.display.update() 添加到 while 循环的末尾

我之前在运行 Pygame 时遇到过类似的问题 :))

【讨论】:

    【解决方案2】:

    简单的修复,忘记了pygame的更新显示命令。

    【讨论】:

    • @RufusVS 不能接受我自己的 2 天,如果 cmets 中的人想同时添加他自己的答案,我会不接受
    猜你喜欢
    • 1970-01-01
    • 2012-11-05
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    相关资源
    最近更新 更多