from tidal import *
from app import App, ButtonOnlyWindow
import random

class Gol(App):
    def on_activate(self):
        super().on_activate()
        display.fill(BLACK)
        self.reset_board()
        self.periodic(50, self.iterate)
    
    def reset_board(self):
        self.color = color565(random.randint(0,255), random.randint(0,255), random.randint(0,255))
        self.boards = [[[0 if random.random() < 0.5 else 1 for i in range(24)] for i in range(13)]]
        self.repeat_count = 0
        if hasattr(self, "reset_timer"):
            self.reset_timer.cancel()
        self.reset_timer = self.after(120000, self.reset_board)


    def iterate(self):
        for ri, row in enumerate(self.boards[-1]):
            for ci, col in enumerate(row):
                display.fill_rect(ri*10, ci*10, 10, 10, self.color if col else BLACK)
                
        self.boards.append([ [0 for i in range(24)] for i in range(13)])
        for cx in range(13):
            for cy in range(24):
                cl = (cx - 1) % 13
                cr = (cx + 1) % 13
                cu = (cy - 1) % 24
                cd = (cy + 1) % 24
                nn = 0
                if self.boards[-2][cl][cu]:
                    nn += 1
                if self.boards[-2][cx][cu]:
                    nn += 1
                if self.boards[-2][cr][cu]:
                    nn += 1
                if self.boards[-2][cl][cy]:
                    nn += 1
                if self.boards[-2][cr][cy]:
                    nn += 1
                if self.boards[-2][cl][cd]:
                    nn += 1
                if self.boards[-2][cx][cd]:
                    nn += 1
                if self.boards[-2][cr][cd]:
                    nn += 1
                
                if self.boards[-2][cx][cy] == 1 and (nn == 2 or nn == 3):
                    self.boards[-1][cx][cy] = 1
                elif self.boards[-2][cx][cy] == 0 and nn == 3:
                    self.boards[-1][cx][cy] = 1

        if len(self.boards) > 4:
            self.boards.pop(0)
            
        for board in self.boards[:-1]:
            if board == self.boards[-1]:
                self.repeat_count += 1
                if self.repeat_count > 10:
                    self.reset_board()

        
main = Gol