Pygame的矩形没有移动?
Posted
技术标签:
【中文标题】Pygame的矩形没有移动?【英文标题】:Pygame the rectangle is not moving? 【发布时间】:2016-06-19 12:19:43 【问题描述】:您好,我是 pygame 的新手。
当我试图向右或向左移动我的rect
时。矩形不会从一个位置移动到另一个位置,而是向右或向左扩展/扩展。
为什么?
import pygame, sys, time
pygame.init()
red = (255, 0, 0)
gameDisplay = pygame.display.set_mode((800, 600))
pygame.display.set_caption('MyGame')
move_x = 200
move_y = 200
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
move_x -= 10
if event.key == pygame.K_RIGHT:
move_x += 10
# pygame.Rect.move(10, 10)
# gameDisplay.fill(white, rect=[move_x, move_y, 10, 100])
pygame.draw.rect(gameDisplay, red, [move_x, move_y, 10, 10])
pygame.display.update()
pygame.display.flip()
请看上图。 按左右键后的样子。
【问题讨论】:
【参考方案1】:在绘制之前使用surface.fill。
我使用的[0, 0, 0]
在 RGB 代码中是黑色的。你应该声明类似
BLACK = (0, 0, 0)
作为一个常数来避免重复。所以请改变它并像上面一样使用它。
import pygame, sys, time
pygame.init()
red = (255, 0, 0)
gameDisplay = pygame.display.set_mode((800, 600))
pygame.display.set_caption('MyGame')
move_x = 200
move_y = 200
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
move_x -= 10
if event.key == pygame.K_RIGHT:
move_x += 10
# pygame.Rect.move(10, 10)
gameDisplay.fill([0,0,0]) # The line added.
pygame.draw.rect(gameDisplay, red, [move_x, move_y, 10, 10])
pygame.display.update()
pygame.display.flip()
注意不要在fill
方法之前绘制任何东西,因为你用别的东西填充了屏幕,它会被擦除。
编辑:我刚刚意识到你已经定义了red
。如果您将其全部声明为大写,可能会更好。 RED
。因为它是PEP-8 建议的全局常量。
【讨论】:
【参考方案2】:import pygame, sys, time
pygame.init()
red = (255, 0, 0)
gameDisplay = pygame.display.set_mode((800, 600))
background = pygame.Surface(gameDisplay.get_size())
background = background.convert()
background.fill((0,0,0))
pygame.display.set_caption('MyGame')
move_x = 200
move_y = 200
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
move_x -= 10
if event.key == pygame.K_RIGHT:
move_x += 10
# pygame.Rect.move(10, 10)
# gameDisplay.fill(white, rect=[move_x, move_y, 10, 100])
background.fill((0,0,0))
pygame.draw.rect(background, red, [move_x, move_y, 10, 10])
gameDisplay.blit(background, (0, 0))
pygame.display.flip()
【讨论】:
以上是关于Pygame的矩形没有移动?的主要内容,如果未能解决你的问题,请参考以下文章
用pygame实现网上游戏‘球球情侣‘(检测矩形和某颜色碰撞的例子)
用pygame实现网上游戏‘球球情侣‘(检测矩形和某颜色碰撞的例子)