This is something I want to use in the game ArkaPyGame.
To grab something from the screen using pygame is not difficult, but it’s a bit tricky at first glance. I made this function to use it in games to save frame rates. For the moment, we will see the basic usage of subsurface. We cannot blit directly on the screen surface, after we grabbed the subsurface. We need to unlock the screen first and we do this blitting the subsurface object on another surface and then blitting this one on the screen surface. Do not worry the grab function will take care of all.
You just need to give the coordinates of the rectangle area on the screen you want to grab, like this:
sub = grab(0, 0, 119, 175)
Remember to have something on the screen to grab, before you do this.
The 0, 0 are the starting corner of the rectangle. 119 is the width of the rectangle and 175 is the height. The image on the example was just 119 x 175.
After you get this sub object, you can blit it on the screen (I made this blit function that is just a shortcut for screeb.blit)
blit(sub, 200, 0)
The original image was this
The result is this, where you see the copied one on the right, that is half of the original, because in the code I put the width to 119 // 2, the half. You can grab what part you want of the screen.
The code
import pygame import sys screen = pygame.display.set_mode((400, 500)) clock = pygame.time.Clock() def grab(x, y, w, h): "Grab a part of the screen" # get the dimension of the surface rect = pygame.Rect(x, y, w, h) # copy the part of the screen sub = screen.subsurface(rect) # create another surface with dimensions # This is done to unlock the screen surface # Unlock screen surface here: screenshot = pygame.Surface((w, h)) screenshot.blit(sub, (0, 0)) return screenshot def blit(part, x, y): screen.blit(part, (x, y)) def quit(): pygame.quit() sys.exit() def start(): # shows half the screen blit(face, 0, 0) # and the other half copied sub = grab(0, 0, 119 // 2, 175) blit(sub, 200, 0) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: quit() pygame.display.update() clock.tick(60) # 119 x 175 face = pygame.image.load("img\\002.png") start()
1.1 – Pong the father of Arkanoid
1.2 – Starting arkanoid… from pong
1.3 – Adding background
1.4 – Collision detection
1.5 – Bricks collisions
1.6 – Still on Collisions
1.7 – Fixed strange bouncing
1.8 – How to destroy the bricks
1.9 – More levels
2.1 – Infinite level generator
2.3 – Sounds and faster frame rate tecnique
2.5 – New nicer levels simmetric and in color and menus
2.6 – Keyboard control
2.7 – Mouse exclusive control
2.xxx – Tiny version
5.0 – Arkagame: 5 different versions
Github repository
https://github.com/formazione/arkapygame
Subscribe to the newsletter for updates
Tkinter templates
My youtube channel
Twitter: @pythonprogrammi - python_pygame