Inicio > Programación > El juego de la vida – Lenguaje de programación C

El juego de la vida – Lenguaje de programación C


El juego de la vida es un autómata celular diseñado por el matemático británico John Horton Conway en el año 1970.
Este simula en cierta manera el mundo en el que vivimos, nos encontramos con una cuadricula de tamaño predeterminado (por nosotros) en el que cada casilla puede tener dos estados, vivo o muerto, este estado viene determinado por las casillas circundantes mediante unas sencillas reglas.

  • Una casilla muerta con exactamente 3 casillas vecinas vivas «nace» (el siguiente turno estará viva).
  • Una casilla viva con 2 ó 3 casillas vecinas vivas sigue viva, si solo tiene 1 vecino muere por soledad, si tiene mas de 3 vecinos muere por superpoblación.

En clase de programación se propuso como ejercicio realizar el juego de la vida en C, a continuación os dejo el código de mi programa.
En el juego se pueden formar múltiples formas, algunas variables, otras intermitentes y  otras fijas e inamovibles, en este programa solo se ha realizado un «bloque» principal pues es mi primera experiencia programando en tablas bidimensionales, el juego original estaría formado por docenas de bloques que irían evolucionando independientemente, se fusionarían o desaparecerían, como por ejemplo, podréis observar en el gif de arriba, para mas información, tenéis la Wikipedia.

