/* DEMO DEL JUEGO DE 8 NUMEROS Y UN HUECO
OJO: el nUmero 0 (cero) es el casillero vacIo
si hay mas de un cero, todos ellos son huecos
*/
/* SECCION DE LIBRERIAS */
#include <stdio.h>
#include <stdlib.h>
/* SECCION DE PROTOTIPOS O FIRMAS DE FUNCION */
void Inicializa( void );
void Muestra( void );
int Revisa(int);
void Ciclo( );
int Busca( int Num );
/* SECCION DE VARIABLES GLOBALES */
int MAT[3][3];
/* SECCION DE CODIGO */
int main( int Narg, char **Args)
{
int Num = 0;
Inicializa( );
Muestra( );
Ciclo( );
}
void Ciclo( )
{
int Num = 9;
for( ; Num != 0 ; )
{
printf("Introduce el nUmero a mover: ");
scanf("%d", &Num);
Busca( Num );
Muestra();
}
}
int Busca( int Num )
{
int x, y, bandera = 0;
for(x=0; x<3; x++)
for(y=0; y<3; y++)
{
if ( MAT[x][y] == Num ) // si si lo encontrO
{
if ( x - 1 >= 0 ) // revisa si es vAlido ir hacia arriba
{
if ( MAT[x-1][y] == 0 ) // hay un cero arriba?
{
printf("ARR_MAT[x][y]=%d\tN=%d\t x=%d\ty=%d\n", MAT[x][y], Num, x, y);
MAT[x-1][y] = MAT[x][y];
MAT[x][y] = 0;
bandera = 1;
printf("hacia arriba\n");
}
}
if ( x + 1 <= 2 ) // revisa si es vAlido ir hacia abajo
{
printf("ABA_MAT[x][y]=%d\tN=%d\t x=%d\ty=%d\n", MAT[x][y], Num, x, y);
if ( MAT[x+1][y] == 0 ) // hay un cero abajo?
{
MAT[x+1][y] = MAT[x][y];
MAT[x][y] = 0;
bandera = 1;
printf("hacia abajo\n");
}
}
if ( y - 1 >= 0 ) // revisa si es vAlido ir hacia la izquierda
{
if ( MAT[x][y-1] == 0 ) // hay un cero a la izquierda?
{
MAT[x][y-1] = MAT[x][y];
MAT[x][y] = 0;
bandera = 1;
printf("hacia izquierda\n");
}
}
if ( y + 1 <= 2 ) // revisa si es vAlido ir hacia la derecha
{
if ( MAT[x][y+1] == 0 ) // hay un cero a la derecha?
{
MAT[x][y+1] = MAT[x][y];
MAT[x][y] = 0;
bandera = 1;
printf("hacia la derecha\n");
}
}
}
if ( bandera) return ;
}
}
int Revisa(int Num)
{
int x, y;
for(x=0; x<3; x++)
for(y=0; y<3; y++)
if ( MAT[x][y] == Num ) return 1;
return 0;
}
void Inicializa( )
{
int x,y, Num, Intentos=0;
srand( (unsigned int)time( NULL ) );
for(x=0; x<3; x++)
for(y=0; y<3; y++)
{
Intentos=0;
etiqueta_1:
Num = rand( ) % 9;
etiqueta_2:
if ( ! Revisa(Num) )
{if ( Num < 9 ) MAT[x][y] = Num;}
else if (++Intentos<3) goto etiqueta_1;
else { Num++; goto etiqueta_2; }
}
}
void Muestra( )
{
int x,y;
char LINEA[50];
for(x=0; x<3; x++)
{
for(y=0; y<3; y++)
printf("%d\t", MAT[x][y]);
printf("\n");
}
}