ソース
ちょうてきとう。
# -*- coding: utf-8 -*- import sys import pygame from pygame.locals import * FPS = 30 width, height = 800, 600 BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) pygame.init() screen = pygame.display.set_mode((width, height)) clock = pygame.time.Clock() R = (4, 4) W, H = R swidth = width / W sheight = height / H sBLACK = 0 sWHITE = 1 state = [[0 for _ in range(sheight)] for _ in range(swidth)] class Ant: def __init__(self, x, y, direction=(0, -1)): self.pos = (x, y) self.direction = direction ant = Ant(swidth/2, sheight/2) while 1: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() for i in range(100): drawpos = map(lambda x: x[0]*x[1], zip(ant.pos, R)) pygame.draw.rect(screen, RED, Rect(drawpos, R)) cx, cy = ant.pos dx, dy = ant.direction if sBLACK == state[cx][cy]: state[cx][cy] = sWHITE ant.direction = (dy, -dx) color = RED elif sWHITE == state[cx][cy]: state[cx][cy] = sBLACK ant.direction = (-dy, dx) color = BLACK drawpos = map(lambda x: x[0]*x[1], zip(ant.pos, R)) pygame.draw.rect(screen, color, Rect(drawpos, R)) ant.pos = map(sum, zip(ant.pos, ant.direction)) nx, ny = ant.pos if nx < 0: ant.pos = (swidth-1, ny) elif nx >= swidth: ant.pos = (0, ny) if ny < 0: ant.pos = (nx, sheight-1) elif ny >= sheight: ant.pos = (nx, 0) drawpos = map(lambda x: x[0]*x[1], zip(ant.pos, R)) pygame.draw.rect(screen, WHITE, Rect(drawpos, R)) pygame.display.flip() clock.tick(FPS)
答え合わせ
こちらのほうがはるかに簡潔。
Langton's ant - Rosetta Code