#include<stdio.h>
#include<conio.h>
#define X 20    //el numero de filas declarado en una constante
#define Y 20   //el numero de columnas declarado en una constante
int main()
{
//declaración de variables
int ix, iy, ixd, ixe, iys, iyi, vius; //las variables ixd(ix derecha), iys(iy superior).etc..
//sirven para comprobar las casillas
alrededor de la casilla que se examina
char mundo[X][Y], estado[X][Y], opc;  //una tabla se mostrará, en la otra se aplicarán los cambios
//inicializar tabla mundo
for(ix=0; ix<X; ix++)
    {
        for(iy=0; iy<Y; iy++)
        {
            mundo[ix][iy]=' ';
        }
    }
//mostrar un menú y escoger el estado inicial de nuestro juego de la vida
printf("Selecciona el estado inicial:\na)bloque\nb)barco\nc)parpadeador\nd)sapo\ne)planeador\nf)
nave ligera\n");

do  //mientras la opción no sea valida, seguirá leyendo hasta dar con una letra valida
{
    scanf("%c", &opc);
}while(opc<'a' || opc>'f');

//situar estado inicial
switch(opc)
{
   case 'a':mundo[0][0]='X';mundo[0][1]='X';mundo[1][0]='X';mundo[1][1]='X';break;
   case 'b':mundo[0][0]='X';mundo[0][1]='X';mundo[1][0]='X';mundo[1][2]='X';mundo[2][1]='X';break;
   case 'c':mundo[0][0]='X';mundo[0][1]='X';mundo[0][2]='X';break;
   case 'd':mundo[0][1]='X';mundo[0][2]='X';mundo[0][3]='X';mundo[1][0]='X';mundo[1][1]='X';mundo[1][2]='X';break;
   case 'e':mundo[0][0]='X';mundo[0][1]='X';mundo[0][2]='X';mundo[1][0]='X';mundo[2][1]='X';break;
   case 'f':mundo[0][1]='X';mundo[0][4]='X';mundo[1][0]='X';mundo[2][0]='X';mundo[2][4]='X';mundo[3][0]='X';mundo[3][1]='X';mundo[3][2]='X';mundo[3][3]='X';break;
   default: printf("error, ha de ser entre 'a' i 'f'");
}
//bucle infinito, dado que el juego de la vida no tiene final
    while(1==1)
    {   //for para mostrar la tabla mundo
        for(ix=0; ix<X; ix++)
        {
            for(iy=0; iy<Y; iy++)
            {
                printf("%c",mundo[ix][iy]);
            }
            printf("\n");
        }
        system("pause");  //pausa el juego, hasta que pulsemos una tecla, no mostrará el siguiente estado de la tabla
        //recorrido total para comprobar si ha llegado al limite de la tabla
        for(ix=0; ix<X; ix++)
        {
            for(iy=0; iy<Y; iy++)
            {
                vivos=0;

                if(ix>=X-1)
                    ixd=0;
                else
                    ixd=ix+1;

                if(iy>=Y-1)
                    iyi=0;
                else
                    iyi=iy+1;

                if(ix<=0)
                    ixe=X-1;
                else
                    ixe=ix-1;

                if(iy<=0)
                    iys=Y-1;
                else
                    iys=iy-1;

                //comprobación para saber si los vecinos están vivos o muertos
                if(mundo[ixd][iy]=='X')    vivos++;
                if(mundo[ixe][iy]=='X')    vivos++;
                if(mundo[ix][iys]=='X')    vivos++;
                if(mundo[ix][iyi]=='X')    vivos++;
                if(mundo[ixd][iys]=='X')   vivos++;
                if(mundo[ixe][iys]=='X')   vivos++;
                if(mundo[ixd][iyi]=='X')   vivos++;
                if(mundo[ixe][iyi]=='X')   vivos++;

                //condicional para determinar si la casilla vive o muere
                if(mundo[ix][iy]=='X')
                {
                    // esta vivo
                    if(vivos<=1 || vivos>3)
                    {
                        estado[ix][iy]=' ';
                    }else{
                            estado[ix][iy]='X';
                    }

                }else
                {
                    // esta muerto
                    if(vivos==3)
                    {
                        estado[ix][iy]='X';
                    }else{

                        estado[ix][iy]=' ';
                    }
                }

            }// final del for iy

        } // final del for ix

        //guardamos la tabla estado en la tabla mundo, para que la próxima vez que entre en el bucle se muestre actualizada
        for(ix=0; ix<X; ix++)
        {
            for(iy=0; iy<Y; iy++)
            {
                mundo[ix][iy]=estado[ix][iy];
            }
        }  //final del for para guardar la tabla estado en la tabla mundo

    } //final del bucle

}

#include<stdio.h>

#include<conio.h>

#define X 20

#define Y 20

int main()

{

//variables

int ix, iy, ixd, ixe, iys, iyi, vius, aux;

char mundo[X][Y], estado[X][Y], opc;

//netejar mundo

for(ix=0; ix<X; ix++)

{

for(iy=0; iy<Y; iy++)

{

mundo[ix][iy]=’ ‘;

}

}

//mostrar menu i escollir estado inicial

printf(«Selecciona l’estado inicial:\na)bloc\nb)barca\nc)semafor\nd)gripau\ne)planador\nf)astronau\n»);

 

do

{

scanf(«%c», &opc);

}while(opc<‘a’ || opc>’f’);

 

//situar estado inicial

switch(opc)

