'Pygame Issue with importing a rectangle for a game [closed]
I have a small question about placing a rectangle in pygame. When I run the code i dont see a rectangle. Does anyone knows how to fix this?
import pygame as pg
from pygame.locals import *
pg.init()
BLACK = ( 0, 0, 0)
WHITE = ( 255, 255, 255)
GREEN = ( 0, 255, 0)
RED = ( 255, 0, 0)
size = width, height = (800, 800)
screen = pg.display.set_mode(size)
pg.display.set_caption("Ball Game")
screen.fill((10, 255, 255))
pg.display.update()
running = True
clock = pg.time.Clock()
#board = pg.draw.rect(screen, BLACK, pg.Rect(30, 30, 60, 60))
#board_loc = pg.
#board_loc.center = width/2, height*0.8
background_image = pg.image.load("pngtree-blue-cartoon-minimalist-planet-surface-starry-sky-main-map-background-image_186868.jpg").convert()
while running:
for event in pg.event.get():
if event.type == QUIT:
running = False
screen.blit(background_image, [0, 0])
pg.display.flip()
#screen.blit(board, board_loc)
rect = pg.Rect(0, 0, 200, 100)
rect.center = (300, 300)
pg.draw.rect(screen, BLACK, rect)
clock.tick(30)
pg.quit()
Solution 1:[1]
You have to update the display after drawing the rectangle:
rect = pg.Rect(0, 0, 200, 100)
rect.center = (300, 300)
while running:
for event in pg.event.get():
if event.type == QUIT:
running = False
# draw background
screen.blit(background_image, [0, 0])
# draw rectangle on top of the background
pg.draw.rect(screen, BLACK, rect)
# update display
pg.display.flip()
You are actually drawing on a Surface
object. If you draw on the Surface associated to the PyGame display, this is not immediately visible in the display. The changes become visible, when the display is updated with either pygame.display.update()
or pygame.display.flip()
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rabbid76 |