0

While I have been learning pygame, I have noticed that the top left corner is considered to be the point where a rectangle is positioned. Because of this, I'm really confused how I would position a rectangle in the middle of the screen.

Here is the code I'm using:

import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((600,600))
pygame.display.set_caption("Basic shapes")
yellow = (255,255,0)
black = (0,0,0)
blue = (0,0,255)
while True:
    screen.fill(yellow)
    pygame.draw.rect(screen,black,(300,300,200,100))
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            exit()
    pygame.display.update()
bananaboss
  • 11
  • 2

1 Answers1

3

One easy way to do this would be to create a Rect object with your desired width and height, then set the center attribute to move the center of the rect to your desired location.

rect = pygame.Rect(0, 0, 200, 100)
rect.center = (300, 300)
pygame.draw.rect(screen, black, rect)

(300,300) because that is the center of your screen.

People often have variables to represent the screen size, like SCREEN_WIDTH and SCREEN_HEIGHT, so if you implemented that you could do something like

SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
...
rect.center = (SCREEN_WIDTH/2, SCREEN_HEIGHT/2)
Starbuck5
  • 1,649
  • 2
  • 7
  • 13