python - Pygame 的矩形不移动?

标签 python pygame pycharm

你好,我是 pygame 的新手。 当我尝试向右或向左移动我的矩形时。矩形不会从一个位置移动到另一个位置,而是向右或向左扩展/延伸。

为什么?

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

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

最佳答案

在绘制之前使用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。如果您声明全部大写可能会更好。红色。因为它是一个全局常量 PEP-8建议。

关于python - Pygame 的矩形不移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35818505/

相关文章:

python - PyGame 在 macOS 上比在 Ubuntu 或 Raspbian 上慢

intellij-idea - 如何在 IntelliJ IDEA、PyCharm 中打开两个终端窗口?

python - 安装 hashLib 会出现 SyntaxError : Missing parentheses in call to 'print'

python - 如何将短语列表转换为单词列表?

Python:傅立叶分析后设计时间序列滤波器

python - PySFTP/Paramiko 异常泄漏到标准错误中

pycharm - PyCharm 中重构的函数名称不适用于笔记本

python - plotly :带有实时图表的破折号按钮不起作用

python - 如何让我的球员在移动的同时仍能旋转?

python - 碰到障碍物后如何修复角色位置?