python - 如何在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()
感谢您的意见。
解决方案
您的代码即将开始工作。
有几个地方你检查了事件的错误部分,大多数情况下你在多个地方都有同样的错误。
此外,当坐标发生变化时,您不会重新绘制矩形。
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()
推荐阅读
- sql - SQl Live:显示列的最小值,加上同一张表中的对应值,加上第二张表中的相关值
- r - 为什么 cbind 与粘贴的列名相比会引发错误而不是手动输入列名?
- android - 从服务器在我的应用程序中显示图像的最佳方式?
- angular - Angular 6:新 angular.json 格式的“app”部分
- wix - 基于 ALLUSERS / MSIINSTALLPERUSER 的“隐藏”功能
- php - 提交后保留值
- mysql - 使用restful API在sql server中插入和检索图像
- nlp - 如何将 NE 与其依赖项联系起来?
- java - 如何在 javac 中升级 JDK 模块
- r - 如何将特定字符串转换为日期时间?