{

case ‘a’:mundo[0][0]=’X’;mundo[0][1]=’X’;mundo[1][0]=’X’;mundo[1][1]=’X’;break;

case ‘b’:mundo[0][0]=’X’;mundo[0][1]=’X’;mundo[1][0]=’X’;mundo[1][2]=’X’;mundo[2][1]=’X’;break;

case ‘c’:mundo[0][0]=’X’;mundo[0][1]=’X’;mundo[0][2]=’X’;break;

case ‘d’:mundo[0][1]=’X’;mundo[0][2]=’X’;mundo[0][3]=’X’;mundo[1][0]=’X’;mundo[1][1]=’X’;mundo[1][2]=’X’;break;

case ‘e’:mundo[0][0]=’X’;mundo[0][1]=’X’;mundo[0][2]=’X’;mundo[1][0]=’X’;mundo[2][1]=’X’;break;

case ‘f’:mundo[0][1]=’X’;mundo[0][4]=’X’;mundo[1][0]=’X’;mundo[2][0]=’X’;mundo[2][4]=’X’;mundo[3][0]=’X’;mundo[3][1]=’X’;mundo[3][2]=’X’;mundo[3][3]=’X’;break;

default: printf(«error, ha de ser entre ‘a’ i ‘f'»);

}

//proces

//bucle infinit

while(1==1)

{   //for per mostra la taula mundo

for(ix=0; ix<X; ix++)

{

for(iy=0; iy<Y; iy++)

{

printf(«%c»,mundo[ix][iy]);

}

printf(«\n»);

}

system(«pause»);

//recorregut total per comprobar si ha arrivat al limit del tauler

for(ix=0; ix<X; ix++)

{

for(iy=0; iy<Y; iy++)

{

vius=0;

 

if(ix>=X-1)

ixd=0;

else

ixd=ix+1;

 

if(iy>=Y-1)

iyi=0;

else

iyi=iy+1;

 

if(ix<=0)

ixe=X-1;

else

ixe=ix-1;

 

if(iy<=0)

iys=Y-1;

else

iys=iy-1;

 

//comprobació de si els veins estan vius o morts

if(mundo[ixd][iy]==’X’)    vius++;

if(mundo[ixe][iy]==’X’)    vius++;

if(mundo[ix][iys]==’X’)    vius++;

if(mundo[ix][iyi]==’X’)    vius++;

if(mundo[ixd][iys]==’X’)   vius++;

if(mundo[ixe][iys]==’X’)   vius++;

if(mundo[ixd][iyi]==’X’)   vius++;

if(mundo[ixe][iyi]==’X’)   vius++;

 

//condicional per determinar si la casella viu o mor

if(mundo[ix][iy]==’X’)

{

// esta viu

if(vius<=1 || vius>3)

{

estado[ix][iy]=’ ‘;

}else{

estado[ix][iy]=’X’;

}

 

 

}else

{

// esta mort

if(vius==3)

{

estado[ix][iy]=’X’;

}else{

 

estado[ix][iy]=’ ‘;

}

}

 

}// for iy

 

} // for ix

 

//guardem la taula estado amb l’estado actual a la taula mundo, per a que la seguent vegada que entri al bucle pugi mostrarla actualitzada

for(ix=0; ix<X; ix++)

{

for(iy=0; iy<Y; iy++)

{

mundo[ix][iy]=estado[ix][iy];

}

}

 

}

 

return 0;

 

}

Por motivos de fomatado de texto, es imposible mostrar correctamente todo el código sin que se excedan los margenes, dado que considero que realizar saltos de linea podría dificultar la lectura del código, adjunto documento de texto para que podáis descargaros el código cómodamente y así compilarlo vosotros mismos.

