Python Forum
[PyGame] Surface and rectangle in pygame
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] Surface and rectangle in pygame
#1
Hello eveyone,

Just a stupid question:
in many tutorials found on internet to draw object on the window we use surfaces and rectangles.
first we create a surface, then with the method getrect we create a rectangle around that surface,
but when i have to move the object we move only the rectangle, what it means?
We move only the rectangle, and the surface? Remain in the original position?
There is a way to combine thi two object and move them with a command?
But first of all why we create a surfaces for a rectangles? we cant' t create a big surface with the dimension of the window and on this big surface create rectangles?

Are a lot of question, but i don' t andurstand this surface - rectangle system

sorry for the bad english Big Grin
Reply
#2
I don't understand very well the question, but if you want to draw a rectangle on the screen you can just use this simple program
import pygame as py
screen: py.Surface = py.display.set_mode((700, 700))
running = True
color = (195, 195, 195)
py.draw.rect(screen, (color), (30, 20, 100, 200)) # draw a rect on the screen at the coordinate (30, 20) with a width of #100 and a height of 200
while running:
    for event in py.event.get():
        if event.type == py.QUIT: # allow to leave the loop
            running = False
            break
    py.display.flip()
but I think that the tutorial you saw said to do a thing like this:
import pygame as py
rectangle = py.Surface((100, 200))
color = (195, 195, 195)
rectangle.fill(color)
screen = py.display.set_mode((700, 700))
screen.blit(rectangle, (30, 20))
while running:
    for event in py.event.get():
        if event.type == py.QUIT: # allow to leave the loop
            running = False
            break
    py.display.flip()
And I think you tutorial said you to do that because I think it's less expansive to blit a surface onto another than use py.draw.rect (but i am not sure)
Reply
#3
I think you want a Sprite.

A sprite has a surface (called image) and a rectangle (called rect). It also has a method "draw()" that draws the sprite. If your sprite class does not have a draw() method, the default draw() method draws the surface at the location of the rectangle.
"""Demonstrate how sprites work."""
import pygame

class MySprite(pygame.sprite.Sprite):
    """You create sprite classes for things on your screen that move or change."""
    def __init__(self, pos=(0, 0)):
        super().__init__()
        self.target = (150, 150)
        # Sprites must have an image and a rect.  When the sprite's draw()
        # method is called, the image is drawn at the rectangle's location.
        self.image = pygame.surface.Surface((20, 20))
        self.image.fill("red")
        self.rect = self.image.get_rect()
        self.rect.x, self.rect.y = pos

    def update(self):
        """Sprites can have an update() method that is called by the
        group the sprite belongs to.  When the update method is called,
        the sprite should update the image and/or rect to prepare for
        the draw() method."""
        dx = max(-1, min(1, self.target[0] - self.rect.x))
        dy = max(-1, min(1, self.target[1] - self.rect.y))
        if dx == 0 and dy == 0:
            self.kill()
        else:
            self.rect.x += dx
            self.rect.y += dy


def main():
    screen = pygame.display.set_mode((300, 300))
    sprites = pygame.sprite.Group()
    clock = pygame.time.Clock()
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                break
            elif event.type == pygame.MOUSEBUTTONDOWN:
                for sprite in sprites.sprites():
                    sprite.target = event.pos
                sprites.add(MySprite(event.pos))

        screen.fill("blue")
        sprites.update()  # Update all sprite positions
        sprites.draw(screen)  # Draw the sprites
        pygame.display.flip()
        clock.tick(60)


main()
Reply
#4
I have a question, why did you use property for target, if you rename self._target to self.target and delete the 2 property that would achieve the same?
Reply
#5
An artifact ftom a different example. I didn't notice I removed all the setter code. I modified the post to not use a property.
Reply
#6
(May-14-2023, 01:53 PM)Fabrizio_fg Wrote: but when i have to move the object we move only the rectangle, what it means?
We move only the rectangle, and the surface? Remain in the original position?
There is a way to combine thi two object and move them with a command?
But first of all why we create a surfaces for a rectangles? we cant' t create a big surface with the dimension of the window and on this big surface create rectangles?
Rectangle is use to position the surface. It just uses the x and y.
Rectangle is also use for collisions.
Surface can be use over and over again. Just set a new position.
Why cant you have big surface ? You can a bigger surface than the screen.

Tip. Take it one step at a time. Add one line of code. Run it. To see how it effect program.
99 percent of computer problems exists between chair and keyboard.
Reply
#7
Thanks for the answers, i couldn't quite understand the connection between surfaces and rectangles but now it's clearer.
Reply
#8
Hey! Great questions — definitely not stupid at all 🙂 A lot of people get confused by surfaces and rectangles in Pygame at first. Let's break it down in simple words:

In Pygame, a Surface is basically an image — it could be a picture, some text, or even just a colored square. Think of it like a sticker. When you create a Surface, you're making that sticker. But just creating a sticker isn't enough — you need to know where to put it on the screen. That’s where Rect (short for rectangle) comes in. A Rect doesn’t hold the image — it just holds the position and size info, like where the top-left corner is and how big it is.

Now, when you say you move the rectangle, you're right — you’re only changing its x and y position. But here's the cool part: when you draw (blit) the surface onto the screen, you tell it to use the rectangle’s position. So even though the image doesn’t move by itself, it gets drawn in the new position because the rectangle says where to put it.

You also asked if we can "combine" the surface and the rectangle. Technically, they’re not glued together, but we often do something like this:

surface = pygame.Surface((50, 50))
rect = surface.get_rect()
Then when we want to move it, we just change rect.x or rect.y. And every time we draw it on the screen, we say:

screen.blit(surface, rect)
So as long as you update the rect’s position, the image (surface) will look like it moved — because you're drawing it in the new place.

About your last question — yes, you can totally create one big surface the size of the screen and draw everything on that. That’s kind of what the main screen surface already is! But using smaller surfaces and rects is better when you want to move or change specific things (like characters, buttons, etc.), because it's easier to control and more efficient.

Hope that makes more sense now! And don’t worry — your English is just fine 👍 Let me know if you want a little example code too!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [PyGame] Pygame is treating blob_group as a surface, when I need it to treat it as a Sprite. Swagford 1 2,341 Jan-24-2023, 09:58 PM
Last Post: metulburr
  Coloring a surface with transparency Sandor 4 3,386 Jan-02-2022, 08:11 AM
Last Post: Sandor
  Rotating a rectangle CompleteNewb 19 20,904 Aug-28-2021, 03:23 PM
Last Post: CompleteNewb
  Make rectangle snap to other rectangle corners Pedroski55 2 5,392 Aug-13-2021, 09:59 PM
Last Post: Pedroski55
  Drawn line shift when that surface is copied to another in pygame Leo_Red 4 4,496 Feb-11-2021, 06:33 AM
Last Post: Leo_Red
  [PyGame] pygame.Surface.fill help Shemira 3 7,713 Nov-29-2019, 12:01 AM
Last Post: Shemira
  pygame.surface Graham 10 11,107 Nov-29-2018, 04:45 PM
Last Post: nilamo
  [PyGame] Rectangle keeps teleporting? keyfive 1 4,063 Jun-27-2018, 11:49 PM
Last Post: sonnekrieger7
  [PyGame] PLEASE HELP! TypeError: unsupported operand type(s) for +: 'pygame.Surface' and 'int' keyfive 1 6,393 Jun-19-2018, 01:20 PM
Last Post: volcano63

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020