Search code examples
pythonpygamepixelresolution

Why are pixels fuzzy in Pygame?


I am just getting started with Pygame, and I did a little test of just printing pixels in random spots. However, I noticed that the pixels don't seem to be single pixels at all, but 'fuzzy' blobs of a few pixels, as shown in the image. Here's the code I used to draw the pixels: Is there any way to just display single pixels?

Edit: Here's the whole code I used:

import pygame.gfxdraw
import pygame
import random

width = 1000
height = 1000

screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()
running = True

while running:
    x = random.randint(0,1000)
    y = random.randint(0,1000)

    pygame.gfxdraw.pixel(screen, x, y, (225,225,225))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    pygame.display.flip()
    clock.tick(240)

fuzzy pixels

more fuzzy pixels


Solution

  • pygame.gfxdraw.pixel(surface, x, y, color) will draw a single pixel on the given surface. Also you will need to add import pygame.gfxdraw.

    EDIT: Full code:

    import pygame.gfxdraw
    import pygame
    import random
    
    width = 1680
    height = 1050
    
    screen = pygame.display.set_mode((width, height))
    clock = pygame.time.Clock()
    running = True
    
    x = [i for i in range(width - 10)]
    x_full = [i for i in range(width)]
    y = 100
    y_full = [i for i in range(height // 2)]
    
    while running:
    
        for i in x:
            for j in y_full:
                pygame.gfxdraw.pixel(screen, i, j, pygame.Color("red"))
    
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
    
        pygame.display.flip()
        clock.tick(1)
    

    Try to test it this way, I set the window size to fit my monitor resolution so it goes fullscreen. x_full and y should give you horizontal line. And if you subtract, for example, 10 you will get slightly shorter line, and vice-versa with y_full and some random x. Also using (width//2, height//2) will cover exactly quarter of the screen. I think it is accurate and that pygame.gfxdraw.pixel(screen, i, j, pygame.Color("red")) displays only single pixel as it should. In your code you are using random to display pixels and it adds them 240 per second so you are very fast ending up with bunch of pixels at random positions resulting to have pixels close to each other looking as a "bigger one". I think this is what was happening here. Please someone correct me if I am wrong. Also make small window e.g. (100, 100) and draw one pixel at (50, 50) this way it can be more easily seen. If you are on windows use magnifier to test it.

    IMPORTANT: While testing this with huge number of pixels do it OUTSIDE of the loop because it will consume much processor power to display them. Hope this answers your question