问题
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)
Here are images for sample
回答1:
I don't think so there is any issue with re-drawing. The number of items being re-drawn is less.
I can see a possible bug in the draw function. You are drawing a box for each pixel. Try doing the following instead (divide the WINDOW_WIDTH with BLOCKSIZE):
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)
来源:https://stackoverflow.com/questions/61061963/character-moves-slowly-when-grid-is-displayed-in-pygame