#!/usr/bin/env python

import pygame
import numpy as np

pygame.init()

ANCHO,ALTO = 640,480
LADO = 40

NEGRO = 0,0,0
BLANCO = 254,254,254

ventana = pygame.display.set_mode([ANCHO, ALTO])
ventana.fill(BLANCO)


class Tablero:
  def __init__(self,):
    self.matriz = np.zeros([ANCHO/LADO, ALTO/LADO])
  def agregar(self, x, y):
    x = (x/LADO)
    y = (y/LADO)
    self.matriz[x,y] = 1
    # aun me falta el quitar
  def dibujar(self):
    for x in range(ANCHO/LADO):
      for y in range(ALTO/LADO):
        if self.matriz[x,y] == 1:
          cuadrado = pygame.Rect(x*LADO, y*LADO, LADO, LADO)
          pygame.draw.rect(ventana, NEGRO, cuadrado)
        else:
          cuadrado = pygame.Rect(x*LADO, y*LADO, LADO, LADO)
          pygame.draw.rect(ventana, BLANCO, cuadrado)

  def evolucionar(self):
    for x in range(ANCHO/LADO):
      for y in range(ALTO/LADO):
        vecinos = 0
        if x > 0 and self.matriz[x-1,y] == 1:
          vecinos = vecinos + 1
        if x < ANCHO/LADO-1 and self.matriz[x+1,y] == 1:
          vecinos = vecinos + 1
        if y > 0 and self.matriz[x,y-1] == 1:
          vecinos = vecinos + 1
        if y < ALTO/LADO-1 and self.matriz[x,y+1] == 1:
          vecinos = vecinos + 1
        if vecinos in [2,3]:
          self.matriz[x,y] = 1
        else:
          self.matriz[x,y] = 0
          
          
vida = Tablero()
continuar = True
while continuar:
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      continuar = False
    if event.type == pygame.MOUSEBUTTONUP:
      x,y = pygame.mouse.get_pos()
      vida.agregar(x,y)
    if event.type == pygame.KEYDOWN:
      if event.key == pygame.K_SPACE:
        vida.evolucionar()
      
  vida.dibujar()
  pygame.display.flip()
