Home > Enterprise >  placing images on a pygame grid
placing images on a pygame grid

Time:05-25

The red and blue sides would each have their tiles replaced by an image (not one image overlapping them all, but one image pasted onto each tile). I'm not really sure how to go about it, and any help would be appreciated!

enter image description here

import pygame

TILESIZE = 22
margin = 1
BOARD_POS = (10, 10)


def create_board_surf():
    board_surf = pygame.Surface((TILESIZE * 50   margin * 51, TILESIZE * 26   margin * 27))
    board_surf.set_colorkey((0, 0, 0))
    board_surf.set_alpha(210)
    for row in range(26):
        for column in range(0, 25):
            color = (170, 70, 70)
            rect = pygame.draw.rect(screen, color, [(margin   TILESIZE) * column   margin, (margin   TILESIZE) * row   margin, TILESIZE, TILESIZE])
            pygame.draw.rect(board_surf, pygame.Color(color), rect)
        for column in range(25, 50):
            color = (70, 95, 195)
            rect = pygame.draw.rect(screen, color, [(margin   TILESIZE) * column   margin, (margin   TILESIZE) * row   margin, TILESIZE, TILESIZE])
            pygame.draw.rect(board_surf, pygame.Color(color), rect)
    return board_surf


def create_board():
    board = []
    for row in range(26):
        board.append([])
        for column in range(50):
            board[row].append(None)
    return board


def main():
    global screen
    pygame.init()
    screen = pygame.display.set_mode((1200, 650))
    clock = pygame.time.Clock()

    while True:
        events = pygame.event.get()
        for e in events:
            if e.type == pygame.QUIT:
                return

        create_board()
        board_surf = create_board_surf()
        screen.fill(pygame.Color((200, 200, 200)))
        screen.blit(board_surf, BOARD_POS)
        pygame.display.flip()
        clock.tick(60)


main()

CodePudding user response:

Under def create_board_surf(): where you draw rectangles for each tile, replace the pygame.draw.rect with board_surf.blit(IMAGE_SURFACE, ((margin TILESIZE) * column margin, (margin TILESIZE) * row margin)) to put an image where the tile rectangle would of been.

You can make the IMAGE_SURFACE by img = pygame.image.load("IMAGENAME.png") These images would have to be scaled to the tile size so they fit properly: img = pygame.transform.scale(img, (TILESIZE, TILESIZE))

If some tiles should have different images, you could maybe use the column and row location to determine which image to use, the same way some tiles are red while others are blue based on their column.

  • Related