import seagull as sg, matplotlib.pyplot as plt, random, numpy as np, pandas as pd
import seagull.lifeforms as lf
from seagull.lifeforms import Pulsar
plt.rcParams["animation.html"] = "jshtml"

# Initialize board
blen = 1000

# One pixel "lifeform"
pix = lf.Custom([[1]])

# Get random binary
def rand2bin(R):
    r = random.uniform(0, 1)
    if (R >= r):
        return 1
    if (R < r):
        return 0

# Initialize random board with given density
def randboard(randdens):
    board = sg.Board(size=(blen,blen))
    for i in range(blen):
        for j in range(blen):
            r = rand2bin(randdens)
            if (r == 1):
                board.add(pix, loc=(i,j))
    return board

# Get average of next (1rst) run
def avg1run(b, iteration):
    sim = sg.Simulator(b)
    stats = sim.run(sg.rules.conway_classic, iters=iteration)
    hist = sim.get_history()
    testmat = 1*np.matrix(hist[iteration])
    return np.mean(testmat)

# Get average of next (1rst) run
def avg1runvec(b, iteration):
    sim = sg.Simulator(b)
    stats = sim.run(sg.rules.conway_classic, iters=iteration)
    hist = sim.get_history()
    resvec = []
    for i in range(iteration):
        testmat = 1*np.matrix(hist[i])
        testmat = np.mean(testmat)
        resvec.append(testmat)
    return resvec

resmat = []
for x in range(100):
    print(x)
    y = x / 100
    resmat.append(avg1runvec(randboard(y), 1000))

plt.matshow(resmat1[:, 10:])
plt.title('Game of Life: Random density development after 10th run')
plt.xlabel('Run')
plt.ylabel('Initial density in %')

pd.DataFrame(resmat).to_csv("resmat.csv")

plt.plot(resmat[70][1:])
plt.title('Game of Life: Density Development with initially 0.7')
plt.xlabel('Run')
plt.ylabel('Current density')

resmat1 = np.array(resmat)

plt.plot(resmat1[:,999])
plt.title('Game of Life: Density Development')
plt.xlabel('Initial random density')
plt.ylabel('Density after 1000 runs')
