Preventing Image from being cleared [PYGAME- Python] - python

It's extremely painful to redraw each image everytime the screen is cleared.
import pygame
from pygame.locals import *
T = pygame.display.set_mode((500,500))
M = pygame.image.load("test.jpg")
X = 0
Y = 0
while True:
X += 1
Y += 1
# Other sprites are here which are also redrawn every time loop runs.
# Other code is here too, this is just a little part of it to help explain my problem
T.fill((0,0,0))
T.blit(M,(X,Y))
pygame.display.flip()
In the above code, I am loading the background image in M Variable, everytime I clear the screen to update the position of my sprites, I also have to redraw the background image which is causing severe FPS drops.
Anyway I can prevent the Background image from being cleared whenever I am using T.fill((0,0,0)) ?

First, try to convert the background image. Images should usually be converted with convert or convert_alpha to improve the performance.
M = pygame.image.load("test.jpg").convert()
Second, if the background image has the size of the screen you can omit the line T.fill((0,0,0)), since the background fills the screen anyway.
Third, if the background isn't scrolling and you only need to update some portions of the screen every frame, you can try to use pygame.display.update() instead of pygame.display.flip(). Pass a single rect or a list of rects to pygame.display.update to tell it which parts of the screen should be updated.
I'm not sure if these measures will improve the performance drastically. Pygame is rather slow because it still relies on software rendering.
Sidenote, use descriptive variable names instead of T, M, etc..

Related

Python : Update a changing variable in a window using pygame.font

this is my first post, I'm a begginer in programmation, in Python especially
I created a game with a controllable character, you have to avoid an AI, otherwise the chances decrease each times by 1 (from 10 to 0), I want to print chances in real time, but the problem is that it is displayed twice on top of each other, so we can't see the reamaning chances,I Don't know what to do, I already used pygame.display.update(), here's my code's part :
import pygame
pygame.init()
nombreDeFois = 10
font = pygame.font.Font(None, 36)
s = "Chances restantes : " + str(nombreDeFois)
text = font.render(s, 0, (255, 178, 51))
textpos = text.get_rect()
textpos.center = (442,15)
backgroundjeu.blit(text, textpos)
pygame.display.update()
Each time you want to display something on the screen with pygame, it gets added to what is already on the screen, so to update it you must first fill the screen with the background color in order to clear the screen and then display it. Generally, this is done every frame for a game with moving graphics.
E.g.:
display = pygame.display.set_mode(...)
#at the start of the code that runs each frame
display.fill(<insert background color>)
If you are using a background image, blit it again each frame instead.
This also means that everything needs to be redrawn each frame, though, or it would disappear immediately after the first frame.

How do I upload a png image in pygame as a sprite, without the black background?

]How do I get my sprite to appear on the screen. i have been days at this and I couldn't get it to appear on the screen and it kept either taking over the screen as black.
import pygame
pygame.init()
win = pygame.display.set_mode((600,600))
pygame.display.set_caption("Napoleon")
bg = pygame.image.load("apple.png").convert()
win.blit(bg, [0,0])
flower= pygame.image.load("flower2.png").convert()
win.blit(flower, [603,29])
pygame.display.update()
Instead of convert() try convert_alpha(). Assuming your image has an alpha channel (PNG should be good) and it has been applied to your background. If your image has no alpha channel and you need a background gone, you should look into the set_colorkey() function.
Also, for future reference, you can format your code in your question by highlighting it all and pressing CTRL+K. Makes it much easier to read (and you'll get faster answers!)

What do ".subsurface()", ".convert_alpha()", and "%" do?

I'm trying to learn Pygame, and the tutorial that I am following has a section explaining how to animate sprites. It gives me a sprite sheet that has 8 images measuring 128x128 each, while the entire sheet measures 1024x128.
Then it presents the following code:
#! /usr/bin/env_python
import pygame, sys
from pygame.local import *
pygame.init()
ZONE = pygame.display.set_mode((400,300))
pygame.display.set_caption("Game Zone")
RED = (255,0,0)
clock = pygame.time.Clock()
counter = 0
sprites = []
sheet = pygame.image.load("spritesheet.gif").convert_alpha()
width = sheet.get_width()
for i in range(int(width/128)):
sprites.append(sheet.subsurface(i*128,0,128,128))
while True:
pygame.display.update()
ZONE.fill(RED)
ZONE.blit(sprites[counter],(10,10))
counter = (counter + 1) % 8
clock.tick(16)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
The tutorial is very vague about what those lines do, so I wonder:
What does sheet.subsurface() do? And what do those four parameters stand for? (I believe that the third and fourth are referring to the individual images' width and height.)
What does .convert_alpha() do? The tutorial says it "preserves transparency," but I found it strange since I already used images with transparent backgrounds before and none of those needed such conversion.
What does % do? I already know that / stands for division, but the tutorial never explained %.
subsurface gets you a surface that represents a rectangular section of a larger surface. In this case you have one big surface with lots of sprites on it, and subsurface is used to extract the pieces from that surface. You could also create new surfaces and use blit to copy the pixels, but it's a bit easier to use subsurface and it doesn't need to copy the pixel data.
https://www.pygame.org/docs/ref/surface.html#pygame.Surface.subsurface
Suggested search: pygame subsurface
convert and convert_alpha are both used to convert surfaces to the same pixel format as used by the screen. This ensures that you won't lose performance because of conversions when you're blitting them to the screen. convert throws away any alpha channel, whereas convert_alpha keeps it. The comment that you see refers to the choice to use convert_alpha instead of convert, rather than a choice to use convert_alpha instead of nothing.
https://www.pygame.org/docs/ref/surface.html#pygame.Surface.convert
Suggested search: pygame convert_alpha
The '%' operator isn't a Pygame feature, it's just Python's "modulo/remainder" operator. In this case it's used to make the counter variable loop repeatedly through the values 0 through to 7 and back to 0 again.
https://docs.python.org/2/reference/expressions.html#binary-arithmetic-operations
Suggested search: python percent sign
Let's talk about subsurface(). Assume you have 1,600 images you want to load into the program. There are two ways to do that. (Well, more than two, but I'm making a point here.) First, you could create 1,600 files, load each one into a surface in turn, and start the program. Alternately, you could place them in one file, load that one file into a single surface, and use subsurface(). In this case, spritesheet.gif is 128 pixels high, and contains a new image every 128 pixels.
The two ways basically do the same thing, but one may be more convenient than the other. In particular, opening and reading a file has a small performance cost, and if you need to do this 1,600 times in a row, that cost could be significant.
My understanding of a child surface is that it's basically a Pygame Surface, but defined in terms of a parent surface; if you changed the parent Surface, any child surfaces would be changed in the same way. However, in all other ways, it can be treated as a regular surface.

Randomly blitting in Pygame

im making a basic pygame and I was wondering if anyone can help me out
so after a certain amount of time a power-up scrolls down the screen but I cant get it to work
here is the method im using:
def random_event(self):
self.force_img_r = self.force_img.get_bounding_rect()
self.rnd_x = random.randint(5,315)
self.force_img_r.x = self.rnd_x
self.force_img_r.y += 3
screen.blit(self.force_img,(self.rnd_x, self.force_img_r.y))
all its doing is the image is blinking for a split second then nothing
can anyone tell me why its not working!?
In pygame you usually have a main loop that cleans the screen on every iteration, that's probably why you only see a blink, you draw and in the next loop you clean again.
To work arround this, in pygame events should only update game state, and draw the screen on every loop according to the current state.
Some pseudocode:
# Main Loop
while True:
# Process events
# -> Update game state
# Clean screen
# Draw current state to the screen
# Update or flip display
# Keep framerate (clock.Tick())
You can call external classes/methods/functions, but you should always keep this structure at the main loop.

Any way to speed up Python and Pygame?

I am writing a simple top down rpg in Pygame, and I have found that it is quite slow.... Although I am not expecting python or pygame to match the FPS of games made with compiled languages like C/C++ or event Byte Compiled ones like Java, But still the current FPS of pygame is like 15. I tried rendering 16-color Bitmaps instead of PNGs or 24 Bitmaps, which slightly boosted the speed, then in desperation , I switched everything to black and white monochrome bitmaps and that made the FPS go to 35. But not more. Now according to most Game Development books I have read, for a user to be completely satisfied with game graphics, the FPS of a 2d game should at least be 40, so is there ANY way of boosting the speed of pygame?
Use Psyco, for python2:
import psyco
psyco.full()
Also, enable doublebuffering. For example:
from pygame.locals import *
flags = FULLSCREEN | DOUBLEBUF
screen = pygame.display.set_mode(resolution, flags, bpp)
You could also turn off alpha if you don't need it:
screen.set_alpha(None)
Instead of flipping the entire screen every time, keep track of the changed areas and only update those. For example, something roughly like this (main loop):
events = pygame.events.get()
for event in events:
# deal with events
pygame.event.pump()
my_sprites.do_stuff_every_loop()
rects = my_sprites.draw()
activerects = rects + oldrects
activerects = filter(bool, activerects)
pygame.display.update(activerects)
oldrects = rects[:]
for rect in rects:
screen.blit(bgimg, rect, rect)
Most (all?) drawing functions return a rect.
You can also set only some allowed events, for more speedy event handling:
pygame.event.set_allowed([QUIT, KEYDOWN, KEYUP])
Also, I would not bother with creating a buffer manually and would not use the HWACCEL flag, as I've experienced problems with it on some setups.
Using this, I've achieved reasonably good FPS and smoothness for a small 2d-platformer.
All of these are great suggestions and work well, but you should also keep in mind two things:
1) Blitting surfaces onto surfaces is faster than drawing directly. So pre-drawing fixed images onto surfaces (outside the main game loop), then blitting the surface to the main screen will be more efficient. For exmample:
# pre-draw image outside of main game loop
image_rect = get_image("filename").get_rect()
image_surface = pygame.Surface((image_rect.width, image_rect.height))
image_surface.blit(get_image("filename"), image_rect)
......
# inside main game loop - blit surface to surface (the main screen)
screen.blit(image_surface, image_rect)
2) Make sure you aren't wasting resources by drawing stuff the user can't see. for example:
if point.x >= 0 and point.x <= SCREEN_WIDTH and point.y >= 0 and point.y <= SCREEN_HEIGHT:
# then draw your item
These are some general concepts that help me keep FPS high.
When using images it is important to convert them with the convert()-function of the image.
I have read that convert() disables alpha which is normally quite slow.
I also had speed problems until I used a colour depth of 16 bit and the convert function for my images. Now my FPS are around 150 even if I blit a big image to the screen.
image = image.convert()#video system has to be initialed
Also rotations and scaling takes a lot of time to calculate. A big, transformed image can be saved in another image if it is immutable.
So the idea is to calculate once and reuse the outcome multiple times.
When loading images, if you absolutely require transparency or other alpha values, use the Surface.convert_alpha() method. I have been using it for a game I've been programming, and it has been a huge increase in performance.
E.G: In your constructor, load your images using:
self.srcimage = pygame.image.load(imagepath).convert_alpha()
As far as I can tell, any transformations you do to the image retains the performance this method calls. E.G:
self.rotatedimage = pygame.transform.rotate(self.srcimage, angle).convert_alpha()
becomes redundant if you are using an image that has had convert_alpha() ran on it.
First, always use 'convert()' because it disables alpha which makes bliting faster.
Then only update the parts of the screen that need to be updated.
global rects
rects = []
rects.append(pygame.draw.line(screen, (0, 0, 0), (20, 20), (100, 400), 1))
pygame.display.update(rects) # pygame will only update those rects
Note:
When moving a sprite you have to include in the list the rect from their last position.
You could try using Psyco (http://psyco.sourceforge.net/introduction.html). It often makes quite a bit of difference.
There are a few things to consider for a well-performing Pygame application:
Ensure that the image Surface has the same format as the display Surface. Use convert() (or convert_alpha()) to create a Surface that has the same pixel format. This improves performance when the image is blit on the display, because the formats are compatible and blit does not need to perform an implicit transformation. e.g.:
surf = pygame.image.load('my_image.png').convert_alpha()
Do not load the images in the application loop. pygame.image.load is a very time-consuming operation because the image file must be loaded from the device and the image format must be decoded. Load the images once before the application loop, but use the images in the application loop.
If you have a static game map that consists of tiles, you can buy performance by paying with memory usage. Create a large Surface with the complete map. blit the area which is currently visible on the screen:
game_map = pygame.Surface((tile_size * columns, tile_size * rows))
for x in range(columns):
for y in range(rows):
tile_image = # image for this row and column
game_map.blit(tile_image , (x * tile_size, y * tile_size))
while game:
# [...]
map_sub_rect = screen.get_rect(topleft = (camera_x, camera_y))
screen.blit(game_map, (0, 0), map_sub_rect)
# [...]
If the text is static, the text does not need to be rendered in each frame. Create the text surface once at the beginning of the program or in the constructor of a class, and blit the text surface in each frame.
If the text is dynamic, it cannot even be pre-rendered. However, the most time-consuming is to create the pygame.font.Font/pygame.font.SysFont object. At the very least, you should avoid creating the font in every frame.
In a typical application you don't need all permutations of fonts and font sizes. You just need a couple of different font objects. Create a number of fonts at the beginning of the application and use them when rendering the text. For Instance. e.g.:
fontComic40 = pygame.font.SysFont("Comic Sans MS", 40)
fontComic180 = pygame.font.SysFont("Comic Sans MS", 180)

Categories

Resources