-1

So, I'm randomly generating a "world" and drawing it with pygame. That part worked perfectly fine until I decided to add something above what I already drew.

The code is as follows. What each thing is is of no consequence, but DISPLAY is the surface I'm working on, y.colour is a size 3 Tuple, y.coord is a (x,y) Tuple

for x in W_Map:
    for y in x:
        DISPLAY.fill(y.colour, pygame.Rect(y.coord[0]-tile_size, 
                                           y.coord[1]-tile_size, 
                                           y.coord[0]+tile_size, 
                                           y.coord[1]+tile_size))  

DISPLAY.fill(lime, pygame.Rect(300,300,310,310))

According to the game above, this should create a lime coloured 10x10 square centered on 305x305. The result, however, is the following picture:

This is the result

As you can see, the first part of the code draws the terrain perfectly, but when creating the lime square on top of what's already drawn, it goes completely crazy. The whole function is:

pygame.init()
DISPLAY = pygame.display.set_mode(
    (shape[0]*2*tile_size, shape[1]*2*tile_size))
DISPLAY.fill((0,0,0))
#Make and draw the Rects
for x in W_Map:
    for y in x:
        DISPLAY.fill(y.colour, pygame.Rect(y.coord[0]-tile_size, 
                                           y.coord[1]-tile_size, 
                                           y.coord[0]+tile_size, 
                                           y.coord[1]+tile_size))  

DISPLAY.fill(lime, pygame.Rect(300,300,310,310))
André Rocha
  • 123
  • 7
  • Note the code `DISPLAY.fill(y.colour, pygame.Rect(...))` woks, because the later rectangle cover the area which was superfluously drawn by the former rectangles. It has to be `pygame.Rect(y.coord[0]-tile_size,y.coord[1]-tile_size,tile_size*2,tile_size*2)` – Rabbid76 Jun 13 '19 at 20:23

1 Answers1

2

Pygame's Rect takes four arguments: x, y, width, and height, where x and y are relative to the top left of the viewport. Your lime rectangle is created with pygame.Rect(300,300,310,310), meaning a width and height of 310 pixels and a location of (300, 300).

To create a 10x10 rectangle centered at (305, 305) you'll need to use pygame.Rect(300, 300, 10, 10). You can also create a helper function to translate size and center point to the necessary rectangle parameters:

def center_rect(x, y, width, height):
    return pygame.Rect(x - width / 2, y - height / 2, width, height)

Then you could use this helper function like so:

DISPLAY.fill(lime, center_rect(305, 305, 10, 10))
FThompson
  • 28,352
  • 13
  • 60
  • 93
  • Thanks. It seems that the first part was only working because the squares were drawn in order and were overlapping eachother nicely – André Rocha Jun 13 '19 at 20:23