pygame中显示网格时角色移动缓慢 [英] Character moves slowly when grid is displayed in pygame

查看:92
本文介绍了pygame中显示网格时角色移动缓慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 pygame 中制作一个蛇游戏,我注意到一件奇怪的事情.每当我显示网格时,我的角色运行缓慢.
这是我的程序的主要功能.
我刚刚开始学习 pygame!

I am making a snake game in pygame and I noticed a wierd thing. Whenever I am displaying a grid my character runs slowly.
Here is the main function of my program.
I have just started learning pygame!

def main():
    global SCREEN, CLOCK
    pygame.init()
    CLOCK = pygame.time.Clock()
    SCREEN.fill(BLACK)

    x = 0
    y = 0
    velocity = 20
    x_change = 0
    y_change = 0

    while True:
        drawGrid()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    y_change = -velocity
                    x_change = 0
                if event.key == pygame.K_DOWN:
                    y_change = velocity
                    x_change = 0
                if event.key == pygame.K_LEFT:
                    x_change = -velocity
                    y_change = 0
                if event.key == pygame.K_RIGHT:
                    x_change = velocity
                    y_change = 0

        x += x_change
        y += y_change

        snake(x, y)
        pygame.display.update()
        SCREEN.fill(BLACK)
        CLOCK.tick(60)

def snake(x, y):
    head_rect = pygame.Rect(x, y, BLOCKSIZE, BLOCKSIZE)
    pygame.draw.rect(SCREEN, GREEN, head_rect)


def drawGrid():
    for x in range(WINDOW_WIDTH):
        for y in range(WINDOW_HEIGHT):
            rect = pygame.Rect(x*BLOCKSIZE, y*BLOCKSIZE,
                               BLOCKSIZE, BLOCKSIZE)
            pygame.draw.rect(SCREEN, WHITE, rect, 1)

这是示例图片

推荐答案

我不认为重新绘制有任何问题.重新绘制的项目数量较少.

I don't think so there is any issue with re-drawing. The number of items being re-drawn is less.

但是,我可以看到在 draw 函数中,您正在为行和列中的每个像素绘制线条.如果在每一帧中都完成它是非常昂贵的,并且它会不必要地浪费 CPU 能力,因为并非所有的线都位于视口中.尝试执行以下操作(在 range 函数中将 WINDOW_WIDTH 与 BLOCKSIZE 分开):

However, I can see that in the draw function you are drawing lines for each pixel in the row and column. It is very expensive if done in every frame and it is wasting CPU power unnecessarily as not all the lines will lie in the viewport. Try doing the following instead (divide the WINDOW_WIDTH with BLOCKSIZE in the range function):

def drawGrid():
    for x in range(WINDOW_WIDTH // BLOCKSIZE):
        for y in range(WINDOW_HEIGHT // BLOCKSIZE):
            rect = pygame.Rect(x*BLOCKSIZE, y*BLOCKSIZE,
                               BLOCKSIZE, BLOCKSIZE)
            pygame.draw.rect(SCREEN, WHITE, rect, 1)

这篇关于pygame中显示网格时角色移动缓慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