Image loading using pygame

本秂侑毒 提交于 2021-02-04 08:19:12

问题


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:


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()


来源:https://stackoverflow.com/questions/60617748/image-loading-using-pygame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!