Search code examples
pythonpygamesprite

Using the function 'get_rect' to remove trail


I'm trying to make a game where the red dot moves in the maze using pygame, however when it moves it leaves a trail. I read that I am supposed to use the get_rect function to make it so that it doesn't leave the trail however I have not been successful at implementing it. What am I doing wrong?

map = pygame.image.load('occupancy1.png')
dimx , dimy = 800 , 600
display_surface = pygame.display.set_mode((dimx, dimy))
red = (255, 0, 0)
black = (0 ,0 ,0)
white =(255,255,255)
green = (0 , 255, 0)

#generate initial position on a valid coordinate
rx , ry = (random.randint(0, map.get_width()), random.randint(0, map.get_height()))
while pygame.Surface.get_at(map , (rx, ry)) == black:
    rx = random.randint(0, map.get_width())
    ry = random.randint(0, map.get_height())
    if rx and ry == white:
        break 
rtheta = 0 
step = 2

t = np.radians(25)
event = None
def get_input():   
        fwd = 0 
        turn = 0 
        side = 0 
        if event is not None:            
            if event.type == pygame.KEYDOWN: 
                if event.key == pygame.K_UP:
                   fwd = -step 
                elif event.key == pygame.K_DOWN:
                    fwd = step 
                elif event.key == pygame.K_LEFT:
                    side = -step            
                elif event.key == pygame.K_RIGHT:
                    side = step                     
        return fwd , side 
    
sigma_step = 0.5 
#sigma_turn = np.radians(2)


def move_robot(rx , ry , fwd , side):
    fwd_noisy = np.random.normal(fwd , sigma_step , 1)
    side_noisy = np.random.normal(side , sigma_step , 1)
    rx +=  side_noisy #* np.cos(rtheta)
    ry +=  fwd_noisy #* np.sin(rtheta)    
    print('fwd noisy' , fwd_noisy)   
 
    return rx[0] , ry[0]
                        



while True : 
    for event in pygame.event.get() : 
        if event.type == pygame.QUIT :    
            # deactivates the pygame library
            pygame.quit()
            # quit the program.
            quit()
            
    pygame.time.delay(10)
    fwd , side  = get_input() 
   
     #surface , color , ceter , radius
    pygame.display.update()  
    
    pygame.time.delay(10)
    display_surface.fill(black)
    display_surface.blit(map, (0, 0))
    pygame.draw.circle(map, red, (rx , ry), 2)
    rx, ry = pygame.get_rect.move_robot(rx , ry , fwd , side)``` 

Solution

  • You need to draw the circles on the display instead of on the map:

    pygame.draw.circle(map, red, (rx , ry), 2)

    pygame.draw.circle(display_surface, red, (rx , ry), 2)