es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Animación simple para el Juego de la Vida de Conway con FuncAnimation.

He hecho un programa simple del Juego de la Vida de Conway en Python y necesito ayuda para hacer una animación con matplotlib porque, para ser honesto, estoy muy perdido y no logro entender cómo se hace.

Mi código se ve así:

import matplotlib.pyplot as plt
import numpy as np

def initialize(size):
    grid = np.random.choice([0, 1], size*size, p=[0.8, 0.2]).reshape(size, size)
    plt.imshow(grid)
    plt.show(block=False)
    plt.pause(0.2)
    return grid

def conway_step(grid, size):
    new_grid = np.zeros_like(grid)
    for x in range(size):
        for y in range(size):
            total = sum([grid[(x+i) % size, (y+j) % size] for i in range(-1, 2) for j in range(-1, 2)])
            if grid[x, y] == 1 and total-1 in (2, 3):
                new_grid[x, y] = 1
            elif grid[x, y] == 0 and total == 3:
                new_grid[x, y] = 1
            else:
                new_grid[x, y] = 0
    grid = np.copy(new_grid)
    return grid

def conway(random=True, size=100):
    grid = initialize(size)
    for i in range(30):
        grid = conway_step(grid, size)
        plt.imshow(grid)
        plt.show(block=False)
        plt.pause(0.2)
    return

if __name__ == "__main__":
    conway(size=100)

Esto funciona bien, pero me gustaría implementarlo como una animación y posiblemente obtener un archivo mp4. He intentado algo así:

def conway(size):
    grid = initialize(size)
    fig, ax = plt.subplots()
    img = ax.imshow(grid)
    ani = animation.FuncAnimation(fig, conway_step, fargs=(grid, size))
    plt.show()

Pero no funciona. ¿Alguna ayuda?

Tags:  , , ,

Answer

  1. Avatar for davy.ai

    Parece que estás tratando de crear una animación del Juego de la Vida de Conway usando matplotlib. Para hacer esto, necesitarás utilizar la función animation.FuncAnimation. Esta función toma una figura, una función para llamar en cada fotograma, y cualquier argumento que la función necesite.

    En tu código, tienes la función conway_step, que toma la cuadrícula y el tamaño como argumentos. Necesitarás pasar estos argumentos a la función animation.FuncAnimation. Puedes hacer esto agregando fargs=(grid, size) al final de la llamada a la función.

    También puedes guardar la animación como un archivo mp4 agregando ani.save('nombre_archivo.mp4') después de la línea plt.show().

    Aquí hay un ejemplo de cómo debería verse tu código:

    def conway(size):
        grid = initialize(size)
        fig, ax = plt.subplots()
        img = ax.imshow(grid)
        ani = animation.FuncAnimation(fig, conway_step, fargs=(grid, size))
        plt.show()
        ani.save('nombre_archivo.mp4')
    

    ¡Espero que esto ayude!

Comments are closed.