#!/usr/bin/python

import pygame
headmap = [ (1,1), (2,1), (3,1),
            (1,2), (2,2), (3,2),
                   (2,3), (3,3) ]
bodymap = [               (3,4),
            (1,5), (2,5), (3,5),
            (1,6), (2,6), (3,6),
                          (3,7) ]
feetmap = [               (3,8),
            (1,9), (2,9), (3,9),
  (0,10), (1,10), (2,10), (3,10) ]

	  
import colorsys
def normalize(color): return map(lambda x: x / 255.0, color)
def reformat(color): return map(lambda x: int(round(x * 255)), color)

def plot(surf, point, color):
	x, y = point
	surf.set_at(point, color)
	for pt in ((x+1,y),(x-1,y),(x,y+1),(x,y-1)):
		try:
			if surf.get_at(pt) == (255, 255, 255, 255):
				surf.set_at(pt, (0,0,0))
		except: pass

def draw_robot(head, body, feet):
	dood = pygame.Surface((7,11))
	dood.fill((255,255,255))
	for bit in xrange(0,8):
		if head & 2**bit:
			x, y = headmap[bit]
			hsv = normalize((head, 50 * (4-x), 270 - (30*y)))
			color = reformat(colorsys.hsv_to_rgb(*hsv))
			plot(dood, (x,y),color)
			plot(dood, (3+abs(3-x),y),color)
		if body & 2**bit:
			x, y = bodymap[bit]
			hsv = normalize((body, 50*(4-x), 270 - (30*(y-3))))
			color = reformat(colorsys.hsv_to_rgb(*hsv))
			plot(dood, (x,y),color)
			plot(dood, (3+abs(3-x),y),color)
		if feet & 2**bit:
			x, y = feetmap[bit]
			hsv = normalize((feet, 50*(4-x), 270 - (30*(y-7))))
			color = reformat(colorsys.hsv_to_rgb(*hsv))
			plot(dood, (x,y),color)
			plot(dood, (3+abs(3-x),y),color)
	return dood

def bigbot(botuple, size=(56,88)):
	dood = draw_robot(*botuple)
	scaled = pygame.transform.scale(dood, size)
	return scaled


def main(head, body, feet):
	pygame.init()
	screen = pygame.display.set_mode((56, 88))
	screen.fill((255,255,255))
	pygame.display.set_caption('Pixel Robots')
	print "Robot Code: 0x%02x%02x%02x" % (head, body, feet)

	clock = pygame.time.Clock()
	botuple = (head, body, feet)
	bot = bigbot(botuple)
	screen.blit(bot, bot.get_rect())
	while 1:
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				pygame.quit()
				return
			elif event.type == pygame.MOUSEBUTTONDOWN:
				botuple = tuple(reformat((random(), random(), random())))
				print "Robot Code: 0x%02x%02x%02x" % botuple
				bot = bigbot(botuple)
				screen.blit(bot, bot.get_rect())
		clock.tick(3)
		pygame.display.update()

if __name__ == '__main__': 
	from sys import argv
	from random import random
	if len(argv) > 2:
		main(*map(int,argv[1:4]))
	elif len(argv) == 2:
		num=argv[1]
		main(int(num[2:4],16), int(num[4:6],16), int(num[6:8],16))
	else:
		main(*reformat((random(), random(), random())))
