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.
Deja un comentario Cancelar la respuesta
Contacto
Categorías
- Programación (1)
- Tutoriales (14)
- Utilidades (1)
- Vídeos (3)
Entradas mensuales
- junio 2010 (1)
- abril 2010 (2)
- marzo 2010 (1)
- enero 2010 (3)
- diciembre 2009 (2)
- noviembre 2009 (5)
- octubre 2009 (2)
- septiembre 2009 (1)
ELPAÍS.com – Tecnología
- Un periodista que viajó a Milán para cubrir el Valencia-Atalanta, positivo por coronavirus
- Mapa de la expansión y claves para entender el coronavirus de Wuhan
- El turismo italiano se resiente; España mira expectante
- “La magnitud del problema del coronavirus no será diferente a una gripe”
- Seis italianos encerrados por partida doble
- Trump nombra al vicepresidente Pence a cargo de la crisis del coronavirus
- El coronavirus de Wuhan | Japón cerrará todos sus centros escolares hasta fin de marzo
- El Gobierno salva el primer escollo de los Presupuestos gracias a ERC
- La mesa de diálogo se reunirá mensualmente y los acuerdos serán “en el marco de la seguridad jurídica”
- Así avanzan las encuestas en Galicia y País Vasco
3Djuegos – Videojuegos
- Tráiler de Mullet MadJack
- Tráiler de anuncio de Big Helmet Heroes
- Tráiler de lanzamiento de Robobeat
- Tráiler de lanzamiento de The Land Beneath Us
- Tráiler de lanzamiento de Homeworld 3
- Tráiler gameplay de The Casting of Frank Stone
- Tráiler de Biomutant para Nintendo Switch
- Tráiler gameplay del Joker en MultiVersus
- Tráiler de lanzamiento de Fabledom
- Tráiler de Realm of Ink. Demo disponible
Deseo aprender – Curso de Word
- Se ha producido un error; es probable que la fuente esté fuera de servicio. Vuelve a intentarlo más tarde.
Deseo aprender – Curso de excel
- Se ha producido un error; es probable que la fuente esté fuera de servicio. Vuelve a intentarlo más tarde.
Deseo aprender – Curso de Powerpoint
- Se ha producido un error; es probable que la fuente esté fuera de servicio. Vuelve a intentarlo más tarde.
Estadisticas
- 52.617 visitas
Pero si esto esta petao de errores!
esta muy bien muchas gracias!!!
lo he modificado bastate si quieres te lo paso
lo agradecería, así el resto de lectores podrán disponer de una alternativa al que he puesto yo (que está bastante simplificado).
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
a la perdon me confundi con tu nombre sorry…….
hey Cristian sera que me lo puedes pasar tambien a mi si.. mi correo es jrft_9@hotmail.com
eii, pues a mi si que me gustari averlo para comparar. porfavor!
Saludos, a mi tambien me gustartia tener tu punto de vista, si fueras tan fino de envirmelo a guiller2k@hotmail.com, gracias
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!
lo necesito si podrías mandármelo a josias_drc@hotmail.com
pasalo. my coorreo es deathumbreon@hotmail.com
Podrías pasarme el código por favor, si serias tan amable a mi correo daysua25@gmail.com
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
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
si me lo puedes psasr a mi tambien ke lo necesito urgente si gracias pila hai este es mi korrero ronaldleon14@hotmail.com
Cristian,como alternativa serias tan amable de pasarme tu codigo, mi correo es gibranmorales@hotmail.com
Me podría pasas tu código??
Qué amable!!
a_siddhartha@hotmail.com
ni puta idea de programar pendejos!
me puedes pasar el codigo am i tambien ? porfavor y muchas gracias
d:_jurado391@hotmail.com
me lo puedes pasar marze-1@hotmail.com
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
hola! podrías pasarme, por favor la alternativa a este juego? gracias de antemano! 🙂
prl1668@gmail.com
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?
PASAMELOOO HAHAHAHAHAHAHA v.sanchez00@hotmail.com
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!
yo también lo necesito si podrías mandármelo a josias_drc@hotmail.com
alguien me podría pasar el codigo, missael_br@hotmail.com
me lo podrian pasar !! madrigal_@live.com.mx
me lo pasarian porfavor!!!! julsss11@hotmail.com
muchas gracias!!!!
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?
podria pasarme alguien porfavor el codigo sinb errores;
a steve_jat@hotmail.com
buenas noches pana sera que me puedes pasar el codigo sin erros por favo este esx mi correo vgomez665mc@gmail.com disculpa la molestia
Buenas noches me podrías pasar el código sin errores por favor!! Mi correo es: pablo_terroba@hotmail.com
Muchas gracias
Hola me podrias pasar el codigo modificado porfavor? pablo_menda_martinez@hormail.com
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
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.
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.
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.
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.
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.
hola, no me funciona el código. Tienen otro que funcione bien?
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.
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.
Algún otro lugar donde encontrar él código?
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?
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.
If you are going for best contents like me,
simply pay a visit this web site every day as it offers
quality contents, thanks
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
alguien me puede mandar el codigo porfa mi correo es warriosnfs@gmal.com
warriosnfs@gmail.com
warriosnfs@gmail.com ese es