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

Conway's Game of Life (follow-up)

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

Problem

I asked for a review of my code, and after making the suggested changes I feel that now the OOP version is clearer in its meaning and overall the code looks cleaner.

```
"""Object oriented implementaition of Conway's Game of life"""
import random
import time
import os

class GameOfLife():
FILE_NAME = "grid.txt"
ROWS = 22
COLS = 62
DELAY = 0.2
GENERATIONS = 200

def __init__(self, rows=ROWS, cols=COLS, delay=DELAY,from_file=False, \
num_generations=GENERATIONS, alive_cell="*", dead_cell="."):
"""
Initializes a GameOfLife Object with the provided values
"""
self.generations = num_generations
self.alive_cell = alive_cell
self.dead_cell = dead_cell
if from_file:
self.cur_gen = self.read_grid()
else:
self.cur_gen = self.init_grid()
self.rows = len(self.cur_gen)
self.cols = len(self.cur_gen[0])

def read_grid(self):
"""
Reads a given grid from a text file and sanitizes it to be used with the
script.
"""
array = []
with open("grid.txt", "r") as f:
for line in f:
temp = []
for char in line:
if char == "*":
temp.append(1)
elif char == ".":
temp.append(0)
array += [temp]

for i in range(len(array)):
for j in range(len(array[0])):
if (i == 0 or j == 0 or (i == len(array) - 1) or (j == len(array[0]) - 1)):
array[i][j] = -1
return array

def init_grid(self,rows=ROWS, cols=COLS):
"""
Returns an array filled with random alive and dead cells of the given
dimensions
"""
array = []
for i in range(rows):
single_row = []
for j in range(cols):
if(i == 0 or j == 0 or (i == rows - 1) or ( j == cols

Solution

First off, the line class GameOfLife(): should be changed to class GameOfLife:.

Secondly, using os.system("clear") isn't very portable. A more portable method would be os.system("cls" if os.name == "nt" else "clear"). If you want re-usability, you can also put this into a function, like this:

def clear():
    os.system("cls" if os.name == "nt" else "clear")


You also don't need to surround conditions in if statements with parentheses. For example if(i == 0 or j == 0 or (i == rows - 1) or ( j == cols - 1 )): should be changed to i (i == 0 or j == 0 or (i == rows - 1) or ( j == cols - 1 ):.

Finally, some of your variable names aren't so great. For example, i, j, or array are not so great. Variable names like these should be more descriptive and describe what the purpose of the variables are.

Code Snippets

def clear():
    os.system("cls" if os.name == "nt" else "clear")

Context

StackExchange Code Review Q#82718, answer score: 3

Revisions (0)

No revisions yet.