How To Create A Checkered Background Using Pygame Surfarrays?

Viewed 39
    # Numpy as N
    self.checkered = N.zeros((550, 550, 3))
    # Variables Used In Array Slice
    left = 0
    right = 50
    bottom = 0
    top = 50

    for num in range(100): 
        if top < 600:
            self.check[left:right, bottom:top] = (255, 255, 255)
            top += 100
            bottom += 100
        else:
            left += 50
            right += 50
            if right % 100 == 0:
                top = 100
                bottom = 50
            else:
                top = 50
                bottom = 0
    self.surface = pygame.surfarray.make_surface(self.checkered)

Here's my solution. I feel that I may have missed a much more effective method. I also think I might have completely missed the point of array slicing by using a for loop. I had trouble understanding the pygame surfarray intro tutorial.

1 Answers

You can use numpy.fromfunction to create an checkered array:

import pygame
import numpy as np

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

w, h, ts = *window.get_size(), 50
c = np.fromfunction(lambda x, y: (x//ts + y//ts) % 2, (w, h))
checkered = np.full((w, h, 3), (128, 128, 128))
checkered[c == 1] = (64, 64, 64)
background = pygame.surfarray.make_surface(checkered)

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

    window.blit(background, (0, 0))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
exit()

However, I suggest simply using pygame.draw.rect. Create a pygame.Surface object and fill it completely with rectangles:

import pygame

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *background.get_size(), (128, 128, 128), (64, 64, 64)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
[pygame.draw.rect(background, color, rect) for rect, color in tiles]

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

    window.blit(background, (0, 0))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
exit()

Related