Last active
August 29, 2015 14:16
-
-
Save mgdm/ec3aa57c6c13999e406a to your computer and use it in GitHub Desktop.
Game of Life in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import numpy as np | |
| import os, sys, time | |
| from random import randrange | |
| def make_board(width, height): | |
| board = np.zeros((width, height)) | |
| for y in xrange(0, height): | |
| for x in xrange(0, width): | |
| if randrange(10) > 8: | |
| board[x, y] = 1 | |
| return board | |
| def print_board(board): | |
| width, height = board.shape | |
| for y in xrange(0, height): | |
| for x in xrange(0, width): | |
| if board[x, y]: | |
| #sys.stdout.write('\033[7m \033[0m') | |
| sys.stdout.write('\xF0\x9F\x98\x83 ') | |
| else: | |
| sys.stdout.write(' ') | |
| sys.stdout.write("\n") | |
| def count_neighbours(board, x, y): | |
| num = 0 | |
| for i in xrange(-1, 2): | |
| for j in xrange(-1, 2): | |
| if i == j == 0: | |
| continue | |
| try: | |
| if board[x + i, y + j]: | |
| num += 1 | |
| except IndexError: | |
| pass | |
| return num | |
| def run_game(board): | |
| width, height = board.shape | |
| new_board = make_board(width, height) | |
| for y in xrange(0, height): | |
| for x in xrange(0, width): | |
| neighbours = count_neighbours(board, x, y) | |
| live = board[x, y] == 1 | |
| if live: | |
| if neighbours < 2: | |
| new_board[x, y] = 0 | |
| elif neighbours < 4: | |
| new_board[x, y] = 1 | |
| else: | |
| new_board[x, y] = 0 | |
| else: | |
| if neighbours == 3: | |
| new_board[x, y] = 1 | |
| return new_board | |
| def clear_screen(): | |
| sys.stdout.write("\x1b[2J\x1b[H") | |
| def get_terminal_size(): | |
| import fcntl, termios, struct | |
| h, w, hp, wp = struct.unpack('HHHH', | |
| fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, | |
| struct.pack('HHHH', 0, 0, 0, 0))) | |
| return w, h | |
| if __name__ == '__main__': | |
| width, height = get_terminal_size() | |
| board = make_board(width / 2, height - 2) | |
| clear_screen() | |
| print_board(board) | |
| for i in xrange(0, 100): | |
| clear_screen() | |
| board = run_game(board) | |
| print_board(board) | |
| time.sleep(0.1) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment