An exercise described here.

import pygame
import os
import random

os.environ['SDL_VIDEO_CENTERED'] = '1'
 
pygame.init()

X = 100
Y = 100

mysurf = pygame.Surface((X, Y), depth=32)
running = True
mysurf.fill((0, 0, 0))

for y in range(Y):
    for x in range(X):
        mysurf.set_at((x, y), random.choice([(255, 0, 0), (0, 0, 255)]))

try:

    screen = pygame.display.set_mode((X, Y))
    pygame.display.flip()
 
    while running:
        for evt in pygame.event.get():
            if evt.type == pygame.QUIT:
                running = False
                break

        x, y = random.choice(range(X)), random.choice(range(Y))
        dx, dy = random.choice([(1, -1), (1,  0), (1,  1), (0,  1),
                                (-1, -1), (-1,  0), (-1,  1), (0,  -1) ])
        nx, ny = (x + X + dx) % X, (y + Y + dy) % Y
        mysurf.set_at((x, y), mysurf.get_at((nx, ny)))
       
        screen.blit(mysurf, (0, 0))
        pygame.display.flip()
finally:
    pygame.quit()  
About these ads