../

Rectangles In Pygame

Functions Of Rectangles

Virtual Attributes Which Can Be Used To Move And Align The Rectangles

x,y
top, left, bottom, right
topleft, bottomleft, topright, bottomright
midtop, midleft, midbottom, midright
center, centerx, centery
size, width, height
w,h

Differences Between Surfaces And Rectangles

Surfaces:

Rectangles:

Rectangles For Precise Positioning of Surfaces

  1. Surface For Image information
  2. Placement Via Rectangle
import pygame
from sys import exit

pygame.init()
screen = pygame.display.set_mode((576,400))
pygame.display.set_caption('Runner')
clock = pygame.time.Clock()
ground_surface = pygame.image.load('assets/background/ground.png').convert_alpha()
sky_surface = pygame.image.load('assets/background/sky.png').convert_alpha() # 576 x 324
test_font = pygame.font.Font('assets/fonts/font1.ttf', 25)
text_surface = test_font.render('My Runner Game', False, 'Blue')


enemy_image = pygame.image.load('assets/characters/enemy/enemy.png').convert_alpha()
snail_x_pos = 450

############# Importing the player Image and creating a rectangle ##################
####################################################################################
player_surface = pygame.image.load('assets/characters/player/player.png').convert_alpha()
player_rectangle = player_surface.get_rect(midbottom = (200,324))# creating a recatngle of size player_surface and adjusting the position
####################################################################################
####################################################################################

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

    screen.blit(sky_surface, (0,0))
    screen.blit(ground_surface, (0,76))
    screen.blit(text_surface, (200,50))

    screen.blit(enemy_image, (snail_x_pos, 187))
    snail_x_pos -= 4

    if snail_x_pos < -50:
        snail_x_pos = 570

    ######################### using the rectangle in display Surface #####################################
    ######################################################################################################

    screen.blit(player_surface, player_rectangle) # displaying the rectangle
    player_rectangle.left += 1 # moving the player
    print(player_rectangle.left) # measure the position    

    #######################################################################################################
    #######################################################################################################

    pygame.display.update()
    clock.tick(60)

Tags: /python/ /python3/ /pygame/ /gamedev/ /tutorial/ /animation/