Agradecería el gesto de comunicar aquellos posibles errores detectados en el código, para así facilitar-les la vida a los lectores.

  1. ER Progamao
    29/10/2010 a las 07:52

    Pero si esto esta petao de errores!

  2. cristian
    01/02/2011 a las 18:45

    esta muy bien muchas gracias!!!

  3. cristian
    01/02/2011 a las 18:46

    lo he modificado bastate si quieres te lo paso

    • 02/02/2011 a las 18:59

      lo agradecería, así el resto de lectores podrán disponer de una alternativa al que he puesto yo (que está bastante simplificado).

    • Laura
      18/10/2011 a las 04:45

      Hola cristina sera que me puedes enviar el codigo a la si porfis…. mi corre es
      l-m_1992@hotmail.com …… te lo agradeceria mucho

      • Laura
        18/10/2011 a las 04:46

        a la perdon me confundi con tu nombre sorry…….

    • Jenny
      18/10/2011 a las 05:07

      hey Cristian sera que me lo puedes pasar tambien a mi si.. mi correo es jrft_9@hotmail.com

    • Carlos
      27/10/2011 a las 14:12

      eii, pues a mi si que me gustari averlo para comparar. porfavor!

    • elGuiller
      29/10/2011 a las 19:49

      Saludos, a mi tambien me gustartia tener tu punto de vista, si fueras tan fino de envirmelo a guiller2k@hotmail.com, gracias

    • Jairo
      04/07/2012 a las 02:02

      URGENTE, porfa si no es mucho abuso sera que me pasas el nuevo codigo, necesito entregar esto como proyecto mas tardar para el domingo 8/07/2012 mi correo es jilpm@hotmail.com de ante mano gracias amigo!

    • Anónimo
      24/01/2013 a las 01:09

      lo necesito si podrías mandármelo a josias_drc@hotmail.com

    • an
      26/09/2015 a las 19:06

      pasalo. my coorreo es deathumbreon@hotmail.com

    • Daisy Suárez
      19/10/2018 a las 16:11

      Podrías pasarme el código por favor, si serias tan amable a mi correo daysua25@gmail.com

    • Anónimo
      07/07/2021 a las 10:33

      Cristian lo necesito para aprobar la asignatura y tengo margen de aqui hasta el 07/10/2021. Se que es muy tarde y han pasado muchos años pero mi correo es salahnose@gmail.com

  4. don josep
    22/08/2011 a las 10:22

    Ola Cristian!
    necesito k me pases el codigo pero sin errores y me gustaria si mo dificas la entrada y salida y hacerla con ficheros
    pasamelo a josep.az@hotmail.com

  5. 25/10/2011 a las 13:00

    si me lo puedes psasr a mi tambien ke lo necesito urgente si gracias pila hai este es mi korrero ronaldleon14@hotmail.com

  6. Anónimo
    13/11/2011 a las 00:25

    Cristian,como alternativa serias tan amable de pasarme tu codigo, mi correo es gibranmorales@hotmail.com

  7. Anónimo
    17/11/2011 a las 22:28

    Me podría pasas tu código??

    Qué amable!!

    a_siddhartha@hotmail.com

  8. 25/11/2011 a las 11:53

    ni puta idea de programar pendejos!

  9. Anónimo
    30/11/2011 a las 01:34

    me puedes pasar el codigo am i tambien ? porfavor y muchas gracias
    d:_jurado391@hotmail.com

  10. Anónimo
    04/12/2011 a las 14:14

    me lo puedes pasar marze-1@hotmail.com

  11. emii
    07/12/2011 a las 14:51

    HOLA!!!! buens dias si no es mucha molestia tambien me interesa el codigo…¿me lo puedes enviar a mi correo?…. la_bb_706@hotmail.com ……por favor y muchas gracias

  12. lo necesito urgente
    09/12/2011 a las 19:24

    hola! podrías pasarme, por favor la alternativa a este juego? gracias de antemano! 🙂
    prl1668@gmail.com

  13. Anónimo
    12/12/2011 a las 12:41

    hola jenny laura y cristian soy G.J y me gustaria que me pasaseis el programilla este mas que nada para comparar con el mio. Gracias
    PD: SE JUEGA CON DADOS NO?

  14. Anónimo
    29/06/2012 a las 00:38

    PASAMELOOO HAHAHAHAHAHAHA v.sanchez00@hotmail.com

  15. Anónimo
    04/07/2012 a las 02:01

    URGENTE, porfa si no es mucho abuso sera que me pasas el nuevo codigo, necesito entregar esto como proyecto mas tardar para el domingo 8/07/2012 mi correo es jilpm@hotmail.com de ante mano gracias amigo!

  16. Anónimo
    24/01/2013 a las 00:56

    yo también lo necesito si podrías mandármelo a josias_drc@hotmail.com

  17. Israel
    30/03/2013 a las 19:46

    alguien me podría pasar el codigo, missael_br@hotmail.com

  18. victor
    10/04/2013 a las 16:32

    me lo podrian pasar !! madrigal_@live.com.mx

  19. Anónimo
    30/04/2013 a las 13:42

    me lo pasarian porfavor!!!! julsss11@hotmail.com
    muchas gracias!!!!

  20. 03/05/2013 a las 02:51

    I drop a leave a response when I especially
    enjoy a post on a website or I have something to add to the conversation.
    It is caused by the passion communicated in the post I looked at.
    And after this article El juego de la vida –
    Lenguaje de programación C | Mi Blog Curricular. I
    was excited enough to leave a comment 😉 I do have a couple of questions for
    you if it’s allright. Is it only me or does it look like some of these responses come across as if they are coming from brain dead individuals? 😛 And, if you are writing at additional places, I’d like
    to keep up with everything fresh you have to post. Could you make a list all of your communal pages
    like your linkedin profile, Facebook page or
    twitter feed?

  21. or al
    09/08/2013 a las 11:12

    podria pasarme alguien porfavor el codigo sinb errores;

    a steve_jat@hotmail.com

  22. victor
    20/11/2013 a las 00:48

    buenas noches pana sera que me puedes pasar el codigo sin erros por favo este esx mi correo vgomez665mc@gmail.com disculpa la molestia

  23. Pablo
    24/11/2013 a las 21:31

    Buenas noches me podrías pasar el código sin errores por favor!! Mi correo es: pablo_terroba@hotmail.com

    Muchas gracias

  24. 17/01/2014 a las 11:51

    Hola me podrias pasar el codigo modificado porfavor? pablo_menda_martinez@hormail.com

  25. 08/09/2014 a las 07:01

    Unquestionably believe that which you stated. Your favourite
    reason appeared to be on the web the easiest thing to
    be mindful of. I say to you, I definitely get irked
    whilst other people consider worries that they plainly don’t understand
    about. You managed to hit the nail upon the highest as well as outlined out the whole thing with no need side effect , other
    folks can take a signal. Will probably be back to get more.
    Thanks

  26. 08/09/2014 a las 10:01

    It’s not my first time to go to see this site, i am
    visiting this site dailly and take nice data from here daily.

  27. 09/09/2014 a las 02:22

    I loved as much as you will receive carried out right here.
    The sketch is tasteful, your authored material stylish.
    nonetheless, you command get got an shakiness over that you wish be delivering the following.
    unwell unquestionably come more formerly again since exactly
    the same nearly very often inside case you shield this increase.

  28. 14/10/2014 a las 16:59

    Right now over 900 million folks in India own a cell
    phone and are in a position to acquire bulk SMS. Firms and organisations the planet more than have realised the huge potential of interacting with the clients, suppliers and
    staff employing Bulk SMS. Bulk SMS in Indore just includes sending
    out large volumes of text messages and conveying the concept 1 wants to convey at as soon as.

    We at BulkSMSIndore.com constantly attempt for producing the most of the
    possible that this technology has.

    BulkSMSIndore.com is a leading SMS Advertising support supplier providing SMS
    conversation solutions. The Bulk SMS in Indore gateway reaches across
    borders and connects to all Indian cellular networks.

    Bulk SMS Indore’s only motto is to supply a high high
    quality messaging service 24X7X365 that permits the consumers to swiftly
    marketise & advertise their tips, products and businesses.

    Confirmed to offer provider at quite affordable price in contrast to other individuals, Bulk SMS Indore is the
    no.1 Bulk SMS service provider in India that offers in low-cost and premium SMS Remedies.

    We are a perfect blend of Outsourced Advertising & Affiliate Advertising which leaves our consumer awestruck and gives increased stages of customer
    delight not only fulfillment.

    Outsourced Advertising is at the forefront of this notion, offering operating solutions for both companies and
    conclude customers to facilitate the Wi-fi Internet and cell technologies,
    which are springing up about us. As our existing flagship merchandise, our
    SMS remedies are currently being utilized in numerous methods to drive new organization designs and offer corporate
    options.

    Affiliate Marketing continues to be the spine of this concept, our
    flexibly attentive staff functions 24X7 toward the accomplishment of our clients’ goods,
    solutions or notion that our clientele want to convey
    to their audience.

    Our function is to provide practical remedies around today’s technological innovation and to
    make it long term evidence and make use of new technology
    as it arrives.

    Most of our solutions are produced in-house, or with third party technique integration.
    Because of this, our understanding of the technologies permits Outsourced Marketing &
    Affiliate Advertising and marketing to speedily and professionally
    give final results to the two organizations and end end users.

    As we discuss about our options, we render companies by means of several equipment like Bulk SMS (Marketing & Transactional), Voice SMS, WhatsApp Posts,
    Quick Code, Lengthy Code, Mass Mail, Skipped Get in touch with Warn (MCA), Interactive Voice Reaction (IVR),
    Toll Totally free Nos. which spans through Non-DND to DND mobile
    numbers to primary inbox mail delivery to guide era to suggestions recording to sharing the information to
    perform surveys to search for market enlargement,
    focusing on, segmentation, differentiation & integration to ultimately achieve
    the increment in total product sales.

  29. 04/05/2015 a las 05:30

    May I simply say what a relief to uncover someone that genuinely
    knows what they are talking about on the net.
    You actually know how to bring an issue to light and make it important.
    More and more people really need to check this out and understand this side of your story.
    I was surprised that you aren’t more popular because you
    surely have the gift.

  30. playbox movie
    22/11/2015 a las 10:01

    Hello I am so thrilled I found your site, I really found you by accident,
    while I was browsing on Google for something else, Nonetheless
    I am here now and would just like to say kudos for a marvelous post and a all round exciting blog (I also love the theme/design), I don’t have time
    to browse it all at the minute but I have bookmarked
    it and also added your RSS feeds, so when I have time I will be back
    to read more, Please do keep up the fantastic work.

  31. Anónimo
    23/03/2016 a las 03:14

    hola, no me funciona el código. Tienen otro que funcione bien?

  32. 18/12/2016 a las 08:11

    I think that what you wrote was very reasonable. But, think
    on this, what if you added a little information? I ain’t suggesting
    your content isn’t solid., but what if you added
    something that makes people desire more? I mean El juego de la vida – Lenguaje
    de programación C | Mi Blog Curricular is a little vanilla.
    You might look at Yahoo’s front page and see how they create article headlines to grab viewers to open the links.

    You might add a video or a picture or two to grab readers excited about what you’ve written.
    In my opinion, it would bring your blog a little
    livelier.

  33. 09/01/2018 a las 07:04

    naturally like your website however you have to check
    the spelling on several of your posts. Many of them are rife with spelling issues and I
    find it very bothersome to tell the reality then again I’ll definitely come again again.

  34. 07/02/2018 a las 23:54

    Algún otro lugar donde encontrar él código?

  35. 04/07/2018 a las 06:41

    Thank you, I have recently been looking for info about this topic for a long time and yours is the greatest
    I’ve came upon till now. However, what in regards to the bottom line?

    Are you certain about the supply?

  36. 06/11/2018 a las 06:58

    It is truly a nice and helpful piece of info. I amm satisfied that you
    simply shared this useful information with us.

    Please keep us upp to date like this. Thank you for sharing.

  37. 20/10/2019 a las 14:32

    If you are going for best contents like me,
    simply pay a visit this web site every day as it offers
    quality contents, thanks

  38. Anónimo
    10/12/2019 a las 02:20

    muchas gracias amigo, me ha servido de mucha ayuda. Solo he tenido que cambiar una variable y unir alguna línea de código. Funciona perfecto. Eres un crack

  1. 19/04/2018 a las 18:05
  2. 09/05/2018 a las 21:53

Deja un comentario