1

This is the code for my background grid

Background = pygame.display.set_mode((900 ,900))
Green = (45,198,14)
Background.fill(Green)

for i in range(0, 900, 50):
    pygame.draw.line(Background, (0, 0, 0), (0, i), (900, i))
    pygame.draw.line(Background, (0, 0, 0), (i, 0), (i, 900))
pygame.display.update()

while pygame.event.wait().type != pygame.QUIT:
    pass

I can not get any images to load onto it would i have to convert this into n image and then a sprite or is there a way for me to load images onto the grid. I have tried to use the blit function but it wont put images onto the grid.

RedInfantry= pygame.image.load("H:\computer science\6.2\Coursework\Week\Red team\InfantryRedV20.gif").convert()


while True:
    Background.blit(RedInfantry,(0,0))

If i turn the images into a sprite would it allow me to move and remove images on the grid? Would i have to create the grid into the image to blit other images onto it.

The infantry image that i would like to use

1 Answers1

1

Crate a grid of:

grid = [[None for i in range(0, 900, 50)] for j in range(0, 900, 50)]

Assign the images to the field in the grid. e.g:

grid[3][2] = RedInfantry

Draw the images in the grid in the application loop:

for i in range(len(grid)):
    for j in range(len(grid[i])):
        x, y = i * 50, j * 50
        image = grid[i][j]
        if image != None:
            Background.blit(RedInfantry,(x, y))

Furthermore I recommend to draw the entire scene continuously in the main application loop:

import pygame 
pygame.init()

Background = pygame.display.set_mode((900 ,900))
Green = (45,198,14)

RedInfantry = pygame.Surface((50, 50))
RedInfantry.fill((255, 0, 0))

grid = [[None for i in range(0, 900, 50)] for j in range(0, 900, 50)]
grid[3][2] = RedInfantry

run = True
while run:
    # handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    # draw background
    Background.fill(Green)

    # draw scene
    for i in range(0, 900, 50):
        pygame.draw.line(Background, (0, 0, 0), (0, i), (900, i))
        pygame.draw.line(Background, (0, 0, 0), (i, 0), (i, 900))
    for i in range(len(grid)):
        for j in range(len(grid[i])):
            x, y = i * 50, j * 50
            image = grid[i][j]
            if image != None:
                Background.blit(image,(x, y))

    # update dispaly
    pygame.display.update()
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • I can not convert the red square into an image even though i am using the command pygame.image.load("H:\computer science\6.2\Coursework\Week\Red team\InfantryRedV20.gif") which should of replaced the red square with the image – AdverntureWare Mar 13 '20 at 12:07