Conway's game of life in Python 3 with matplotlib - problem with displaying a formation
I am currently trying to program a python 3 implementation of the game of life. My main goal was to display a grid of the size n that gets filled randomly according to conway's rules.
That part works fine.
Now I wanted to implement a second mode that allows you to start with one of the given formations - in my first try a glider.
Here is the main():
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from gol_functions import *
def main():
# get arguments from input function
arguments = input_arguments()
# set the arguments
gridsize = int(arguments.gridsize)
interval = int(arguments.interval)
formation = arguments.formationflag
# if you want to start with a formation:
if formation:
grid = np.zeros(gridsize*gridsize).reshape(gridsize, gridsize)
add_glider(1, 1, grid)
# else display a randopm grid
else:
grid = randomgrid(gridsize)
fig, ax = plt.subplots()
# colormap: black -> alive, white -> dead
img = ax.imshow(grid, cmap='binary', interpolation='nearest')
# this will be used to save the animation in a later version
ani = animation.FuncAnimation(fig, update, fargs=(img, grid, gridsize,),
frames=10,
interval=interval,
save_count=50)
# remove x and y - axis labels, numbers and ticks
ax.axes.xaxis.set_ticklabels()
ax.axes.yaxis.set_ticklabels()
plt.xticks()
plt.yticks()
# plot the animated output
plt.show()
if __name__ == '__main__':
main()
Here is the function for adding the glider:
def add_glider(i, j, grid):
"""adds a glider with top-left cell at (i, j)"""
glider = np.array([[0, 0, 255],
[255, 0, 255],
[0, 255, 255]])
grid[i:i+3, j:j+3] = glider
It adds a glider in the grid @ position 1, 1
And here is my update function:
def update(frameNum, img, grid, gridsize):
"""Updates the grid every time it is refreshed"""
newgrid = grid.copy()
for i in range(gridsize):
for j in range(gridsize):
# this formula considers the edge/boundary conditions that appear
# every cell has to have 8 neighbouring cells
# to implement this in a grid of size n we simply fold the 4 edges to each parallel edge
# we'll end up with a cylinder first, then with a geometric shape called torus (google it.)
total = int((grid[i, (j - 1) % gridsize] + grid[i, (j + 1) % gridsize] +
grid[(i - 1) % gridsize, j] + grid[(i + 1) % gridsize, j] +
grid[(i - 1) % gridsize, (j - 1) % gridsize] +
grid[(i - 1) % gridsize, (j + 1) % gridsize] +
grid[(i + 1) % gridsize, (j - 1) % gridsize] + grid[
(i + 1) % gridsize, (j + 1) % gridsize]) / 255)
# apply conway's basic rules of the game of life for each cell
if grid[i, j] == ON:
if (total < 2) or (total > 3):
newgrid[i, j] = OFF
else:
if total == 3:
newgrid[i, j] = ON
# update data
img.set_data(newgrid)
grid[:] = newgrid[:]
return img,
However when I run it with the option to have it display the glider, all I see is the following formation...
failedglider_1.png
which swiftly turns into this and becomes static:
failedglider_2.png
... instead of an actual glider as seen in the matrix of add_glider. So it seems that somehow the program adds an unwanted alive cell right at the top. I tried to find where it comes from... but I can't find it.
Does anyone have any clues? I am greatful for all help.
Thanks in advance!
python python-3.x matplotlib conways-game-of-life
add a comment |
I am currently trying to program a python 3 implementation of the game of life. My main goal was to display a grid of the size n that gets filled randomly according to conway's rules.
That part works fine.
Now I wanted to implement a second mode that allows you to start with one of the given formations - in my first try a glider.
Here is the main():
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from gol_functions import *
def main():
# get arguments from input function
arguments = input_arguments()
# set the arguments
gridsize = int(arguments.gridsize)
interval = int(arguments.interval)
formation = arguments.formationflag
# if you want to start with a formation:
if formation:
grid = np.zeros(gridsize*gridsize).reshape(gridsize, gridsize)
add_glider(1, 1, grid)
# else display a randopm grid
else:
grid = randomgrid(gridsize)
fig, ax = plt.subplots()
# colormap: black -> alive, white -> dead
img = ax.imshow(grid, cmap='binary', interpolation='nearest')
# this will be used to save the animation in a later version
ani = animation.FuncAnimation(fig, update, fargs=(img, grid, gridsize,),
frames=10,
interval=interval,
save_count=50)
# remove x and y - axis labels, numbers and ticks
ax.axes.xaxis.set_ticklabels()
ax.axes.yaxis.set_ticklabels()
plt.xticks()
plt.yticks()
# plot the animated output
plt.show()
if __name__ == '__main__':
main()
Here is the function for adding the glider:
def add_glider(i, j, grid):
"""adds a glider with top-left cell at (i, j)"""
glider = np.array([[0, 0, 255],
[255, 0, 255],
[0, 255, 255]])
grid[i:i+3, j:j+3] = glider
It adds a glider in the grid @ position 1, 1
And here is my update function:
def update(frameNum, img, grid, gridsize):
"""Updates the grid every time it is refreshed"""
newgrid = grid.copy()
for i in range(gridsize):
for j in range(gridsize):
# this formula considers the edge/boundary conditions that appear
# every cell has to have 8 neighbouring cells
# to implement this in a grid of size n we simply fold the 4 edges to each parallel edge
# we'll end up with a cylinder first, then with a geometric shape called torus (google it.)
total = int((grid[i, (j - 1) % gridsize] + grid[i, (j + 1) % gridsize] +
grid[(i - 1) % gridsize, j] + grid[(i + 1) % gridsize, j] +
grid[(i - 1) % gridsize, (j - 1) % gridsize] +
grid[(i - 1) % gridsize, (j + 1) % gridsize] +
grid[(i + 1) % gridsize, (j - 1) % gridsize] + grid[
(i + 1) % gridsize, (j + 1) % gridsize]) / 255)
# apply conway's basic rules of the game of life for each cell
if grid[i, j] == ON:
if (total < 2) or (total > 3):
newgrid[i, j] = OFF
else:
if total == 3:
newgrid[i, j] = ON
# update data
img.set_data(newgrid)
grid[:] = newgrid[:]
return img,
However when I run it with the option to have it display the glider, all I see is the following formation...
failedglider_1.png
which swiftly turns into this and becomes static:
failedglider_2.png
... instead of an actual glider as seen in the matrix of add_glider. So it seems that somehow the program adds an unwanted alive cell right at the top. I tried to find where it comes from... but I can't find it.
Does anyone have any clues? I am greatful for all help.
Thanks in advance!
python python-3.x matplotlib conways-game-of-life
add a comment |
I am currently trying to program a python 3 implementation of the game of life. My main goal was to display a grid of the size n that gets filled randomly according to conway's rules.
That part works fine.
Now I wanted to implement a second mode that allows you to start with one of the given formations - in my first try a glider.
Here is the main():
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from gol_functions import *
def main():
# get arguments from input function
arguments = input_arguments()
# set the arguments
gridsize = int(arguments.gridsize)
interval = int(arguments.interval)
formation = arguments.formationflag
# if you want to start with a formation:
if formation:
grid = np.zeros(gridsize*gridsize).reshape(gridsize, gridsize)
add_glider(1, 1, grid)
# else display a randopm grid
else:
grid = randomgrid(gridsize)
fig, ax = plt.subplots()
# colormap: black -> alive, white -> dead
img = ax.imshow(grid, cmap='binary', interpolation='nearest')
# this will be used to save the animation in a later version
ani = animation.FuncAnimation(fig, update, fargs=(img, grid, gridsize,),
frames=10,
interval=interval,
save_count=50)
# remove x and y - axis labels, numbers and ticks
ax.axes.xaxis.set_ticklabels()
ax.axes.yaxis.set_ticklabels()
plt.xticks()
plt.yticks()
# plot the animated output
plt.show()
if __name__ == '__main__':
main()
Here is the function for adding the glider:
def add_glider(i, j, grid):
"""adds a glider with top-left cell at (i, j)"""
glider = np.array([[0, 0, 255],
[255, 0, 255],
[0, 255, 255]])
grid[i:i+3, j:j+3] = glider
It adds a glider in the grid @ position 1, 1
And here is my update function:
def update(frameNum, img, grid, gridsize):
"""Updates the grid every time it is refreshed"""
newgrid = grid.copy()
for i in range(gridsize):
for j in range(gridsize):
# this formula considers the edge/boundary conditions that appear
# every cell has to have 8 neighbouring cells
# to implement this in a grid of size n we simply fold the 4 edges to each parallel edge
# we'll end up with a cylinder first, then with a geometric shape called torus (google it.)
total = int((grid[i, (j - 1) % gridsize] + grid[i, (j + 1) % gridsize] +
grid[(i - 1) % gridsize, j] + grid[(i + 1) % gridsize, j] +
grid[(i - 1) % gridsize, (j - 1) % gridsize] +
grid[(i - 1) % gridsize, (j + 1) % gridsize] +
grid[(i + 1) % gridsize, (j - 1) % gridsize] + grid[
(i + 1) % gridsize, (j + 1) % gridsize]) / 255)
# apply conway's basic rules of the game of life for each cell
if grid[i, j] == ON:
if (total < 2) or (total > 3):
newgrid[i, j] = OFF
else:
if total == 3:
newgrid[i, j] = ON
# update data
img.set_data(newgrid)
grid[:] = newgrid[:]
return img,
However when I run it with the option to have it display the glider, all I see is the following formation...
failedglider_1.png
which swiftly turns into this and becomes static:
failedglider_2.png
... instead of an actual glider as seen in the matrix of add_glider. So it seems that somehow the program adds an unwanted alive cell right at the top. I tried to find where it comes from... but I can't find it.
Does anyone have any clues? I am greatful for all help.
Thanks in advance!
python python-3.x matplotlib conways-game-of-life
I am currently trying to program a python 3 implementation of the game of life. My main goal was to display a grid of the size n that gets filled randomly according to conway's rules.
That part works fine.
Now I wanted to implement a second mode that allows you to start with one of the given formations - in my first try a glider.
Here is the main():
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from gol_functions import *
def main():
# get arguments from input function
arguments = input_arguments()
# set the arguments
gridsize = int(arguments.gridsize)
interval = int(arguments.interval)
formation = arguments.formationflag
# if you want to start with a formation:
if formation:
grid = np.zeros(gridsize*gridsize).reshape(gridsize, gridsize)
add_glider(1, 1, grid)
# else display a randopm grid
else:
grid = randomgrid(gridsize)
fig, ax = plt.subplots()
# colormap: black -> alive, white -> dead
img = ax.imshow(grid, cmap='binary', interpolation='nearest')
# this will be used to save the animation in a later version
ani = animation.FuncAnimation(fig, update, fargs=(img, grid, gridsize,),
frames=10,
interval=interval,
save_count=50)
# remove x and y - axis labels, numbers and ticks
ax.axes.xaxis.set_ticklabels()
ax.axes.yaxis.set_ticklabels()
plt.xticks()
plt.yticks()
# plot the animated output
plt.show()
if __name__ == '__main__':
main()
Here is the function for adding the glider:
def add_glider(i, j, grid):
"""adds a glider with top-left cell at (i, j)"""
glider = np.array([[0, 0, 255],
[255, 0, 255],
[0, 255, 255]])
grid[i:i+3, j:j+3] = glider
It adds a glider in the grid @ position 1, 1
And here is my update function:
def update(frameNum, img, grid, gridsize):
"""Updates the grid every time it is refreshed"""
newgrid = grid.copy()
for i in range(gridsize):
for j in range(gridsize):
# this formula considers the edge/boundary conditions that appear
# every cell has to have 8 neighbouring cells
# to implement this in a grid of size n we simply fold the 4 edges to each parallel edge
# we'll end up with a cylinder first, then with a geometric shape called torus (google it.)
total = int((grid[i, (j - 1) % gridsize] + grid[i, (j + 1) % gridsize] +
grid[(i - 1) % gridsize, j] + grid[(i + 1) % gridsize, j] +
grid[(i - 1) % gridsize, (j - 1) % gridsize] +
grid[(i - 1) % gridsize, (j + 1) % gridsize] +
grid[(i + 1) % gridsize, (j - 1) % gridsize] + grid[
(i + 1) % gridsize, (j + 1) % gridsize]) / 255)
# apply conway's basic rules of the game of life for each cell
if grid[i, j] == ON:
if (total < 2) or (total > 3):
newgrid[i, j] = OFF
else:
if total == 3:
newgrid[i, j] = ON
# update data
img.set_data(newgrid)
grid[:] = newgrid[:]
return img,
However when I run it with the option to have it display the glider, all I see is the following formation...
failedglider_1.png
which swiftly turns into this and becomes static:
failedglider_2.png
... instead of an actual glider as seen in the matrix of add_glider. So it seems that somehow the program adds an unwanted alive cell right at the top. I tried to find where it comes from... but I can't find it.
Does anyone have any clues? I am greatful for all help.
Thanks in advance!
python python-3.x matplotlib conways-game-of-life
python python-3.x matplotlib conways-game-of-life
edited Nov 23 '18 at 10:36
Andy M.
asked Nov 23 '18 at 7:52
Andy M.Andy M.
134
134
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
With some minor fixes to the code from your original post I am able to produce exactly what you wanted. The modified code is listed at the bottom. First frame is shown on the left in the image bellow. After few frames it looks like the image on the right.
So the glider seems to work just fine :)
#!/usr/bin/python
# call with: python3 cgl.py 10 500 1 1
import os
import argparse
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
ON = 255
OFF = 0
def update(frameNum, img, grid, gridsize):
"""Updates the grid every time it is refreshed"""
newgrid = grid.copy()
for i in range(gridsize):
for j in range(gridsize):
# this formula considers the edge/boundary conditions that appear
# every cell has to have 8 neighbouring cells
# to implement this in a grid of size n we simply fold the 4 edges to each parallel edge
# we'll end up with a cylinder first, then with a geometric shape called torus (google it.)
total = int((grid[i, (j - 1) % gridsize] + grid[i, (j + 1) % gridsize] +
grid[(i - 1) % gridsize, j] + grid[(i + 1) % gridsize, j] +
grid[(i - 1) % gridsize, (j - 1) % gridsize] +
grid[(i - 1) % gridsize, (j + 1) % gridsize] +
grid[(i + 1) % gridsize, (j - 1) % gridsize] + grid[
(i + 1) % gridsize, (j + 1) % gridsize]) / 255)
# apply conway's basic rules of the game of life for each cell
if grid[i, j] == ON:
if (total < 2) or (total > 3):
newgrid[i, j] = OFF
else:
if total == 3:
newgrid[i, j] = ON
# update data
grid[:] = newgrid[:]
img.set_data(newgrid)
return img,
def add_glider(i, j, grid):
"""adds a glider with top-left cell at (i, j)"""
glider = np.array([[0, 0, 255],
[255, 0, 255],
[0, 255, 255]])
grid[i:i+3, j:j+3] = glider
def main():
parser = argparse.ArgumentParser(description="Conway's game of life in Python 3")
parser.add_argument('gridsize', type=int, help='Dimension of grid.')
parser.add_argument('interval', type=int, help='Interval.')
parser.add_argument('formationflag', type=bool, help='Predefined formation.')
parser.add_argument('frame', type=int, help='How many frames to animate.')
# get arguments from input function
arguments = parser.parse_args()
# set the arguments
frame = int(arguments.frame)
gridsize = int(arguments.gridsize)
interval = int(arguments.interval)
formation = arguments.formationflag
# if you want to start with a formation:
if formation:
grid = np.zeros(gridsize*gridsize).reshape(gridsize, gridsize)
add_glider(1, 1, grid)
# else display a randopm grid
else:
grid = randomgrid(gridsize)
fig, ax = plt.subplots()
# colormap: black -> alive, white -> dead
img = ax.imshow(grid, cmap='binary', interpolation='nearest')
# # this will be used to save the animation in a later version
ani = animation.FuncAnimation(fig, update, fargs=(img, grid, gridsize,),
frames=frame,
interval=interval,
save_count=50)
# remove x and y - axis labels, numbers and ticks
ax.axes.xaxis.set_ticklabels()
ax.axes.yaxis.set_ticklabels()
plt.xticks()
plt.yticks()
# plot the animated output
plt.show()
if __name__ == '__main__':
main()
print("DONE")
1
funcAnimation is a function of the matplotlib library animation. Sorry, forgot to include the imports in my post - corrected that. Thanks for looking into it though - now I know that the problem seems to be with the funcAnimation parameters.
– Andy M.
Nov 23 '18 at 10:44
Oh cool, I have updated the gist code. Now it works and animates the glider nicely. If this solves the problem consider accepting the answer.
– dsalaj
Nov 23 '18 at 12:18
1
Great! Thanks for your effort! I don't quite understand, why it works if you use argument parsing but not if you get the input via a regular "variable = input(xy)" prompt in the command line...
– Andy M.
Nov 23 '18 at 13:11
@ImportanceOfBeingErnest Good point. The code is now listed in the answer. Thanks. @AndyM. Well not sure why and if that is the case. Only reason why I used argument parsing is because I am familiar with it. I have no idea what yourinput_arguments
does so I couldn't use it. If you return the argument values in correct data type, there should be no problems. I hope it answers your question now.
– dsalaj
Nov 23 '18 at 17:03
1
Thanks! I found the error, There was a problem with my input function. It works now, I marked your question as the solution. Thanks a lot for your help!
– Andy M.
Nov 24 '18 at 7:01
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53442614%2fconways-game-of-life-in-python-3-with-matplotlib-problem-with-displaying-a-fo%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
With some minor fixes to the code from your original post I am able to produce exactly what you wanted. The modified code is listed at the bottom. First frame is shown on the left in the image bellow. After few frames it looks like the image on the right.
So the glider seems to work just fine :)
#!/usr/bin/python
# call with: python3 cgl.py 10 500 1 1
import os
import argparse
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
ON = 255
OFF = 0
def update(frameNum, img, grid, gridsize):
"""Updates the grid every time it is refreshed"""
newgrid = grid.copy()
for i in range(gridsize):
for j in range(gridsize):
# this formula considers the edge/boundary conditions that appear
# every cell has to have 8 neighbouring cells
# to implement this in a grid of size n we simply fold the 4 edges to each parallel edge
# we'll end up with a cylinder first, then with a geometric shape called torus (google it.)
total = int((grid[i, (j - 1) % gridsize] + grid[i, (j + 1) % gridsize] +
grid[(i - 1) % gridsize, j] + grid[(i + 1) % gridsize, j] +
grid[(i - 1) % gridsize, (j - 1) % gridsize] +
grid[(i - 1) % gridsize, (j + 1) % gridsize] +
grid[(i + 1) % gridsize, (j - 1) % gridsize] + grid[
(i + 1) % gridsize, (j + 1) % gridsize]) / 255)
# apply conway's basic rules of the game of life for each cell
if grid[i, j] == ON:
if (total < 2) or (total > 3):
newgrid[i, j] = OFF
else:
if total == 3:
newgrid[i, j] = ON
# update data
grid[:] = newgrid[:]
img.set_data(newgrid)
return img,
def add_glider(i, j, grid):
"""adds a glider with top-left cell at (i, j)"""
glider = np.array([[0, 0, 255],
[255, 0, 255],
[0, 255, 255]])
grid[i:i+3, j:j+3] = glider
def main():
parser = argparse.ArgumentParser(description="Conway's game of life in Python 3")
parser.add_argument('gridsize', type=int, help='Dimension of grid.')
parser.add_argument('interval', type=int, help='Interval.')
parser.add_argument('formationflag', type=bool, help='Predefined formation.')
parser.add_argument('frame', type=int, help='How many frames to animate.')
# get arguments from input function
arguments = parser.parse_args()
# set the arguments
frame = int(arguments.frame)
gridsize = int(arguments.gridsize)
interval = int(arguments.interval)
formation = arguments.formationflag
# if you want to start with a formation:
if formation:
grid = np.zeros(gridsize*gridsize).reshape(gridsize, gridsize)
add_glider(1, 1, grid)
# else display a randopm grid
else:
grid = randomgrid(gridsize)
fig, ax = plt.subplots()
# colormap: black -> alive, white -> dead
img = ax.imshow(grid, cmap='binary', interpolation='nearest')
# # this will be used to save the animation in a later version
ani = animation.FuncAnimation(fig, update, fargs=(img, grid, gridsize,),
frames=frame,
interval=interval,
save_count=50)
# remove x and y - axis labels, numbers and ticks
ax.axes.xaxis.set_ticklabels()
ax.axes.yaxis.set_ticklabels()
plt.xticks()
plt.yticks()
# plot the animated output
plt.show()
if __name__ == '__main__':
main()
print("DONE")
1
funcAnimation is a function of the matplotlib library animation. Sorry, forgot to include the imports in my post - corrected that. Thanks for looking into it though - now I know that the problem seems to be with the funcAnimation parameters.
– Andy M.
Nov 23 '18 at 10:44
Oh cool, I have updated the gist code. Now it works and animates the glider nicely. If this solves the problem consider accepting the answer.
– dsalaj
Nov 23 '18 at 12:18
1
Great! Thanks for your effort! I don't quite understand, why it works if you use argument parsing but not if you get the input via a regular "variable = input(xy)" prompt in the command line...
– Andy M.
Nov 23 '18 at 13:11
@ImportanceOfBeingErnest Good point. The code is now listed in the answer. Thanks. @AndyM. Well not sure why and if that is the case. Only reason why I used argument parsing is because I am familiar with it. I have no idea what yourinput_arguments
does so I couldn't use it. If you return the argument values in correct data type, there should be no problems. I hope it answers your question now.
– dsalaj
Nov 23 '18 at 17:03
1
Thanks! I found the error, There was a problem with my input function. It works now, I marked your question as the solution. Thanks a lot for your help!
– Andy M.
Nov 24 '18 at 7:01
add a comment |
With some minor fixes to the code from your original post I am able to produce exactly what you wanted. The modified code is listed at the bottom. First frame is shown on the left in the image bellow. After few frames it looks like the image on the right.
So the glider seems to work just fine :)
#!/usr/bin/python
# call with: python3 cgl.py 10 500 1 1
import os
import argparse
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
ON = 255
OFF = 0
def update(frameNum, img, grid, gridsize):
"""Updates the grid every time it is refreshed"""
newgrid = grid.copy()
for i in range(gridsize):
for j in range(gridsize):
# this formula considers the edge/boundary conditions that appear
# every cell has to have 8 neighbouring cells
# to implement this in a grid of size n we simply fold the 4 edges to each parallel edge
# we'll end up with a cylinder first, then with a geometric shape called torus (google it.)
total = int((grid[i, (j - 1) % gridsize] + grid[i, (j + 1) % gridsize] +
grid[(i - 1) % gridsize, j] + grid[(i + 1) % gridsize, j] +
grid[(i - 1) % gridsize, (j - 1) % gridsize] +
grid[(i - 1) % gridsize, (j + 1) % gridsize] +
grid[(i + 1) % gridsize, (j - 1) % gridsize] + grid[
(i + 1) % gridsize, (j + 1) % gridsize]) / 255)
# apply conway's basic rules of the game of life for each cell
if grid[i, j] == ON:
if (total < 2) or (total > 3):
newgrid[i, j] = OFF
else:
if total == 3:
newgrid[i, j] = ON
# update data
grid[:] = newgrid[:]
img.set_data(newgrid)
return img,
def add_glider(i, j, grid):
"""adds a glider with top-left cell at (i, j)"""
glider = np.array([[0, 0, 255],
[255, 0, 255],
[0, 255, 255]])
grid[i:i+3, j:j+3] = glider
def main():
parser = argparse.ArgumentParser(description="Conway's game of life in Python 3")
parser.add_argument('gridsize', type=int, help='Dimension of grid.')
parser.add_argument('interval', type=int, help='Interval.')
parser.add_argument('formationflag', type=bool, help='Predefined formation.')
parser.add_argument('frame', type=int, help='How many frames to animate.')
# get arguments from input function
arguments = parser.parse_args()
# set the arguments
frame = int(arguments.frame)
gridsize = int(arguments.gridsize)
interval = int(arguments.interval)
formation = arguments.formationflag
# if you want to start with a formation:
if formation:
grid = np.zeros(gridsize*gridsize).reshape(gridsize, gridsize)
add_glider(1, 1, grid)
# else display a randopm grid
else:
grid = randomgrid(gridsize)
fig, ax = plt.subplots()
# colormap: black -> alive, white -> dead
img = ax.imshow(grid, cmap='binary', interpolation='nearest')
# # this will be used to save the animation in a later version
ani = animation.FuncAnimation(fig, update, fargs=(img, grid, gridsize,),
frames=frame,
interval=interval,
save_count=50)
# remove x and y - axis labels, numbers and ticks
ax.axes.xaxis.set_ticklabels()
ax.axes.yaxis.set_ticklabels()
plt.xticks()
plt.yticks()
# plot the animated output
plt.show()
if __name__ == '__main__':
main()
print("DONE")
1
funcAnimation is a function of the matplotlib library animation. Sorry, forgot to include the imports in my post - corrected that. Thanks for looking into it though - now I know that the problem seems to be with the funcAnimation parameters.
– Andy M.
Nov 23 '18 at 10:44
Oh cool, I have updated the gist code. Now it works and animates the glider nicely. If this solves the problem consider accepting the answer.
– dsalaj
Nov 23 '18 at 12:18
1
Great! Thanks for your effort! I don't quite understand, why it works if you use argument parsing but not if you get the input via a regular "variable = input(xy)" prompt in the command line...
– Andy M.
Nov 23 '18 at 13:11
@ImportanceOfBeingErnest Good point. The code is now listed in the answer. Thanks. @AndyM. Well not sure why and if that is the case. Only reason why I used argument parsing is because I am familiar with it. I have no idea what yourinput_arguments
does so I couldn't use it. If you return the argument values in correct data type, there should be no problems. I hope it answers your question now.
– dsalaj
Nov 23 '18 at 17:03
1
Thanks! I found the error, There was a problem with my input function. It works now, I marked your question as the solution. Thanks a lot for your help!
– Andy M.
Nov 24 '18 at 7:01
add a comment |
With some minor fixes to the code from your original post I am able to produce exactly what you wanted. The modified code is listed at the bottom. First frame is shown on the left in the image bellow. After few frames it looks like the image on the right.
So the glider seems to work just fine :)
#!/usr/bin/python
# call with: python3 cgl.py 10 500 1 1
import os
import argparse
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
ON = 255
OFF = 0
def update(frameNum, img, grid, gridsize):
"""Updates the grid every time it is refreshed"""
newgrid = grid.copy()
for i in range(gridsize):
for j in range(gridsize):
# this formula considers the edge/boundary conditions that appear
# every cell has to have 8 neighbouring cells
# to implement this in a grid of size n we simply fold the 4 edges to each parallel edge
# we'll end up with a cylinder first, then with a geometric shape called torus (google it.)
total = int((grid[i, (j - 1) % gridsize] + grid[i, (j + 1) % gridsize] +
grid[(i - 1) % gridsize, j] + grid[(i + 1) % gridsize, j] +
grid[(i - 1) % gridsize, (j - 1) % gridsize] +
grid[(i - 1) % gridsize, (j + 1) % gridsize] +
grid[(i + 1) % gridsize, (j - 1) % gridsize] + grid[
(i + 1) % gridsize, (j + 1) % gridsize]) / 255)
# apply conway's basic rules of the game of life for each cell
if grid[i, j] == ON:
if (total < 2) or (total > 3):
newgrid[i, j] = OFF
else:
if total == 3:
newgrid[i, j] = ON
# update data
grid[:] = newgrid[:]
img.set_data(newgrid)
return img,
def add_glider(i, j, grid):
"""adds a glider with top-left cell at (i, j)"""
glider = np.array([[0, 0, 255],
[255, 0, 255],
[0, 255, 255]])
grid[i:i+3, j:j+3] = glider
def main():
parser = argparse.ArgumentParser(description="Conway's game of life in Python 3")
parser.add_argument('gridsize', type=int, help='Dimension of grid.')
parser.add_argument('interval', type=int, help='Interval.')
parser.add_argument('formationflag', type=bool, help='Predefined formation.')
parser.add_argument('frame', type=int, help='How many frames to animate.')
# get arguments from input function
arguments = parser.parse_args()
# set the arguments
frame = int(arguments.frame)
gridsize = int(arguments.gridsize)
interval = int(arguments.interval)
formation = arguments.formationflag
# if you want to start with a formation:
if formation:
grid = np.zeros(gridsize*gridsize).reshape(gridsize, gridsize)
add_glider(1, 1, grid)
# else display a randopm grid
else:
grid = randomgrid(gridsize)
fig, ax = plt.subplots()
# colormap: black -> alive, white -> dead
img = ax.imshow(grid, cmap='binary', interpolation='nearest')
# # this will be used to save the animation in a later version
ani = animation.FuncAnimation(fig, update, fargs=(img, grid, gridsize,),
frames=frame,
interval=interval,
save_count=50)
# remove x and y - axis labels, numbers and ticks
ax.axes.xaxis.set_ticklabels()
ax.axes.yaxis.set_ticklabels()
plt.xticks()
plt.yticks()
# plot the animated output
plt.show()
if __name__ == '__main__':
main()
print("DONE")
With some minor fixes to the code from your original post I am able to produce exactly what you wanted. The modified code is listed at the bottom. First frame is shown on the left in the image bellow. After few frames it looks like the image on the right.
So the glider seems to work just fine :)
#!/usr/bin/python
# call with: python3 cgl.py 10 500 1 1
import os
import argparse
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
ON = 255
OFF = 0
def update(frameNum, img, grid, gridsize):
"""Updates the grid every time it is refreshed"""
newgrid = grid.copy()
for i in range(gridsize):
for j in range(gridsize):
# this formula considers the edge/boundary conditions that appear
# every cell has to have 8 neighbouring cells
# to implement this in a grid of size n we simply fold the 4 edges to each parallel edge
# we'll end up with a cylinder first, then with a geometric shape called torus (google it.)
total = int((grid[i, (j - 1) % gridsize] + grid[i, (j + 1) % gridsize] +
grid[(i - 1) % gridsize, j] + grid[(i + 1) % gridsize, j] +
grid[(i - 1) % gridsize, (j - 1) % gridsize] +
grid[(i - 1) % gridsize, (j + 1) % gridsize] +
grid[(i + 1) % gridsize, (j - 1) % gridsize] + grid[
(i + 1) % gridsize, (j + 1) % gridsize]) / 255)
# apply conway's basic rules of the game of life for each cell
if grid[i, j] == ON:
if (total < 2) or (total > 3):
newgrid[i, j] = OFF
else:
if total == 3:
newgrid[i, j] = ON
# update data
grid[:] = newgrid[:]
img.set_data(newgrid)
return img,
def add_glider(i, j, grid):
"""adds a glider with top-left cell at (i, j)"""
glider = np.array([[0, 0, 255],
[255, 0, 255],
[0, 255, 255]])
grid[i:i+3, j:j+3] = glider
def main():
parser = argparse.ArgumentParser(description="Conway's game of life in Python 3")
parser.add_argument('gridsize', type=int, help='Dimension of grid.')
parser.add_argument('interval', type=int, help='Interval.')
parser.add_argument('formationflag', type=bool, help='Predefined formation.')
parser.add_argument('frame', type=int, help='How many frames to animate.')
# get arguments from input function
arguments = parser.parse_args()
# set the arguments
frame = int(arguments.frame)
gridsize = int(arguments.gridsize)
interval = int(arguments.interval)
formation = arguments.formationflag
# if you want to start with a formation:
if formation:
grid = np.zeros(gridsize*gridsize).reshape(gridsize, gridsize)
add_glider(1, 1, grid)
# else display a randopm grid
else:
grid = randomgrid(gridsize)
fig, ax = plt.subplots()
# colormap: black -> alive, white -> dead
img = ax.imshow(grid, cmap='binary', interpolation='nearest')
# # this will be used to save the animation in a later version
ani = animation.FuncAnimation(fig, update, fargs=(img, grid, gridsize,),
frames=frame,
interval=interval,
save_count=50)
# remove x and y - axis labels, numbers and ticks
ax.axes.xaxis.set_ticklabels()
ax.axes.yaxis.set_ticklabels()
plt.xticks()
plt.yticks()
# plot the animated output
plt.show()
if __name__ == '__main__':
main()
print("DONE")
edited Nov 23 '18 at 17:00
answered Nov 23 '18 at 10:00
dsalajdsalaj
6291027
6291027
1
funcAnimation is a function of the matplotlib library animation. Sorry, forgot to include the imports in my post - corrected that. Thanks for looking into it though - now I know that the problem seems to be with the funcAnimation parameters.
– Andy M.
Nov 23 '18 at 10:44
Oh cool, I have updated the gist code. Now it works and animates the glider nicely. If this solves the problem consider accepting the answer.
– dsalaj
Nov 23 '18 at 12:18
1
Great! Thanks for your effort! I don't quite understand, why it works if you use argument parsing but not if you get the input via a regular "variable = input(xy)" prompt in the command line...
– Andy M.
Nov 23 '18 at 13:11
@ImportanceOfBeingErnest Good point. The code is now listed in the answer. Thanks. @AndyM. Well not sure why and if that is the case. Only reason why I used argument parsing is because I am familiar with it. I have no idea what yourinput_arguments
does so I couldn't use it. If you return the argument values in correct data type, there should be no problems. I hope it answers your question now.
– dsalaj
Nov 23 '18 at 17:03
1
Thanks! I found the error, There was a problem with my input function. It works now, I marked your question as the solution. Thanks a lot for your help!
– Andy M.
Nov 24 '18 at 7:01
add a comment |
1
funcAnimation is a function of the matplotlib library animation. Sorry, forgot to include the imports in my post - corrected that. Thanks for looking into it though - now I know that the problem seems to be with the funcAnimation parameters.
– Andy M.
Nov 23 '18 at 10:44
Oh cool, I have updated the gist code. Now it works and animates the glider nicely. If this solves the problem consider accepting the answer.
– dsalaj
Nov 23 '18 at 12:18
1
Great! Thanks for your effort! I don't quite understand, why it works if you use argument parsing but not if you get the input via a regular "variable = input(xy)" prompt in the command line...
– Andy M.
Nov 23 '18 at 13:11
@ImportanceOfBeingErnest Good point. The code is now listed in the answer. Thanks. @AndyM. Well not sure why and if that is the case. Only reason why I used argument parsing is because I am familiar with it. I have no idea what yourinput_arguments
does so I couldn't use it. If you return the argument values in correct data type, there should be no problems. I hope it answers your question now.
– dsalaj
Nov 23 '18 at 17:03
1
Thanks! I found the error, There was a problem with my input function. It works now, I marked your question as the solution. Thanks a lot for your help!
– Andy M.
Nov 24 '18 at 7:01
1
1
funcAnimation is a function of the matplotlib library animation. Sorry, forgot to include the imports in my post - corrected that. Thanks for looking into it though - now I know that the problem seems to be with the funcAnimation parameters.
– Andy M.
Nov 23 '18 at 10:44
funcAnimation is a function of the matplotlib library animation. Sorry, forgot to include the imports in my post - corrected that. Thanks for looking into it though - now I know that the problem seems to be with the funcAnimation parameters.
– Andy M.
Nov 23 '18 at 10:44
Oh cool, I have updated the gist code. Now it works and animates the glider nicely. If this solves the problem consider accepting the answer.
– dsalaj
Nov 23 '18 at 12:18
Oh cool, I have updated the gist code. Now it works and animates the glider nicely. If this solves the problem consider accepting the answer.
– dsalaj
Nov 23 '18 at 12:18
1
1
Great! Thanks for your effort! I don't quite understand, why it works if you use argument parsing but not if you get the input via a regular "variable = input(xy)" prompt in the command line...
– Andy M.
Nov 23 '18 at 13:11
Great! Thanks for your effort! I don't quite understand, why it works if you use argument parsing but not if you get the input via a regular "variable = input(xy)" prompt in the command line...
– Andy M.
Nov 23 '18 at 13:11
@ImportanceOfBeingErnest Good point. The code is now listed in the answer. Thanks. @AndyM. Well not sure why and if that is the case. Only reason why I used argument parsing is because I am familiar with it. I have no idea what your
input_arguments
does so I couldn't use it. If you return the argument values in correct data type, there should be no problems. I hope it answers your question now.– dsalaj
Nov 23 '18 at 17:03
@ImportanceOfBeingErnest Good point. The code is now listed in the answer. Thanks. @AndyM. Well not sure why and if that is the case. Only reason why I used argument parsing is because I am familiar with it. I have no idea what your
input_arguments
does so I couldn't use it. If you return the argument values in correct data type, there should be no problems. I hope it answers your question now.– dsalaj
Nov 23 '18 at 17:03
1
1
Thanks! I found the error, There was a problem with my input function. It works now, I marked your question as the solution. Thanks a lot for your help!
– Andy M.
Nov 24 '18 at 7:01
Thanks! I found the error, There was a problem with my input function. It works now, I marked your question as the solution. Thanks a lot for your help!
– Andy M.
Nov 24 '18 at 7:01
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53442614%2fconways-game-of-life-in-python-3-with-matplotlib-problem-with-displaying-a-fo%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown