1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
| #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#define MENTION printf("Enter 'j', 'i', 'l' or 'k' to move the empty cell left, up, right or down correspondingly, or 'q' to exit: \n\n");
int** field;
int emptyCell_x, emptyCell_y;
//------------------
void init()
{
int x,y, i,j;
srand(time(NULL));
for(i=1; i<=15;)
{
x=rand()%4; y=rand()%4;
if(field[x][y] == 0) field[x][y] = i++;
}
for(i=0; i<4; i++) //to find the empty cell
for(j=0; j<4; j++)
if(field[j][i] == 0)
{
emptyCell_x=j; emptyCell_y = i; return;
}
}
//---------------------
void printField()
{
int i,j;
for(i=0; i<4; i++)
{
for(j=0; j<4; j++)
if(field[j][i]) printf("%3d", field[j][i]);
else printf(" _");
printf("\n\n");
}
printf("\n\n");
}
//-----------------------
int notEndYet()
{
int i,j;
for(i=0; i<3; i++)
for(j=0; j<4; j++)
if(field[j][i] != 4*i+j+1) return 0; //go on play
if(field[0][3] != 13) return 0;
return 1; //victory!
}
//--------------- allows move the emply cell
int move()
{
char c;
while(1)
{
c = getch();
switch(c)
{
case 'j':
if(emptyCell_x==0)
{
printf("Not valid move.\n\n");
break;
}
else
{
field[emptyCell_x][emptyCell_y] = field[emptyCell_x-1][emptyCell_y];
field[emptyCell_x-1][emptyCell_y] = 0;
emptyCell_x--;
return 1;
}
case 'i':
if(emptyCell_y==0)
{
printf("Not valid move.\n\n");
break;
}
else
{
field[emptyCell_x][emptyCell_y] = field[emptyCell_x][emptyCell_y-1];
field[emptyCell_x][emptyCell_y-1] = 0;
emptyCell_y--;
return 2;
}
case 'l':
if(emptyCell_x==3)
{
printf("Not valid move.\n\n");
break;
}
else
{
field[emptyCell_x][emptyCell_y] = field[emptyCell_x+1][emptyCell_y];
field[emptyCell_x+1][emptyCell_y] = 0;
emptyCell_x++;
return 3;
}
case 'k':
if(emptyCell_y==3)
{
printf("Not valid move.\n\n");
break;
}
else
{
field[emptyCell_x][emptyCell_y] = field[emptyCell_x][emptyCell_y+1];
field[emptyCell_x][emptyCell_y+1] = 0;
emptyCell_y++;
return 4;
}
case 'q': exit(1);
default: MENTION
}
}
}
//----------------- main function
void main()
{
field = (int**)calloc(4, sizeof(int*));
for(int i=0; i<4; i++)
field[i] = (int*)calloc(4, sizeof(int));
do init(); while(notEndYet());
MENTION
printField();
while(!notEndYet())
{
move();
printField();
}
printf("\nYou win!\n"); getch();
} |