Thursday 10 December 2015

Pygame: pygame.Surface tutorial

By using pygame.Surface method, we can create new image objects.

Syntax
Surface((width, height), flags=0, depth=0, masks=None) ->Surface
Surface((width, height), flags=0, Surface) -> Surface

Argument
Description
(width, height)
Represent width, height of this surface
flags
flags represent bitmask of additional features for the surface HWSURFACE, creates the image in video memory SRCALPHA, the pixel format will include a per-pixel alpha
depth
The pixel format can be controlled by passing the bit depth or an existing Surface.
masks
The masks are a set of 4 integers representing which bits in a pixel will represent each color.


Following example creates two images using pygame.Surface method and render them on main window.
# import pygame
import pygame

# initialize game engine
pygame.init()

window_width=500
window_height=500

animation_increment=10
clock_tick_rate=20

# Open a window
size = (window_width, window_height)
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()
screen.fill(WHITE)

while(dead==False):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            dead = True

    # Defining new image using surface
    image1 = pygame.Surface([200, 200])
    image1.fill(RED)

    # Adding new circle to image1
    pygame.draw.ellipse(image1, GREEN, [0, 0, 200, 200])

    #Adding two triangles to image1
    pygame.draw.polygon(image1, RED, [[100,0],[0, 100],[200, 100]])
    pygame.draw.polygon(image1, RED, [[0,100],[100, 200],[200, 100]])

     # Defining new image using surface
    image2 = pygame.Surface([300, 300])
    image2.fill(RED)

    # Adding new circle to image2
    pygame.draw.ellipse(image2, GREEN, [0, 0, 300, 300])

    #Adding two triangles to image1
    pygame.draw.polygon(image2, RED, [[150,0],[0, 150],[300, 150]])
    pygame.draw.polygon(image2, RED, [[0,150],[150, 300],[300, 150]])

    # blit method is used to draw images onto screen
    screen.blit(image1, (0, 0))
    screen.blit(image2, (200, 200))

    pygame.display.flip()
    clock.tick(clock_tick_rate)

Previous                                                 Next                                                 Home

No comments:

Post a Comment