hi i have a program here the 15 puzzle my problem is that im having a hard time makeing a random function the right way and also thinking of a way to make so that the program will not go out of the bounderies here my code
#include <stdio.h>
void displayArrayOfInt(int board[], int size);
void swap(int *a, int *b);
int isFinish(int board[], int size);
void moveup(int board[], int size);
void movedown(int board[],int size);
void moveleft(int board[],int size);
void moveright(int board[],int size);
int main()
{
char m, d;
int board[] = {1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 0};
int isMatch;
int i;
do
{
displayArrayOfInt(board, 15);
printf(" Press w for up \n\n");
printf(" Press s for down \n\n");
printf(" Press a for left \n\n");
printf(" Press d for right \n\n");
fflush(stdin);
scanf("%c",&m);
switch(m)
{
case 'w':
{
moveup(board, 15);
}
break;
case 's':
{
movedown(board, 15);
}
break;
case 'a':
{
moveleft(board, 15);
}
break;
case 'd':
{
moveright(board, 15);
}
break;
printf(" \n");
}
isMatch = isFinish(board, 15);
if(isMatch == 1)
{
displayArrayOfInt(board, 15);
printf("Congratulations You Won\n\n");
}
else
{
printf("Try Again\n\n");
}
}while(isMatch != 1);
return 0;
}
void displayArrayOfInt(int board[], int size)
{
printf("---------------------------------\n");
printf("| %2d | %2d | %2d | %2d |\n",board[0],board[1],board[2],board[3]);
printf("| %2d | %2d | %2d | %2d |\n",board[4],board[5],board[6],board[7]);
printf("| %2d | %2d | %2d | %2d |\n",board[8],board[9],board[10],board[11]);
printf("| %2d | %2d | %2d | %2d |\n",board[12],board[13],board[14],board[15]);
printf("---------------------------------\n");
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int isFinish(int board[], int size)
{
int ref[15];
int i;
for(i = 0; i < size; i++)
{
ref[i] = (i + 1) % 16;
}
for(i = 0; i < size; i++)
{
if(board[i] != ref[i])
{
return 0;
}
}
return 1;
}
void moveup(int board[],int size)
{
int i;
for(i = 0; i <= 15; i++)
{
if(board[i] == 0)
{
swap(&board[i], &board[i-4]);
break;
}
}
}
void movedown(int board[], int size)
{
int i;
for(i = 0; i <= 15; i++)
{
if(board[i] == 0)
{
swap(&board[i], &board[i+4]);
break;
}
}
}
void moveleft(int board[],int size)
{
int i;
for(i = 0; i <= 15; i++)
{
if(board[i] == 0)
{
swap(&board[i], &board[i-1]);
break;
}
}
}
void moveright(int board[],int size )
{
int i;
for(i = 0; i <= 15; i++)
{
if(board[i] == 0)
{
swap(&board[i], &board[i+1]);
break;
}
}
}