Created
January 18, 2025 10:40
-
-
Save horstjens/4af5281bdde15fc8cf10604f2c3cbac6 to your computer and use it in GitHub Desktop.
conway game of life
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# conways game of life | |
# see https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life | |
startfield=""" | |
...X............ | |
.......XXX.....X | |
...............X | |
...............X | |
................ | |
................ | |
...X............ | |
...X............ | |
""" | |
startfield2 = """ | |
..... | |
..... | |
.XXX. | |
..... | |
..... | |
""" | |
def display(array): | |
for line in array: | |
# print(line) | |
print( "".join(line)) | |
def check_startfield(): | |
"""reads startfield into an array and returns it, | |
return None if array is not rectangular""" | |
length = None | |
board = [] | |
# spielfeld einlesen | |
for line in startfield.splitlines(): | |
if len(line.strip())==0: | |
continue | |
if length is None: | |
length = len(line) | |
if len(line) != length: | |
print(f"Error: Length should be: {length} but is {len(line)}: {line}") | |
return None | |
board.append(list(line)) | |
return board | |
def main(): | |
board = check_startfield() | |
if board is None: | |
return | |
length = len(board[0]) | |
height = len(board) | |
print("Dimensions:",length, height) | |
while True: | |
display(board) | |
command=input("press ENTER for next turn or q to quit >>>") | |
if command=="q": | |
break | |
# board2 must be empty | |
board2 = [["." for element in line1] for line1 in board] | |
#print("empty:", board2) | |
# caclulate | |
#numbers = [] | |
for y, line in enumerate(board): | |
#numberline = "" | |
for x, char in enumerate(line): | |
alive=0 | |
for dx,dy in ((1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)): | |
# wrap-around | |
nx = x+dx | |
ny = y+dy | |
#if nx == -1: | |
# nx = length - 1 | |
#if ny == -1: | |
# ny = height - 1 | |
if nx == length: | |
nx = 0 | |
if ny == height: | |
ny = 0 | |
if board[ny][nx] == "X": | |
alive += 1 | |
#numberline += f"{alive}" | |
new = "." | |
if (board[y][x]==".") and (alive == 3): | |
new = "X" | |
elif (board[y][x]== "X") and (2 <= alive <= 3): | |
new = "X" | |
board2[y][x]=new | |
# numbers.append(numberline) | |
#print("\n".join(numbers)) | |
board = board2 | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment