I've again encountered I don't know if a problem or just the placement of my code is off but in my python take on Conways game of life in python(taken from The Coding Train challenge #85 in js) with pygame to actually display the system.
I have finished and it seems to run, but the end result doesn't seem to me like the one you see in finished projects, mine looks more like a QR code or idk.
If you could take a look at it, would appreciate it a lot.
Here is the source code:
from itertools import count
from os import stat
import pygame
import random
WIDTH = 500
HEIGHT = 500
pygame.init()
window = pygame.display.set_mode((WIDTH,HEIGHT))
# create 2d array
def create_2d_list(cols, rows):
arr = []
for i in range(cols):
arr.append([0] * rows)
return arr
resolution = 20
cols = WIDTH // resolution
rows = HEIGHT // resolution
def main():
# pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
global grid
grid = create_2d_list(cols, rows)
for i in range(cols):
for j in range(rows):
grid[i][j] = random.randint(0,1)
draw()
next = create_2d_list(cols, rows)
# compute next based on grid
for i in range(cols):
for j in range(rows):
state = grid[i][j]
# count live neighbors
sum = 0
neighbors = countNeighbors(grid, i , j)
if state == 0 and neighbors == 3:
next[i][j] = 1
elif state == 1 and (neighbors < 2 or neighbors > 3):
next[i][j] = 0
else:
next[i][j] = state
grid = next
pygame.time.delay(50)
pygame.display.flip()
def draw():
background = window.fill((255,255,255))
for i in range(cols):
for j in range(rows):
x = i * resolution
y = j * resolution
if grid[i][j] == 1:
pygame.draw.rect(window,(0,0,0), pygame.Rect(x , y, resolution, resolution))
elif grid[i][j] == 0:
pygame.draw.rect(window,(255,255,255), pygame.Rect(x , y, resolution, resolution))
def countNeighbors(grid, x, y):
sum = 0
for i in range(-1,2):
for j in range(-1,2):
col = (x + i + cols) % cols
row = (x + i + rows) % rows
sum += grid[col][row]
sum -= grid[x][y]
return sum
if __name__ == "__main__":
main()
I tried to debug it and it seems at least to me that the rules of Conway's Game of Life apply. But still in the bigger picture it just looks off.
I do think it has to do with my code arrangement, and I am not exactly sure how to place it to be correct.