I am making a game in pygame and I copied and pasted my Player class from my previous game but when the player moves it leaves a trail behind but it didn't do that in my previous game where I copied and pasted from. This is the player class:
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.speed = 7
self.frames = []
self.index = 0
for num in range(1, 4):
img = pygame.image.load(f'hunter/img/player/player{num}.png')
img.convert()
img = pygame.transform.scale(img, (75, 75))
self.frames.append(img)
self.player = self.frames[self.index]
self.rect = self.player.get_rect()
self.rect.center = (x, y)
def update(self):
# movement
dx = 0
dy = 0
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
dy -= self.speed
if keys[pygame.K_s]:
dy += self.speed
if keys[pygame.K_a]:
dx -= self.speed
if keys[pygame.K_d]:
dx += self.speed
self.rect.x += dx
self.rect.y += dy
# collison check
if (self.rect.left) + 24 < 0:
self.rect.left = -24
if (self.rect.right) - 24 > 1024:
self.rect.right = 1024 + 24
if (self.rect.top) + 24 < 0:
self.rect.top = -24
if (self.rect.bottom) - 24 > 512:
self.rect.bottom = 512 + 24
# shoot
display.blit(self.player, self.rect)
and this is the main game loop:
player = Player(200, 200)
world = Tile(getTilemap('map1.txt'))
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
player.update()
world.draw()
pygame.display.flip()
CLOCK.tick(60)
pygame.quit()
Code! This is a common issue, and I believe there are other posts covering it. Nonetheless, I will aid you.
When rendering each frame, Pygame does not clear what was previously there. Instead, it simply creates images on top of it. In this case, I believe you drew your player and your maze.
For example, you started off with the black screen, and then drew the player and the maze. Then, you drew the updated player location and the same maze. Therefore, since the black screen wasn't redrawn, we can see the previous frame as well.
The solution? A simple screen.fill((0,0,0))
should do the trick. Stick it in your game loop.
Happy coding!