How to Draw a Rectangle using Pygame



What is Pygame?

Pygame is a Python library designed to develop video games. Pygame adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the Python language.

The Functions We Need!

  • pygame.display.set_mode(): This function is used to initialize a surface for display. This function takes the size of the display as a parameter.
  • pygame.display.flip(): This function is used to update the content of the entire display surface of the screen.
  • pygame.draw.rect(): This function is used to draw a rectangle. It takes the surface, color, and pygame Rect object as an input parameter and draws a rectangle on the surface.

Example 1: Drawing a rectangle and filled it with blue color.

from pygame.locals import *

def main():
pygame.init()

DISPLAY=pygame.display.set_mode((500,400),0,32)

BLUE=(0,0,255)

pygame.draw.rect(DISPLAY,BLUE,(200,150,100,50))

while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
pygame.display.update()

main()

Output:



Example 2: Drawing a rectangle with blue colored outline.

import pygame, sys
from pygame.locals import *

def main():
pygame.init()

DISPLAY=pygame.display.set_mode((500,400),0,32)

BLUE=(0,0,255)

pygame.draw.rect(DISPLAY,BLUE,(200,150,100,50),2)

while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
pygame.display.update()

main()

Output:



Now you have learned how to draw a rectangle using pygame! Thank you a for visiting our blog!

Comments

Popular posts from this blog

LOGIC GATE AND LOGIC GATE ICs | BUCKET OF PROJECTS

THE SG90 SERVO MOTOR WITH AN ARDUINO

KUMAR ANADEN AND HE'S GUINNESS WORLD RECORDS | BUCKET OF PROJECTS

Arduino - Ultrasonic Sensor

LOGIC GATE | XOR GATE | BUCKET OF PROJECTS

IMPORTANCE OF READING | BUCKET OF PROJECTS

LOGIC GATE | AND GATE | BUCKET OF PROJECTS

Scratch - How to Change the Size of Sprite According to the Loudness

Arduino - Led Blink