Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Game of Life in python.
- Handles worlds as 2x2 lists.
- Starts with a 128x64 randomly generated world.
- """
- from random import random
- from time import sleep
- # Returns the next iteration of a given world.
- def next_world(world):
- # Returns a cell's next value given
- # its state and its surroundings.
- def next_cell(surr, cell):
- return (surr == 3 or (cell and surr == 2))
- height = len(world)
- width = len(world[0])
- new_world = [[0]*width for i in range(height)]
- for m in range(height):
- for n in range(width):
- # p_m, etc. are defined for wraparound purposes.
- p_m = (m-1) % height
- n_m = (m+1) % height
- p_n = (n-1) % width
- n_n = (n+1) % width # ^_^
- # print('m,n', m, n)
- # print('p_m', p_m)
- # print('n_m', n_m)
- # print('p_n', p_n)
- # print('n_n', n_n)
- surr = (world[p_m][p_n]
- +world[p_m][n]
- +world[p_m][n_n]
- +world[m][p_n]
- +world[m][n_n]
- +world[n_m][p_n]
- +world[n_m][n]
- +world[n_m][n_n]
- )
- cell = world[m][n]
- new_world[m][n] = next_cell(surr, cell)
- return new_world
- # Outputs a given world to the console.
- def out(world):
- height = len(world)
- width = len(world[0])
- new_world = ' ' + '-'*width
- for i in range(height):
- # Convert each boolean in the row to a character.
- str_row = ('\n|'
- +''.join([('\u2588' if val else ' ') for val in world[i]])
- +'|'
- )
- new_world += str_row
- new_world += '\n ' + '-'*width
- print(new_world)
- # sleep(amount)
- def worldgen(height,width):
- world = [[0]*width for i in range(height)]
- for m in range(height):
- for n in range(width):
- world[m][n] = random() < 0.5
- return world
- # world = [[False]*9
- # ,[False]*4 + [True] + [False]*4
- # ,[False]*4 + [True] + [False]*4
- # ,[False]*4 + [True] + [False]*4
- # ,[False]*9]
- world = worldgen(64,128)
- out(world)
- while(True):
- world = next_world(world)
- out(world)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement