Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Brain_Cellular_Automaton.py
- from tkinter import *
- from PIL import Image, ImageTk
- import time
- import random
- import math
- grid_size = (140, 69) # Sets the size of the grid
- cell_size = 9 # Sets the drawn size of each cell
- frame_rate = 30
- max_cells = grid_size[0]*grid_size[1]-50
- root = Tk()
- root.title("Brain Cellular Automaton")
- canvas = Canvas(root,width=grid_size[0]*cell_size,height=grid_size[1]*cell_size)
- text = Text(root)
- canvas.pack()
- default_font = ("Arial 20")
- color_239_62_62 = f"#%02x%02x%02x" % (239,62,62)
- def randomise(cells):
- for i in range(grid_size[0]):
- for j in range(grid_size[1]):
- cells[i][j] = random.randrange(0,3)
- return cells
- def initialise():
- canvas.configure(bg='black')
- cells = [[0 for y in range(grid_size[1])] for x in range(grid_size[0])]
- cells = randomise(cells)
- return cells
- def next_gen(crowd, cells):
- crowd = 0
- feed = [1]*50+[0]*max_cells
- random.shuffle(feed)
- new = [[0 for y in range(grid_size[1])] for x in range(grid_size[0])]
- for i in range(grid_size[0]):
- for j in range(grid_size[1]):
- if cells[i][j] == 0:
- alive = 0
- for k in range(-1,2):
- for l in range(-1,2):
- if cells[(i+k) % grid_size[0]][(j+l)% grid_size[1]] == 1:
- alive += 1
- if alive == 2:
- new[i][j] = 1
- elif cells[i][j] == 1:
- new[i][j] = 2
- elif cells[i][j] == 2:
- crowd += 1
- if feed.pop():
- new[i][j] = 1
- else:
- new[i][j] = 0
- return crowd, new
- def update_cells(new, cells):
- for i in range(grid_size[0]):
- for j in range(grid_size[1]):
- t = new[i][j]
- cells[i][j] = new[i][j]
- return cells
- def draw(generation, start_time, cells, crowd):
- canvas.delete('all')
- for i in range(grid_size[0]):
- for j in range(grid_size[1]):
- if cells[i][j] == 1:
- canvas.create_rectangle((i*cell_size,j*cell_size,i*cell_size+cell_size,j*cell_size+cell_size), fill=('white'))
- elif cells[i][j] == 2:
- canvas.create_rectangle((i*cell_size,j*cell_size,i*cell_size+cell_size,j*cell_size+cell_size), fill=(color_239_62_62))
- mGensPerSec = round(generation/round(time.time() - start_time,2),2)
- canvas.create_text((500,60), text=f"Generation: {generation} Cells: {crowd} mGensPerSec: {mGensPerSec}", font=default_font, fill=(f"#ffffff"))
- canvas.update()
- def game_loop(cells):
- crowd = 0
- start_time = time.time()
- time.sleep(0.01)
- generation = 0
- while True:
- generation += 1
- crowd, new = next_gen(crowd, cells)
- cells = update_cells(new, cells)
- draw(generation, start_time, cells, crowd)
- def main():
- cells = initialise()
- game_loop(cells)
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement