Skip to content
Advertisement

getting the current color of the visible pixel in the pygame module

I am using PYgame to create an environment with multiple cars. etch car has its own radar where it can check the distance between obstacles. the problem that I am having is, how to get the color of a pixel. so if a moving car has the color purple and it is currently over the [x,y] Pixsle I will get the purple cooler not the surface color of the picture screen.

current logic for the radars:

    while not WIN.get_at((x, y)) == pygame.Color(48, 48, 48, 255) and length < 80:
        length += 1
        x = int(xcenter + math.sin(-math.radians(self.angle + radar_angle)) * length)
        y = int(ycenter - math.cos(-math.radians(self.angle + radar_angle)) * length)

    pygame.draw.line(WIN, (255, 255, 255, 0), (xcenter,ycenter), (x, y), 1)
    pygame.draw.circle(WIN, (0, 255, 0, 0), (x, y), 2)
    pygame.display.flip()

this code works great with the screen image.
this code works great with the screen image but not so great with other cars

but not so great with other cars
but not so great with other cars

do there is a function in pygame that handles this case?

Advertisement

Answer

You have to options.

  1. Do the opposite. Test if the color is the gray color of the street:

    street_gray = (128, 128, 128) # use your gray street color here
    
    while WIN.get_at((x, y)) == street_gray and length < 80: 
        # [...]
    
    
  2. Use a pygame.mask.Mask that is 1 at positions of obstacles and 0 elsewhere. When you create the mask you need to set the set_colorkey() for the gray road. The mask can be created with pygame.mask.from_surface. pygame.mask.Mask.get_at returns either 0 or 1:

    win_surf = WIN.copy()
    win_surf.set_colorkey(street_gray)
    street_mask = pygame.mask.from_surface(win_surf)
    
    while street_mask.get_at((x, y)) == 0 and length < 80: 
       # [...]
    
    
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement