A bit confused with blitting (Pygame) - python

I've just started learning some pygame (quite new to programming overall), and I have some very basic questions about how it works.
I haven't found a place yet that explains when I need to blit or not to include a certain surface on the screen. For example, when drawing a circle:
circle = pygame.draw.circle(screen, (0, 0, 0), (100, 100), 15, 1)
I don't need to do screen.blit(circle), but when displaying text:
text = font.render("TEXT", 1, (10, 10, 10))
textpos = text.get_rect()
textpos.centerx = screen.get_rect().centerx
screen.blit(text, textpos)
If I don't blit, the text won't appear.
To be honest, I really don't know what blitting is supposed to do, apart from "pasting" the desired surface onto the screen. I hope I have been clear enough.

The short answer
I haven't found a place yet that explains when I need to blit or not to include a certain surface on the screen.
Each operation will behave differently, and you'll need to read the documentation for the function you're working with.
The long answer
What Is Blitting?
First, you need to realize what blitting is doing. Your screen is just a collection of pixels, and blitting is doing a complete copy of one set of pixels onto another. For example, you can have a surface with an image that you loaded from the hard drive, and can display it multiple times on the screen in different positions by blitting that surface on top of the screen surface multiple times.
So, you often have code like this...
my_image = load_my_image()
screen.blit(my_image, position)
screen.blit(my_image, another_position)
In two lines of code, we copied a ton of pixels from the source surface (my_image) onto the screen by "blitting".
How do the pygame.draw.* functions blit?
Technically, the pygame.draw.* methods could have been written to do something similar. So, instead of your example...
pygame.draw.circle(screen, COLOR, POS, RADIUS, WIDTH)
...they COULD have had you do this...
circle_surface = pygame.draw.circle(COLOR, RADIUS, WIDTH)
screen.blit(circle_surface, POS)
If this were the case, you would get the same result. Internally, though, the pygame.draw.circle() method directly manipulates the surface you pass to it rather than create a new surface. This might have been chosen as the way to do things because they could have it run faster or with less memory than creating a new surface.
So which do I do?
So, to your question of "when to blit" and "when not to", basically, you need to read the documentation to see what the function actually does.
Here is the pygame.draw.circle() docs:
pygame.draw.circle():
draw a circle around a point
circle(Surface, color, pos, radius, width=0) -> Rect
Draws a circular shape on the Surface. The pos argument is the center of the circle, and radius is the size. The width argument is the thickness to draw the outer edge. If width is zero then the circle will be filled.
Note that it says that "draws a shape on the surface", so it has already done the pixel changes for you. Also, it doesn't return a surface (it returns a Rect, but that just tells you where the pixel changes were done).
Now let's look at the pygame.font.Font.render() documentation:
draw text on a new Surface
render(text, antialias, color, background=None) -> Surface
This creates a new Surface with the specified text rendered on it. Pygame provides no way to directly draw text on an existing Surface: instead you must use Font.render() to create an image (Surface) of the text, then blit this image onto another Surface.
...
As you can see, it specifically says that the text is drawn on a NEW Surface, which is created and returned to you. This surface is NOT your screen's surface (it can't be, you didn't even tell the render() function what your screen's surface is). That's a pretty good indication that you will need to actually blit this surface to the screen.

Blit means 'BL'ock 'I'mage 'T'ranfser
When you are displaying things on the screen you will, in some way, use screen because that's where you are putting it.
When you do:
pygame.draw.circle(screen, (0, 0, 0), (100, 100), 15, 1)
you are still using screen but you are just not blitting because pygame is drawing it for you.
And when you use text, pygame renders it into an image then you have to blit it.
So basically you blit images, but you can also have pygame draw them for you. But remember when you blit an image, say over a background, you need to loop it back and fourth; so that it blits the background, then the image, then the background etc...
You dont need to know much more than that, but you can read all about it here Pygame Blit
I hope this helped. Good Luck!

Imagine that you are a painter:
You have a canvas, and a brush.
Let's say that your main screen surface will be your canvas, and all the other surfaces, are "in your head" - you know how to draw them already.
When you call blit, you paint on top of the surface, covering any pixels that were overlapped. That is why you need to repaint the whole screen black so that you won't have any smudges on the painting while moving an object.
As Mark already said, you can draw a circle with a function, or first blit it to a new surface, and blit that on the screen surface.
If you have a more complicated surface - curves, text etc. you wouldn't need to have a surface for that, so you don't have to do any expensive calculations, just drawing. The setback is that your program takes up more memory, so you have to choose between those 2.

Related

How to properly inherit the Surface class in Pygame

To put OOP in practice, I created my own Window class that inherits from pygame.Surface, and adds functionality. According to the following source, this is what I should do:
class MyWindow(pygame.Surface):
def __init__(self, w, h):
pygame.Surface.__init__(self, size=(w, h))
self.screens: list[Screen] = [] # For example
I tried the following code, and it seems to work fine, up until the point where display.update() is called. This throws a pygame.error.
myWin: MyWindow = MyWindow(200, 200)
print(myWin) # This correctly prints: <Surface(200x200x32 SW)>
pygame.draw.rect(myWin, (255, 255, 255), (90, 90, 20, 20))
pygame.display.update()
pygame.time.delay(1000)
That code doesn't even create an actual window. In contrast, the following code works just fine, instead relying on the display.set_mode() function to initialize the Surface.
pyWin: pygame.Surface = pygame.display.set_mode((200, 200))
pygame.draw.rect(pyWin, (255, 255, 255), (90, 90, 20, 20))
pygame.display.update() # Actually shows the square
pygame.time.delay(1000)
Clearly display.set_mode() does something that Surface.__init__() doesn't.
TL;DR: How can I initialize an object inheriting from Surface, in such a way that it actually shows and updates the window?
Thanks!
TL;DR: How can I initialize an object inheriting from Surface, in such a way that it actually shows and updates the window?
I'd say you can't do it in the way you think, and there is a good reason for not ever wanting to do it.
A couple of things to keep in mind:
A Surface is simply a 2D array of pixels, with convenient methods to read / edit / write the values of those pixels. Write where? To other surfaces. You can have as many surfaces you want in a game, each one storing the image of a different element of the game (your main character, an enemy, an element of the map, etc). You can write the content of a Surface on top of another Surface, to make complex images.
A Surface, by itself, it has no connection with the screen (i.e. with what is shown on the window you see on your PC monitor).
The display is a special Surface, instantiated by pygame.display.set_mode(). It is a Surface like all the other you can create using the Surface class, but that, and only that Surface, represents the display, i.e. what you see on your monitor.
This means that a pygame.Surface instance is never shown on the screen. To show stuffs on the screen, you need to blit the other Surfaces (i.e. copy their content) somewhere on the special display Surface.
Now let's go back to your question. With what I have just explained in mind, you could ask: Then can I write a Surface subclass such that each time the Surface value changes, it is automatically blit on the display and display.update() is called`?
Well, it will be complicated. If you use the function from pygame.draw the Surface is an argument, so you need some good trick to let an argument understanding when it is used.
However, trust me: you don't want to do it. As soon as your game becomes a little more complex, it will be highly inefficient. The reason is that blitting and drawing requires time, so you want to optimize these operations, performing them only when needed. If you have many surfaces in your game, you want to blit them on the display each iteration of your main loop (or each frame if you prefer) to "prepare" the new frame, and call display.update only once.

Is There a Way to Make a Rect Transparent in Pygame?

Is it possible to make a rect transparent in pygame?
I need it because I'm using rects as particles for my game. :P
pygame.draw functions will not draw with alpha. The documentation says:
Most of the arguments accept a color argument that is an RGB triplet. These can also accept an RGBA quadruplet. The alpha value will be written directly into the Surface if it contains pixel alphas, but the draw function will not draw transparently.
What you can do is create a second surface and then blit it to the screen. Blitting will do alpha blending and color keys. Also, you can specify alpha at the surface level (faster and less memory) or at the pixel level (slower but more precise). You can do either:
s = pygame.Surface((1000,750)) # the size of your rect
s.set_alpha(128) # alpha level
s.fill((255,255,255)) # this fills the entire surface
windowSurface.blit(s, (0,0)) # (0,0) are the top-left coordinates
or,
s = pygame.Surface((1000,750), pygame.SRCALPHA) # per-pixel alpha
s.fill((255,255,255,128)) # notice the alpha value in the color
windowSurface.blit(s, (0,0))
Keep in mind in the first case, that anything else you draw to s will get blitted with the alpha value you specify. So if you're using this to draw overlay controls for example, you might be better off using the second alternative.
Also, consider using pygame.HWSURFACE to create the surface hardware-accelerated.
Check the Surface docs at the pygame site, especially the intro.
Draw a transparent rectangle in pygame
I have had this question as a pygame user before, and this is a method of solving your problem.

(pygame) Empty squares displaying copies of what was previously there instead of background

I made a 2D project with a lot of tile sprites, and one player sprite. I'm trying to get the camera to follow the player, and for the most part it's working. However, there's one problem:
If you go to the edge of the map, it scrolls normally, but instead of the black background, it displays copies of the sprites on the edge of the map instead of the background (black). It has the same problem if I leave some squares empty, when I move it displays a copy of the tile that was previously there.
The camera works like this:
Select sprites that should be visible
Do sprite.visible = 1 for them, and sprite.visible = 0 for all other sprites
Set the position sprite.rect of all sprites to coords - offset
Update the screen (I use flip(), because the camera moves every turn, so the whole screen has to be updated every turn)
All DirtySprites have dirty = 2.
Does anyone know why it's displaying copies of the sprites on the edge instead of the background?
Help would be appreciated!
Unless you manually clear your screen surface, flip will not change its content.
Thus, if you neglect to draw to a certain location, it will remain the same.
If you want to get rid of this effect, usually called "hall of mirrors", you will have to keep track of what portions of the screen have not been drawn to yet and draw over these yourself.
It may be easier to define background sprites around your map's contours and block your camera from going off too far.
Since you use a "dirty/clean" approach to only redrawing what's changed, you won't have the option to just fill the whole screen surface before you draw your frame, because that would draw over anything that's stayed the same since the last frame.

Artifacts when drawing primitives with pygame?

I'm working on some code involving use of the pygame library to draw a circle to a surface. The code to draw the circle looks something like the following:
surf = pygame.Surface((2000,2000))
pygame.draw.circle(surf,
pygame.Color("white"),
(1000,1000),
508,
50)
The problem is that the resulting circle has artifacts
Is there anyway to draw a circle like this without getting these artifacts?
What you see is most likely a problem with pygame.draw.circle implementation. Most likely pygame developer foolishly assumed that you can draw thick circle by drawing several circles in sequence, increasing radius by one for every circle. That's not going to work in practice and you'll get moire pattern like the one you see. Try increasing circle line thickness by 100 or 200 and see what happens. If it gets worse, then it is pygame.draw.circle's fault.
A solution would be to provide your own circle rendering routine. This can be certainly be done, but for optimum performance it makes sense to do it in C/C++ extension module for pygame OR using OpenGL (with or without fragment shaders).
To get a perfect circle for every scanline you'll have to calculate start and end of filled area for every scanline. It might be possible to do this in python with tolerable performance by using pygame.draw.line to draw individual scanlines.
This bug is mentioned in the comments for the circle and arc methods. There's one workaround in the comments of the draw.circle documentation. This is adapted from that workaround:
def draw_outlined_circle(surf, color, origin, radius, thickness):
width = radius * 2 + thickness * 2
background = (0, 0, 0, 0)
circle = pygame.Surface((width, width)).convert_alpha()
rect = circle.get_rect()
circle.fill(background)
pygame.draw.circle(circle, color, rect.center, radius)
pygame.draw.circle(circle, background, rect.center, radius - thickness)
surf.blit(circle, (origin[0] - (rect.w / 2), origin[1] - (rect.w / 2)))
This method uses an extra Surface and draws two circles: a smaller circle inside of a larger one to achieve the same effect. The smaller circle's fill color has an alpha of 0, so the full circle's center appears transparent.
EDIT: From the above comment, I see the behavior is mentioned in the pygame FAQ as well.
I fixed this issue, and it will be in the next release of pygame (1.9.4). How do you draw circles like that without artifacts? Use the newer version of pygame.
This might have happened with a problem on how pygame.draw.circle is implementing.
You can try the arcade library for better performance. Also, the arcade library is very easy to use while I find pygame quite complicated.

How do I clear a pygame alpha layer efficiently?

I'm trying to write a 2D game using python / pygame that blits several layers on top of one another every screen refresh. My basic setup is (from bottom to top):
Background: surface (non-transparent), scrolls at a different rate than rest
Midground: SRCALPHA transparent surface (static)
Player / Sprites / Enemies: sprite group
Forground: SRCALPHA transparent surface (static)
Right now, I'm blitting these four layers one on top of another every screen. The background scrolls at a different rate than the other three layers, which is why I have it separate from midground. As I have the game structured now, it runs on my fairly modest laptop at 60fps.
-BUT- I'm having trouble with the sprite group, which I'm blitting directly to the screen. Having to adjust the rect for every sprite according to my current viewport seems like an ugly way to program things, and I'd like a more elegant solution.
I'd love to blit the sprites to another transparent surface which I could manage, but therin lies my problem: I can't find a way of clearing a transparent layer that doesn't half my performance. Some of the setups I've tried:
I've tried filling the layer with a white surface with blend mode rgba_sub (surf.fill((255,255,255,255), area, BLEND_RGBA_SUB)) -- this is super, super slow
I've tried surface.copy() of a blank surface - this is faster, but still halves my fps
I've tried combining the sprites with the midground layer and using pygame.sprite.LayeredUpdates to update the sprites. This has no effect on performance, but does not work where the midground is transparent. I get trails of sprites over the background layer.
The best solution I've found so far is my current setup of drawing sprites directly to the screen. It looks great, runs fast, but is a pain to manage, as I have to make sure each sprites' rect is adjusted according to the viewport every frame. Its also making collision detection difficult.
Is there another quick way to clear a pygame transparent surface? Quick as in, can be done 60+ times a second? Alternately, is there a setup for my layers that would still accomplish the same effect?
I figured out a fast way of clearing a sprites only transparent layer by applying Peter's solution selectively to the layer:
for s in self.level.sprites:
spritelayer.fill((0), s.rect)
This seems to be working fine (erasing everything each frame) and still runs at 60fps.
The Surface.fill() will clear all R, G, B, and A values.
>>> img = pygame.image.load("hasalpha.png")
>>> print img.get_at((300, 300))
(238, 240, 239, 255)
>>> surface.fill(0)
>>> print img.get_at((300, 300))
(0, 0, 0, 0)
It sounds like this will do what you are describing. If you are trying to do something more specific with the alpha values the pygame.surfarray.pixel functions can give you directly editable values. That will be quick, but requires numpy as a dependency.

Categories