Search code examples
pythonpygamesurface

pygame surface doesn't show up


I have been doing some test with pygame but I am stuck with surfaces. I cannot draw a surface or something on it. Here is my code:

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))
#surface = pygame.Surface((100, 100))
done = False
screen.fill((255, 255, 255))


while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True


    #surface = pygame.Surface((50, 50))
    surface = pygame.Surface((100, 100))
    #surface.fill((255, 0, 0))
    #surface.set_colorkey((255, 0, 0))
    pygame.draw.circle(surface, (0,0,0), (25,25),25) 
    #pygame.draw.rect(screen, (0, 128, 255), pygame.Rect(30, 30, 60, 60))

    pygame.display.flip()

So when I want to draw something onto screen it draws it:

This works:

pygame.draw.circle(screen, (0,0,0), (25,25),25)

But this not:

pygame.draw.circle(surface, (0,0,0), (25,25),25) 

I have read some documents, but it seems that is enough to call the surface and put the background to white, because it draws it black by default. I really don't what I am doing wrong.

I hope is enough information.

Cheers.


Solution

  • Pygame has different types of surfaces. Besides normal surfaces, there are also displays. A display is a type of surface, but a surface is not a type of display. The difference between these is that displays are displayed on the screen, normal surfaces are not.

    Pygame surfaces are created with pygame.Surface, while displays are created with pygame.display.set_mode. In Pygame, you can only have one display at a time, but you can have any amount of surfaces that you desire.

    Assuming screen is your display, and surface is your other surface, here is how you would display the surface on the screen:

    screen.blit(surface, [x,y])
    

    x and y are the coordinates of where they are displayed on the display.

    In your program, you never blit the surface onto the display, so it is never shown. Simply do that, and the program will work unless there is also another issue with your code.

    If this does not fix your problem, please notify me in the comments and I'll see what I can do to help.

    Refer to https://www.pygame.org/docs/ref/display.html and https://www.pygame.org/docs/ref/surface.html.