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

Object-oriented Conway's Game of Life

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

Problem

I have Conway's Game of Life working now and was hoping for direction on:

  • Unclear code - where would comments make it clearer?



  • Poor design choices - I already know of one in the countNeighbors method, as it needs knowledge of the game object's name



  • Improvements to make - I have already noted that I wish to add more templates and the ability to rotate them. What would be a good idea to implement that would improve/demonstrate a coding concept?



```
#TODO - automate the generation cyling
#TODO - allow rotation of templates
#TODO - generate more templates (gun, oscillator,LWSS etc)
#TODO - don't require knowledge of the board object in the methods of the cell object!

from tkinter import *
import time

class game:
"""An object to store the game"""

def __init__(self, size):
self.size = size
self.cell_size = 25
window = Tk()
self.canvas = Canvas(window, width=size self.cell_size, height=size self.cell_size)
self.canvas.pack()

self.board = [[cell(i, j) for i in range(size)] for j in range(size)]

return None

def drawbox(self):
for j in range(self.size):
for i in range(self.size):
if self.board[i][j].alive:
self.box_colour = "#220C65"
else:
self.box_colour = "#B7F3D5"

self.canvas.create_rectangle(self.cell_size i, self.cell_size j,self.cell_size * i + self.cell_size,
self.cell_size * j + self.cell_size, fill=self.box_colour, outline="#FFFFFF",width=2)

return

def createGlider(self, x, y):
self.board[x - 1][y - 1].alive = True
self.board[x][y - 1].alive = True
self.board[x + 1][y - 1].alive = True
self.board[x + 1][y].alive = True
self.board[x][y + 1].alive = True

def createGun(self,x,y):
self.board

class cell:
"""An object for the cells in Conway's Game of Life"""

def __init__(self, y, x

Solution

In my opinion, I believe your code is pretty straight forward and doesn't need much extra comments (Perhaps to explain your steps in the 'countNeighbors' method).

Perhaps also consider to use

if __name__ == '__main__':


for the later part of your code (under the '####'),

which has two primary use cases:

-
Allow a module to provide functionality for import into other code
while also providing useful semantics as a standalone script (a
command line wrapper around the functionality)

-
Allow a module to define a suite of unit tests which are stored with (in the same file as) the code to be tested and which can be
executed independently of the rest of the codebase.

(Source: https://stackoverflow.com/questions/22492162/understanding-the-main-method-of-python)

Code Snippets

if __name__ == '__main__':

Context

StackExchange Code Review Q#74932, answer score: 3

Revisions (0)

No revisions yet.