为什么形状不会在屏幕上移动?

2024-04-25 13:38:07 发布

您现在位置:Python中文网/ 问答频道 /正文

import pygame 
pygame.init()

gameDisplay= pygame.display.set_mode((800,600))
pygame.display.set_caption("My game!")

gameEnd = False
gameDisplay.fill(white)
pygame.draw.rect(gameDisplay, black, [400,300,10,10])
pygame.display.update()

lead_x = 300
lead_y = 300

while not gameEnd:

    for start in pygame.event.get():
        if start.type == pygame.QUIT:
            gameEnd = True   
        if start.type == pygame.KEYDOWN:
            if start.key == pygame.K_LEFT:
                lead_x -= 10
            if start.key == pygame.K_RIGHT:
                lead_x += 10

pygame.quit()

Tags: keyimportifinitmodemytypedisplay
1条回答
网友
1楼 · 发布于 2024-04-25 13:38:07

在调用pygame.draw.rect时必须使用坐标(lead_xlead_y)。
清除显示(^{})、绘制矩形(^{})和更新显示(^{})必须在主循环中完成。因此,窗口将连续重画,矩形将在每一帧的当前位置绘制:

import pygame 
pygame.init()

gameDisplay= pygame.display.set_mode((800,600))
pygame.display.set_caption("My game!")

black   = (  0,  0,  0)
white   = (255,255,255)
lead_x  = 300
lead_y  = 300
gameEnd = False

while not gameEnd:

    for start in pygame.event.get():
        if start.type == pygame.QUIT:
            gameEnd = True   
        if start.type == pygame.KEYDOWN:
            if start.key == pygame.K_LEFT:
                lead_x -= 10
            if start.key == pygame.K_RIGHT:
                lead_x += 10

    # clear window
    gameDisplay.fill(white)

    # draw rectangle at the current position (lead_x, lead_y)
    pygame.draw.rect(gameDisplay, black, [lead_x,lead_y,10,10])

    # update the display
    pygame.display.update() 

相关问题 更多 >