0% found this document useful (0 votes)
6 views

CGR Microprojects

Uploaded by

noahsus589
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

CGR Microprojects

Uploaded by

noahsus589
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

2048 puzzle game

yogeshwari sathe

prof. mrs priyanka ghenand


1
a program code for the 2048
puzzle game
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 4
#define MAXPREV 500

int arr[MAX][MAX] = {0}, c[MAX], score = 0, highscore = 0, count = 0;

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

if (choice == 'U' || choice == 'u') break;

if (choice == 'R' || choice == 'r') {


resetgame();

4
print();
continue;
}

for (int i = 0; i < MAX; i++) {


for (int j = 0; j < MAX; j++) c[j] = (choice == 'W' || choice == 'S')
? arr[j][i] : arr[i][j];
if (choice == 'A' || choice == 'W') for (int j = 0; j < MAX; j++) c[j]
= c[MAX - j - 1];
rupdate();
for (int j = 0; j < MAX; j++) {
if (choice == 'A' || choice == 'W') arr[i][MAX - j - 1] = c[j];
else arr[i][j] = c[j];
}
}
addrandomno();
print();
}

printf("\nThanks for playing!\n");


return 0;
}

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.

You might also like