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()
解决方案
您必须lead_x
在lead_y
调用pygame.draw.rect
.
清除显示 ( .fill()
)、绘制矩形 ( pygame.draw.rect()
) 和显示更新 ( pygame.display.update()
) 必须在主循环中完成。所以窗口不断地重绘,并且在每一帧的当前位置绘制矩形:
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()
推荐阅读
- javascript - Discord.js - setNickname 没有足够的权限
- python - 在 NLP 中合并相关词
- google-sheets - 如何在整个工作表中找到具有特定值的单元格
- django - Nginx 在 Django 应用程序上使用 Gunicorn 重定向无法正常工作
- php - \Image::make 生产失败(Laravel)
- javascript - 识别 useStyles 中未使用的样式
- c++ - 为什么我的程序会跳过我的 switch 语句,直接进入默认状态?
- android - 我无法显示可扩展列表的第 4 级
- serverless - 如何调用 Lambda 函数然后使用无服务器返回
- python - 展平和重塑编码器的输入