user6858805
user6858805

Reputation:

Getting a rectangle to display on the screen in pygame

I have the following code, but for some reason the white rectangle doesn't disply on the screen on running the program. It could have something to do with where I have put various blocks of code, or something else. Could someone please advise? Many thanks in advance:

                            import pygame
                            from pygame.locals import*
                            pygame.init()


                            SCREEN_WIDTH = 400
                            SCREEN_HEIGHT = 300
                            screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

                            # Create the surface and pass in a tuple with its length and width
                            surf = pygame.Surface((50, 50))
                                                    # Give the surface a color to differentiate it from the background
                            surf.fill((255, 255, 255))


                            done = False


                            #---GAME LOGIC HERE -------------#
                            #This is our main loop
                            while not done:
                                #for loop that goes through the event queue
                                    for event in pygame.event.get():
                                        #check for user input (int his case quitting the program)
                                            if event.type == pygame.QUIT:
                                                #if user quits then the done variable is set to True, and exits the loop!
                                                    done = True




                                                    # This line says "Draw surf onto screen at coordinates x:400, y:300"
                                    rect = surf.get_rect()
                                    screen.blit(surf, (400, 300))
                                    pygame.display.flip()

Upvotes: 0

Views: 959

Answers (1)

Travis McPhee
Travis McPhee

Reputation: 61

I've just looked at your code and the reason why you can't see the 'white surface/rectangle' on the screen is because it is being blitted outside of the screen's width and height!

When blitting a Surface or Image etc, the x and y coordinates that you pass for the position will set the surface's top-left pixel at that position. Since you have blitted the rectangle: screen.blit(surf, (400, 300)) at the position (400, 300), which is the screen width and height of the window... Your actually blitting the rectangle outside of the screen. So to fix, all you need to do is change the x and y position to within the screen. Try a position within the screen, maybe (100, 100)? Hope that helped!

-Travis

Upvotes: 3

Related Questions