Last Updated on 2021-12-01 by Clay
Rect is a very important component in Pygame framework. I wanted to wait until I had enough time to write a very detailed article in the original plan, but buttons, input boxes and other components will need to use many Rect component, so I wrote the article first.
The introduction in this article is very simple, and does not mention the more overlap and movement of Rect components, but simply records how to set the attributes of Rect components and draw them on the window.
Let's look at the code directly below.
Sample Code
# coding: utf-8
import pygame
def main():
# Settings
width = 800
height = 600
color_bg = (0, 0, 0)
running = True
# Init
pygame.init()
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Rect Demo")
# Rect(left, top, width, height)
rect_1 = pygame.Rect(0, 0, 100, 100)
rect_2 = pygame.Rect(0, 0, 300, 100)
rect_2.center = (width/2, height/2)
# Run
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Screen
screen.fill(color_bg)
# Draw
pygame.draw.rect(screen, (100, 100, 100), rect_1)
pygame.draw.rect(screen, (255, 0, 255), rect_2)
# Updates
pygame.display.update()
if __name__ == "__main__":
main()
Output:
This code is actually very short, and the focus is under the paragraph # Rect(left, top, width, height)
.
We just need to use pygame.Rect()
that can create a rectangle component, the four input parameters are the left start point, the upper start point, width, and height.
Or we can use Rect.center
to set the center position.
Then use pygame.draw.rect() to draw these rectangular objects.
References
- https://www.geeksforgeeks.org/how-to-draw-rectangle-in-pygame/
- https://www.pygame.org/docs/ref/draw.html