CGR Microprojects
CGR Microprojects
yogeshwari sathe
void print();
void movevalue(int k);
int findlen(int n);
void addrandomno();
void rupdate();
void createprev(int*** p);
void updatearrtoprev(int*** p);
void resetgame();
int findlen(int n) {
int len = 0;
while (n) {
n /= 10;
len++;
}
return len;
}
void print() {
printf("\n=========== 2048 ===========\n");
printf("Score: %d | High Score: %d\n", score, highscore);
for (int i = 0; i < MAX; i++) {
2
for (int j = 0; j < MAX; j++) {
printf("| %4d ", arr[i][j] ? arr[i][j] : 0);
}
printf("|\n");
}
printf("=============================\n");
printf("Controls: W/A/S/D, P (prev), R (restart), U (exit)\n");
}
void addrandomno() {
int i, j;
srand(time(NULL));
do {
i = rand() % MAX;
j = rand() % MAX;
} while (arr[i][j] != 0);
arr[i][j] = (rand() % 10 == 0) ? 4 : 2;
}
void movevalue(int k) {
for (int i = k; i < MAX - 1; i++) {
if (c[i] == 0) {
c[i] = c[i + 1];
c[i + 1] = 0;
}
}
}
void rupdate() {
for (int i = MAX - 1; i > 0; i--) {
3
if (c[i] == c[i - 1]) {
c[i] += c[i - 1];
score += c[i];
c[i - 1] = 0;
}
}
movevalue(0);
}
void resetgame() {
for (int i = 0; i < MAX; i++)
for (int j = 0; j < MAX; j++)
arr[i][j] = 0;
score = 0;
addrandomno();
}
int main() {
char choice;
resetgame();
print();
while (1) {
choice = getchar();
while (getchar() != '\n'); // Clear input buffer
4
print();
continue;
}
5
here is the output of the
project
Conclusion
Developing a project like the 2048 game in C
provides a hands-on and enjoyable way to
enhance programming skills. The article has
shown the usage of the fundamental
components of the language for
implementing the game, including its grid
layout, tile movement, scoring, and game-
ending conditions.