Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Needed for sleep.
- import time
- width = 30
- height = 20
- on = 1
- off = 0
- max_steps = 100
- # Get cell at x y on a w h board.
- # Wrap coordinates so that -1 maps to 19 on the other side of 20 board.
- def wrap_get_cell(x, y, w, h, b):
- if x<0:
- x = x + w
- if y<0:
- y = y + h
- x = x % w
- y = y % h
- return b[y][x]
- def calculate_new_cell_at(x, y, w, h, board):
- count_neighbors = wrap_get_cell(x+0, y+1, w, h, board) + \
- wrap_get_cell(x+1, y+1, w, h, board) + \
- wrap_get_cell(x+1, y+0, w, h, board) + \
- wrap_get_cell(x+1, y-1, w, h, board) + \
- wrap_get_cell(x+0, y-1, w, h, board) + \
- wrap_get_cell(x-1, y-1, w, h, board) + \
- wrap_get_cell(x-1, y+0, w, h, board) + \
- wrap_get_cell(x-1, y+1, w, h, board)
- living_currently = board[y][x]
- if living_currently:
- if count_neighbors in (2,3):
- return on
- else:
- return off
- else:
- if count_neighbors == 3:
- return on
- else:
- return off
- def print_board(b):
- for row in b:
- for cell in row:
- print(cell, end="") # end="" suppresses newlines.
- print("\n", end="")
- # Given a list of strings li, put the character at [y][x]
- # into the right place in the given board b.
- def setboard(b, li):
- for row_n, row in enumerate(li):
- for x, cell in enumerate(row):
- b[row_n][x] = on if (cell == "*") else off;
- def run_life():
- # Board is a list of rows, each containing a list of cells.
- # Start off all cell off.
- board = [[off for x in range(width)] for y in range(height)]
- oldboard = [[off for x in range(width)] for y in range(height)]
- # Put a glider in the top left.
- setboard(board, [" * ", \
- " * ", \
- " *** "])
- for step in range(max_steps):
- # Swap boards.
- # We read from the current board (we just printed) now called 'oldboard'.
- # And we write into a new board now called 'board'.
- board, oldboard = oldboard, board
- for y in range(height):
- for x in range(width):
- board[y][x] = calculate_new_cell_at(x, y, width, height, oldboard)
- print()
- print()
- print()
- print("LIFE AFTER %d STEPS" % step)
- print_board(board)
- time.sleep(0.2)
- # If we are -running- this file, not just importing its functions
- # this bottom bit is run.
- if __name__ == "__main__":
- run_life()
Advertisement
Add Comment
Please, Sign In to add comment