Pygame矩形不动?

时间:2016-03-05 19:04:53

标签: python pygame pycharm

您好我是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()

enter image description here

请参阅上图。 按右或左键后的样子。

2 个答案:

答案 0 :(得分:3)

在绘图之前使用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建议的全局常量。

答案 1 :(得分:1)

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()
相关问题