首页 > 解决方案 > 如何在pygame中移动一个矩形

问题描述

我正在尝试在 Pygame 中制作一个移动的矩形。我知道我首先需要使用我拥有的 pygame.draw.rect()。我暂时使用在线 IDE,Repl.it。我只需要确保这段代码是正确的。

import pygame, sys
pygame.init()
screen = pygame.display.set_mode((1000,600))
x = 500
y = 300
white = (255,255,255)
player = pygame.draw.rect(screen, white, (x,y,50,40))

while True:
  for event in pygame.event.get():
    if pygame.event == pygame.QUIT:
      pygame.QUIT
      sys.exit()
    if pygame.event == pygame.KEYDOWN:
      if pygame.key == pygame.K_LEFT:
        x -= 5
      if pygame.event == pygame.K_RIGHT:
        x += 5
  pygame.display.update()

感谢您的意见。

标签: pythonpygamerepl.it

解决方案


您的代码即将开始工作。

有几个地方你检查了事件的错误部分,大多数情况下你在多个地方都有同样的错误。

此外,当坐标发生变化时,您不会重新绘制矩形。

import pygame, sys
pygame.init()
screen = pygame.display.set_mode((1000,600))
x = 500
y = 300
black = (  0,  0,  0)
white = (255,255,255)

while True:
    # Handle Events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:            # <<-- HERE use event.type
            pygame.quit()                        # <<-- HERE use pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:       # <<-- HERE use event.type
            if event.key == pygame.K_LEFT:       # <<-- HERE use event.key
                x -= 5
            elif event.key == pygame.K_RIGHT:    # <<-- HERE use event.key
                x += 5

    # Reapint the screen
    screen.fill( black )                                     # erase old rectangle
    player = pygame.draw.rect(screen, white, (x,y,50,40))    # draw new rectangle
    pygame.display.update()

推荐阅读