#!/usr/bin/python # -*- coding: utf-8 -*- """Wang tile paint program. This fills the screen with a random array of Wang tiles and invites you to paint on them. """ from random import randrange as rand import pygame from pygame import display, image, mixer, event, draw tile_size = 64 def decompose(pos): x, y = pos return x // tile_size, y // tile_size, x % tile_size, y % tile_size def draw_line(s, start, end, color, tiles): ww, hh = s.get_size() stx, sty, sx, sy = decompose(start) etx, ety, ex, ey = decompose(end) # XXX this needs to be revamped to break the line into a part for # each tile that it crosses ex += tile_size * (etx - stx) ey += tile_size * (ety - sty) d = 8 surface = pygame.Surface((8, 8), pygame.SRCALPHA) draw.ellipse(surface, color, surface.get_rect()) for yo, tile_row in zip(range(0, hh, tile_size), tiles): for xo, tile in zip(range(0, ww, tile_size), tile_row): if tile == tiles[sty][stx]: s.blit(surface, (xo+ex-d/2, yo+ey-d/2)) #draw.ellipse(s, color, (xo+ex-4, yo+ey-4, 8, 8)) #draw.line(s, color, (xo+sx, yo+sy), (xo+ex, yo+ey), 2) def main(): s = display.set_mode((0, 0)) ww, hh = s.get_size() # Wang tiles have a “color” on each of their four sides, and the # color must be the same for adjacent sides. So here we choose # the colors for the sides at random and use that to determine # each tile. ncolors = 2 # Colors of vertical edges. vcolors = [[rand(ncolors) for x in range(0, ww+tile_size, tile_size)] for y in range(0, hh+tile_size, tile_size)] # Colors of horizontal edges. hcolors = [[rand(ncolors) for x in range(0, ww+tile_size, tile_size)] for y in range(0, hh+tile_size, tile_size)] tiles = [[(vcolors[i][j], vcolors[i+1][j], hcolors[i][j], hcolors[i][j+1]) for j in range(len(vcolors[0])-1)] for i in range(len(vcolors)-1)] #print tiles draw_pos = None alpha = 32 color = pygame.Color(64, 64, 192, alpha) while True: ev = event.poll() if ev.type == pygame.QUIT: break elif ev.type == pygame.MOUSEBUTTONDOWN: draw_pos = ev.pos elif ev.type == pygame.MOUSEMOTION: if draw_pos: draw_line(s, draw_pos, ev.pos, color, tiles) draw_pos = ev.pos elif ev.type == pygame.MOUSEBUTTONUP: draw_pos = None elif ev.type == pygame.KEYDOWN: if ev.unicode in 'cC': color = pygame.Color(rand(256), rand(256), rand(256), alpha) elif ev.unicode in 'dD': s.fill(0) elif ev.unicode in '\033': break display.flip() if __name__ == '__main__': main()