David Wolters
David Wolters

Reputation: 41

How do you create rect variables in python pygame

I am programming in Python with the pygame library. I want to know how to make a rectangle variable, something like:

import ...
rect1 = #RECT VARIABLE
rect2 = #RECT VARIABLE

Upvotes: 3

Views: 14240

Answers (3)

Brella J
Brella J

Reputation: 31

Just do

pygame.Rect(left, top, width, height)

this will return you a Rect object in pygame

Upvotes: 3

Jean Alves
Jean Alves

Reputation: 78

Perhaps something like this will work?

import pygame
# your whole code until you need a rectangle
rect1 = pygame.draw.rect( (x_coordinate, y_coordinate), (#a rgb color), (#size of rect in pixels) )

If you want a red rectangle with 100x150 size in 0x50 position, it will be:

rect1 = pygame.draw.rect( (0, 50), (255, 0, 0), (100, 150) )

To insert it into the screen you use:

pygame.screen_you_have_created.blit(rect1, 0, 50)

Upvotes: 1

Niraj
Niraj

Reputation: 1261

For rectangle draw pattern is : pygame.Rect(left, top, width, height)

You can modify this code according to your need.

import pygame, sys
from pygame.locals import *
pygame.init()
windowSurface = pygame.display.set_mode((500, 400), 0, 32)
pygame.display.set_caption('Title')
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
basicFont = pygame.font.SysFont(None, 48)
message =  'Hello '

text = basicFont.render(message, False, WHITE, BLUE)
textRect = text.get_rect()
textRect.centerx = windowSurface.get_rect().centerx
textRect.centery = windowSurface.get_rect().centery
windowSurface.fill(WHITE)
pixArray = pygame.PixelArray(windowSurface)
pixArray[480][380] = BLACK
del pixArray
windowSurface.blit(text, textRect)
pygame.display.update()
while True:
    for event in pygame.event.get():
        if event.type == K_ESCAPE:
            pygame.quit()
            sys.exit()

Upvotes: -1

Related Questions