문제

I thought you guys might be able to help me wrap my head around this. I want to be able to generate rects and assign images to those rects. I've been doing this for the whole project and isn't too hard. The hard part here is that I want this particular function to be able to generate as many different rects as I want. The project is a game that takes place on like a chess board. I figure I can write like... if statements for every single space and then have like a bazillion parameters in the function that dictate which rects get generated and where, but I was hoping someone might be able to think of a more elegant solution.

도움이 되었습니까?

해결책

You could use two nested "for" loops --

def make_chessboard(upper_x=0, upper_y=0, size=30):
    chessboard = []

    for y in range(8):
        row = []
        for x in range(8):
            coords = (upper_x + x * size, upper_y + y * size)
            row.append(pygame.Rect(coords, (size, size)))
        chessboard.append(row)
    return chessboard

Then, to get the rect that's in the top-left corner, you could do chessboard[0][0]. To get the rect that's in the top-right corner, you could do chessboard[0][7].

You wouldn't be able to explicitly name each rect, but then again, you really wouldn't need to.

Note: I'm assuming that you wanted to create a chessboard-like pattern of rects of some kind. I can edit my question if you detail specifically what you're trying to do.

다른 팁

class ChessTile(pygame.sprite.Sprite):

    def __init__(self, image, location):
        pygame.sprite.Sprite.__init__(self)

        self.image = image.convert()
        self.mask = pygame.mask.from_surface(self.image)
        self.rect = pygame.Rect(location, self.image.get_size())

Then make another method called like "MakeBoard". Call MakeBoad and have a loop setup with the size of the board. so the pseudo code would be:

(let's assume "img" is a 32x32 white or black square)

for y in range(0,7):
    for x in range(0,7):
        # alternate the tile image from black/white before calling ChessTile with it
        # the location parameter is going to be x*32,y*32.. something like that
        # so you'd have a tile at (0,0) then at (32,0), then (64,0), etc...
        # after the first "j" run is done, "i" increments so now we have
        # (0, 32), (32, 32), etc etc.
        # 
        tile = ChessTile(img, (x,y))

then just draw the tile object as you normall would in some render method!

hope that helps!!!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top