HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Grid displayer: Game of Life and Langton's Ant

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
displayergridandantgamelifelangton

Problem

Re-use

Given that both the Langton's Ant and the Game of Life use a grid, I decided to code a generic grid_diplayer code and use it both for GoL (Game of Life) and Langton's Ant to put into practice the principle of code re-use.

Rules of Game of Life

Rules of Langton's Ant

Pure logic

The code inside the ant_logic and life_logic cannot make contact with the outside world, any state not contained in the grid can be handled with a specific state variable that is returned along with the grid.

grid_displayer

grid_displayer shows the board after each update.

Commands

In the case of Game of Life I also added a bit of interactivity (in grid_displayer):

  • SPACEBAR : Pause / Resume



  • ENTER : Start Again from a random board



  • + : Increase the x and y dimension by 10



  • - : Decrease the x and y dimension by 10



(Please note that + and - may create un-aesthetic effects if the size is not a sub-multiple of the screen size, just increase or decrease more to get a nicer effect)

grid_displayer

``
import sys, pygame
import random
from itertools import count

import life_logic
import ant_logic as ant

def show_grid(grid, screen, screen_size, color_decider):
"""
Shows the
grid on the screen.
The colour of each cell is given by color_decider,
a function of the form (cell -> rgb_triplet)
"""
number_of_squares = len(grid)
square_size = screen_size[0] // number_of_squares

for y, row in enumerate(grid):
for x, item in enumerate(row):
pygame.draw.rect(screen, color_decider(item), (x square_size, y square_size, square_size, square_size), 0)

def animate_grid(grid, grid_updater, color_decider, screen_size=(600, 600), state={}):
"""
Repeatedly calls
show_grid` to show a continually updating grid.
"""
pygame.init()
screen = pygame.display.set_mode( screen_size )

for ticks in count(0):
user_inputs = pygame.event.get()
# if user_inputs: print(rep

Solution

You offered the code without a specific review question, so I take it to be a generic "please pick nits" sort of review.

Your code has exemplary style, very clear, with nicely chosen identifiers and lovely docstrings. I have no nits to pick. Bravo!

Put another way, every bit of code you write presents an argument to the Gentle Reader, and I am completely buying the argument, I believe it.

Context

StackExchange Code Review Q#140673, answer score: 2

Revisions (0)

No revisions yet.