Created
May 13, 2023 17:34
-
-
Save richhaase/e3be82279ceeaa59945228367e950dd2 to your computer and use it in GitHub Desktop.
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
| ''' | |
| Conway's Game of Life implementation in Python | |
| Generated by OpenAI's ChatGPT | |
| Original code adapted from OpenAI's ChatGPT example code | |
| Modified by Rich Haase | |
| Date: 2023-05-11 | |
| Code licensed under the MIT License | |
| Copyright 2023 Rich Haase | |
| Permission is hereby granted, free of charge, to any person obtaining a copy of | |
| this software and associated documentation files (the “Software”), to deal in the | |
| Software without restriction, including without limitation the rights to use, | |
| copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the | |
| Software, and to permit persons to whom the Software is furnished to do so, | |
| subject to the following conditions: | |
| The above copyright notice and this permission notice shall be included in all | |
| copies or substantial portions of the Software. | |
| THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS | |
| FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR | |
| COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER | |
| IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION | |
| WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
| Source: OpenAI's ChatGPT example | |
| ''' | |
| import argparse | |
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| import matplotlib.animation as animation | |
| import time | |
| import sys | |
| def initialize_grid(size, chance): | |
| grid = np.random.choice([0, 1], size=(size, size), p=[1 - chance, chance]) | |
| return grid | |
| def load_generation(file_path): | |
| try: | |
| grid = np.loadtxt(file_path, delimiter=',', dtype=int) | |
| return grid | |
| except IOError: | |
| print(f"Failed to load generation from file: {file_path}") | |
| return None | |
| def update_grid(grid): | |
| size = grid.shape[0] | |
| new_grid = np.copy(grid) | |
| for i in range(size): | |
| for j in range(size): | |
| neighbors = get_alive_neighbors(grid, i, j) | |
| if grid[i, j] == 1: # Cell is alive | |
| if neighbors < 2 or neighbors > 3: | |
| new_grid[i, j] = 0 # Cell dies due to underpopulation or overcrowding | |
| else: # Cell is dead | |
| if neighbors == 3: | |
| new_grid[i, j] = 1 # Cell becomes alive due to reproduction | |
| return new_grid | |
| def get_alive_neighbors(grid, row, col): | |
| size = grid.shape[0] | |
| count = 0 | |
| for i in range(-1, 2): | |
| for j in range(-1, 2): | |
| if i == 0 and j == 0: | |
| continue # Skip the current cell | |
| neighbor_row = (row + i) % size | |
| neighbor_col = (col + j) % size | |
| count += grid[neighbor_row, neighbor_col] | |
| return count | |
| def animate_grid(initial_grid, num_generations, interval): | |
| plt.rcParams['keymap.save'] = '' # Disable the 's' key binding | |
| fig, ax = plt.subplots(figsize=(12, 9)) | |
| img = ax.imshow(initial_grid, cmap='binary') | |
| grid_history = [initial_grid] # Initialize the grid history | |
| current_generation = 0 | |
| def animate(frame): | |
| nonlocal current_generation | |
| if is_paused: | |
| return | |
| if current_generation >= num_generations: | |
| # Stop the animation after reaching the desired number of generations | |
| ani.event_source.stop() | |
| return | |
| grid = update_grid(grid_history[current_generation]) | |
| current_generation += 1 | |
| if current_generation < len(grid_history): | |
| grid = np.copy(grid_history[current_generation]) | |
| else: | |
| grid_history.append(np.copy(grid)) | |
| img.set_array(grid) | |
| ax.set_title(f"Generation: {current_generation} of {num_generations}", fontsize=14) | |
| def on_key(event): | |
| nonlocal current_generation | |
| global is_paused | |
| if event.key == ' ': | |
| is_paused = not is_paused | |
| elif event.key == 'left': | |
| current_generation = max(current_generation - 1, 0) | |
| grid = np.copy(grid_history[current_generation]) | |
| img.set_array(grid) | |
| elif event.key == 's': | |
| save_generation(grid_history[current_generation], current_generation) | |
| def save_generation(grid, generation_number): | |
| timestamp = time.strftime("%Y%m%d%H%M%S", time.localtime()) | |
| filename = f'generation_{generation_number}_{timestamp}.txt' | |
| np.savetxt(filename, grid, fmt='%d', delimiter=',') | |
| ax.set_title(f"Generation: {current_generation} of {num_generations}", fontsize=14) | |
| ax.text(0.5, -0.12, f"Generation saved to: {filename}", transform=ax.transAxes, ha='center', fontsize=12) | |
| fig.canvas.mpl_connect('key_press_event', on_key) | |
| ani = animation.FuncAnimation(fig, animate, frames=num_generations, interval=interval, blit=False) | |
| ax.set_title(f"Generation: {current_generation} of {num_generations}", fontsize=14) | |
| # Display the legend as text at the bottom of the screen | |
| legend_labels = ['Space: Pause/Resume', 'Left: Previous Generation', 'S: Save Generation'] | |
| legend_text = ' '.join(legend_labels) | |
| ax.text(0.5, -0.08, legend_text, transform=ax.transAxes, ha='center', fontsize=12) | |
| plt.show() | |
| def main(): | |
| parser = argparse.ArgumentParser(description='Conway\'s Game of Life') | |
| parser.add_argument('--gridsize', type=int, default=50, | |
| help='size of the grid (default: 50)') | |
| parser.add_argument('--num-generations', type=int, default=100, | |
| help='total number of generations to generate (default: 100)') | |
| parser.add_argument('--speed', type=float, default=0.5, | |
| help='speed at which new generations are displayed in seconds (default: 0.5)') | |
| parser.add_argument('--initial-chance', type=float, default=0.3, | |
| help='odds that any cell will be populated initially (default: 0.3)') | |
| parser.add_argument('--load', type=str, default=None, | |
| help='file path to load a generation from') | |
| args = parser.parse_args() | |
| global is_paused | |
| is_paused = False | |
| if args.load is None: | |
| initial_grid = initialize_grid(args.gridsize, args.initial_chance) | |
| else: | |
| initial_grid = load_generation(args.load) | |
| # Configure the animation speed | |
| interval = int(args.speed * 1000) | |
| animate_grid(initial_grid, args.num_generations, interval) | |
| if __name__ == '__main__': | |
| main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment