Monday, 7 December 2015

Pygame: Draw Rectangle


‘pygame.draw.rect()’ method is used to draw a rectangle on the surface.

Syntax
rect(Surface, color, Rect, width=0)

Example
pygame.draw.rect(screen,BLACK,[25,35,250,100],3)

The first two numbers in the list define the upper left corner at (25, 35).  The next two numbers specify width of 250, and height of 100 in pixels. Last argument specifies the width in 3 pixels. If width is zero then the rectangle will be filled.

pygame_hello.py
#import pygame
import pygame

#initialize game engine
pygame.init()

#Open a window
size = (600, 500)
screen = pygame.display.set_mode(size)

#Set title to the window
pygame.display.set_caption("Hello World")

dead=False

#Initialize values for color (RGB format)
WHITE=(255,255,255)
RED=(255,0,0)
GREEN=(0, 255, 0)
BLUE=(0,0,255)
BLACK=(0,0,0)

clock = pygame.time.Clock()

while(dead==False):
 for event in pygame.event.get(): 
  if event.type == pygame.QUIT:
   dead = True
  
  screen.fill(WHITE)
  pygame.draw.rect(screen,GREEN,[25,35,250,100],3)
  pygame.draw.rect(screen,RED,[125,135,250,100],0)
  pygame.draw.rect(screen,BLUE,[225,235,250,100],3)
  pygame.draw.rect(screen,BLACK,[325,335,250,100],0)
  
  pygame.display.flip()
  clock.tick(60)
   
#Shutdown display module
pygame.display.quit()

Run above program, you will get following output.




Previous                                                 Next                                                 Home

No comments:

Post a Comment