当我在Pygame中移动一个对象时,它会在其后面绘制对象的路径

2024-10-02 04:18:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我觉得这个bug很容易解释,所以我就把代码和所发生的事情的截图贴出来

'''
Created on Oct 29, 2012

@author: pipsqueaker
'''
import pygame, sys, random
from pygame.locals import *

frapsClock = pygame.time.Clock()

class Alien:
    def __init__(self, arg1, arg2):
        self.x = arg1
        self.y = arg2
    def move(self, craftx, crafty):
        if self.x < craftx:
            self.x += 1
        elif self.x > craftx:
            self.x -= 1
    if self.y < crafty:
        self.y += 1
    elif self.y > crafty:
        self.y -= 1

class PlayShip():
    def __init__(self, ag1, ag2):
        self.x = ag1
        self.y = ag2

class mainLopp():
    Board = pygame.display.set_mode((650, 500))
    pygame.display.set_caption("This")
    pygame.init()

    player = PlayShip(random.randrange(1, 650), random.randrange(1, 500))
    alienList = [Alien(random.randrange(1, 650), random.randrange(1, 500))]

    while True:
        pygame.draw.rect(Board, (0, 0, 255), (player.x, player.y, 12, 12))

        for currAlien in alienList:
            currAlien.move(player.x, player.y)
            pygame.draw.rect(Board, (255, 0, 0), (currAlien.x, currAlien.y, 16, 16))

        for event in pygame.event.get():
            if event.type == QUIT:
                print(alienList)
                pygame.quit()
                sys.exit()
        pygame.display.update()  
        frapsClock.tick(100)

move()方法应该(随着时间的推移)将外星人(红色)移动到玩家(蓝色)。但是当代码运行时,会发生It isnt supposed to be continuous like this

它不应该是连续的。这就引出了一个问题,我该如何修复它?在


Tags: selfboardmoveifinitdefdisplayrandom
1条回答
网友
1楼 · 发布于 2024-10-02 04:18:29

快速修复:

在主循环之前预创建颜色:

black = pygame.Color('black')

在主循环中:

^{pr2}$

这将在整个屏幕上涂上黑色,有效地擦除所有内容。 这是可以的,因为你重新绘制后,立即删除它。在

在更高级的绘图代码中,您可以:

  • 在旧精灵的上方画一个黑色矩形
  • 然后更新精灵的位置
  • 然后重新绘制精灵。在

相关问题 更多 >

    热门问题