class App(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.title("Conway's Game of Life") self.canvas = tk.Canvas(self, width=500, height=500) self.canvas.pack(side="top", fill="both", expand=True) self.rows = 100 self.columns = 100 self.size = 10 self.rect = {} for r in range(self.rows): for c in range(self.columns): x1 = c * self.size y1 = r * self.size x2 = x1 + self.size y2 = y1 + self.size self.rect[r, c] = self.canvas.create_rectangle(x1, y1, x2, y2, fill="white") self.con = Conway(self.rows, self.columns) self.con.populate() self.redraw(10) def redraw(self, delay): self.con.generation() for r in range(self.rows): for c in range(self.columns): if self.con.board[r][c] == '.': self.canvas.itemconfig(self.rect[r, c], fill="black") else: self.canvas.itemconfig(self.rect[r, c], fill="white") self.after(delay, lambda: self.redraw(delay))
def pygame_loop(conway: Conway, screen_size: tuple = (800, 800), fps: int = 30): """ Function to display the evolution of Conway's Game of Life or any other simulation with a 2D output. Parameters ---------- conway : Conway Any class providing the attributes * shape * is_empty and the methods * show_field() -> numpy.ndarray * update_field() * reset_field() screen_size : Tuple(int, int), optional Size of the Screen to be displayed. The default is (1600, 800). fps : int, optional Frames per second goal to achieve. The default is 30. """ pygame.init() screen = pygame.display.set_mode(screen_size, HWSURFACE | DOUBLEBUF) running = True clock = pygame.time.Clock() colors = np.array([[155, 255, 155], [0, 20, 220]]) while running: pygame.display.update() conway.update_field() arr = conway.show_field() surf = pygame.surfarray.make_surface(colors[arr]) surf = pygame.transform.scale(surf, screen_size) screen.blit(surf, (0, 0)) clock.tick(fps) #surf = pygame.Surface(conway.shape) #surfarray.blit_array(surf, arr) #surf = pygame.transform.scale(surf, screen_size) #screen.blit(surf, (0, 0)) #clock.tick(fps) pygame.display.set_caption( f"Conway's Game of Life | fps: {clock.get_fps():.3}") for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_BACKSPACE: running = False elif event.type == QUIT: running = False pygame.quit() if conway.is_empty: sleep(0.5) conway.reset_field()
def start_conway(self, game_height, game_width): """Load or generate a Conway graph from input. Quits if 'q' is hit. :param game_height: the height of the Conway graph :param game_width: the width of the Conway graph :return: a Conway graph fitting input """ # Start a new Conway graph to be returned. conway = Conway(game_width, game_height) # Either randomize the Conway graph (enter), load ('l'), or quit ('q'). key = self.intro_win.getkey() if key is '\n': # If enter is hit, start conway as a randomized graph. return conway.randomize() elif key is 'l': # If 'l' is hit, load from file. # Clear line 7 in case user input a key other than enter or 'l'. self.add_text_easy(7, 0, ' '*49).add_text_easy(7, 0, "Enter filename: ") curses.echo() filename = self.intro_win.getstr(7, 16) curses.noecho() try: return conway.read_from_file(filename) except FileNotFoundError: self.add_text_easy(7, 0, ' '*self.win_width) self.add_text_easy(7, 8, "File not found. Please try again.") return self.start_conway(game_height, game_width) elif key is 'q': # Exit the program safely. exit() else: # If another key is hit, tell the user it was invalid and retry. self.add_text_easy(7, 0, ' '*49).add_text_easy(7, 16, "Invalid command.") return self.start_conway(game_height, game_width)
def main(): if len(sys.argv) > 1: tick_count = int(sys.argv[1]) else: tick_count = 20 # Initialize ncurses and get the board dimensions from the screen limits scr = curses.initscr() (x, y) = scr.getmaxyx() dim = min(x, y) # Use the lower bound to set the dimensions conway = Conway(bounds=(0, dim)) # Turn on the initialized cells initial_cells = read_initial_state_file('initial_state.txt') for cell in initial_cells: conway.set_initial_state_on_board(cell, True) scr.keypad(0) curses.noecho() curses.curs_set(0) # Draw the live cells on the screen and update tick for i in range(tick_count): scr.clear() for position in conway.get_alive_positions(): # Draw as an asterisk scr.addstr(position[0], position[1], '*') scr.refresh() # Slow down if necessary time.sleep(.5) # Update each cells future state conway.update_each_cells_state() # Update the board all at once conway.update_board() # No ticks left, all done cleanup()
def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.title("Conway's Game of Life") self.canvas = tk.Canvas(self, width=500, height=500) self.canvas.pack(side="top", fill="both", expand=True) self.rows = 100 self.columns = 100 self.size = 10 self.rect = {} for r in range(self.rows): for c in range(self.columns): x1 = c * self.size y1 = r * self.size x2 = x1 + self.size y2 = y1 + self.size self.rect[r, c] = self.canvas.create_rectangle(x1, y1, x2, y2, fill="white") self.con = Conway(self.rows, self.columns) self.con.populate() self.redraw(10)
def main(): if len(sys.argv) > 1: tick_count = int(sys.argv[1]) else: tick_count = 20 # Initialize ncurses and get the board dimensions from the screen limits scr = curses.initscr() (x,y) = scr.getmaxyx() dim = min(x, y) # Use the lower bound to set the dimensions conway = Conway(bounds=(0,dim)) # Turn on the initialized cells initial_cells = read_initial_state_file('initial_state.txt') for cell in initial_cells: conway.set_initial_state_on_board(cell, True) scr.keypad(0) curses.noecho() curses.curs_set(0) # Draw the live cells on the screen and update tick for i in range(tick_count): scr.clear() for position in conway.get_alive_positions(): # Draw as an asterisk scr.addstr(position[0],position[1],'*') scr.refresh() # Slow down if necessary time.sleep(.5) # Update each cells future state conway.update_each_cells_state() # Update the board all at once conway.update_board() # No ticks left, all done cleanup()
clock.tick(fps) pygame.display.set_caption( f"Conway's Game of Life | fps: {clock.get_fps():.3}") for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_BACKSPACE: running = False elif event.type == QUIT: running = False pygame.quit() if conway.is_empty: sleep(0.5) conway.reset_field() if __name__ == '__main__': import numpy as np from configs import * base = np.zeros((81, 101)) # start_config = insert_pattern(base, BLINKER) start_config = insert_pattern(base, GOSPER, offset=(-20, -20)) start_config = insert_pattern(start_config, GOSPER, offset=(10, 10)).T # start_config = insert_pattern(base, PULSER).T # start_config = insert_pattern(start_config, BLINKER, offset=(7, 5)) # start_config = insert_pattern(start_config, BLINKER, offset=(-8, 5)) # start_config = insert_pattern(start_config, BLINKER, offset=(7, -5)) # start_config = insert_pattern(start_config, BLINKER, offset=(-8, -5)) screen_size = np.array(start_config.shape) * 10 conway = Conway(start_config) pygame_loop(conway, screen_size=screen_size, fps=20)
from conway import Conway inputs = [line.strip() for line in open("input.txt").readlines()] c = Conway() c.set_initial_state(inputs) for i in range(6): c.cycle() print(len(c.cubes)) exit()
from conway import Conway import neworder as no # size of domain nx, ny = (320, 320) # saturation (proportion initially alive) sat = 0.36 n = int(nx * ny * sat) # edges wrap - try with no.Edge.CONSTRAIN m = Conway(nx, ny, n, no.Edge.WRAP) no.run(m)
clear_text = button_font.render("Clear", 1, (10, 10, 10)) clear_text_rec = clear_text.get_rect() clear_text_rec.x = 390 clear_text_rec.y = 60 generation_text = button_font.render("Generation: 0", 1, (10, 10, 10)) generation_text_rec = generation_text.get_rect() generation_text_rec.x = 460 generation_text_rec.y = 400 cells = pygame.sprite.Group() for i in range(game_size): for j in range(game_size): cells.add(Cell(i, j)) conway = Conway(game_size) clock = pygame.time.Clock() done = False running = False pygame.time.set_timer(pygame.USEREVENT_CONWAY_STEP, 1000) while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.MOUSEBUTTONUP: pos = pygame.mouse.get_pos() if start_text_rec.collidepoint(pos): if running: running = False start_text = button_font.render(
row_count = int(worldfile.readline().strip()) col_count = int(worldfile.readline().strip()) data = [] for r in range(row_count): row = tuple(c == '*' for c in worldfile.readline().strip()) assert len(row) == col_count, f"Row {r} is too long!" data.append(row) return row_count, col_count, data if __name__ == "__main__": root = tk.Tk() filepath = None if len(sys.argv) < 2: filepath = filedialog.askopenfilename(title="Open Conway World...", filetypes=(("Text Files", "*.txt"), ("All Files", "*.*"))) else: filepath = sys.argv[1] with open(filepath) as worldfile: row_count, col_count, cells = parse_file(worldfile) app = Conway(row_count, col_count, cells, root) while True: app.tick() root.update() root.update_idletasks() time.sleep(0.5) # root.mainloop()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 17 10:58:54 2021 @author: dkappe """ from conway import Conway from visual import pygame_loop from configs import GOSPER, insert_pattern if __name__ == '__main__': import numpy as np base = np.zeros((1000, 1000)) start_config = insert_pattern(base, GOSPER, offset=(-90, -80)).T screen_size = np.array(start_config.shape) * 1 conway = Conway(start_config, border=True, fade=(0.7, 0.7, 0.5), gauss_sigma=0) pygame_loop(conway, screen_size=screen_size, fps=150)
surfarray.blit_array(surf, arr) surf = pygame.transform.scale(surf, screen_size) screen.blit(surf, (0, 0)) clock.tick(fps) pygame.display.set_caption( f"Conway's Game of Life | fps: {clock.get_fps():.3}") for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_BACKSPACE: running = False elif event.type == QUIT: running = False pygame.quit() if conway.is_empty: sleep(0.5) conway.reset_field() if __name__ == '__main__': import numpy as np from configs import insert_pattern, PULSER, BLINKER base = np.zeros((15, 20)) start_config = insert_pattern(base, PULSER).T start_config = insert_pattern(start_config, BLINKER, offset=(7, 5)) start_config = insert_pattern(start_config, BLINKER, offset=(-7, 5)) start_config = insert_pattern(start_config, BLINKER, offset=(7, -5)) start_config = insert_pattern(start_config, BLINKER, offset=(-7, -5)) screen_size = np.array(start_config.shape) * 60 conway = Conway(start_config, fade=(0.5, 0.5, 0.2), gauss_sigma=2) pygame_loop(conway, screen_size=screen_size, fps=10)