Skip to content

Instantly share code, notes, and snippets.

@pranavk
Created Apr 29, 2015
Embed
What would you like to do?
Puzzle game
/*
What is this game all about ?
There is an ideal 2D array consisting of alphabets from a to x, and the last element of the array being '-'. But the user is given some permutation of the array with '-' somewhere in between. The goal of the user is to reach that ideal 2D array.
*/
#include<stdio.h>
static char ideal[5][5] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'_' };
static char random[5][5] = { 'l', 'm', '_', 'd', 'q', 'c', 'o', 'e', 'a', 'f',
'g', 'b', 'i', 'p', 'h', 'r', 's', 'w', 'x', 'k', 'j', 't', 'u', 'v',
'n' };
int m = 0; //this is the row position of '_' ;
int n = 2; // this is the column position of '_';
static void print() {
int i, j;
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
printf("%c ", random[i][j]);
}
printf("\n");
}
printf("\n");
}
static int check() {
int k = 0;
int i, j;
for (i = 0; i < 5; i++) {
for (j = 0; j < 5; j++) {
if (ideal[i][j] == random[i][j]) {
if (i == 4 && j == 4)
return 1;
} else
return 0;
}
}
return 0;
}
static void swap(char* a, char* b) {
char t;
t = *a;
*a = *b;
*b = t;
print();
}
int main() {
int counter = 0;
printf("Use 'i','j','k','l' for up, left, down, right respectively.\n");
char ch;
print();
while (!check()) {
ch = getchar();
if (ch == '\n')
continue;
switch (ch) {
case 'i':
if (m == 4) {
printf("Action not possible. Please enter a valid option.\n");
print();
break;
}
swap(&random[m][n], &random[m + 1][n]);
m++;
counter++;
break;
case 'j':
if (n == 4) {
printf("Action not possible. Please enter a valid option.\n");
print();
break;
}
swap(&random[m][n], &random[m][n + 1]);
n++;
counter++;
break;
case 'k':
if (m == 0) {
printf("Action not possible. Please enter a valid option.\n");
print();
break;
}
swap(&random[m][n], &random[m - 1][n]);
m--;
counter++;
break;
case 'l':
if (n == 0) {
printf("Action not possible. Please enter a valid option.\n");
print();
break;
}
swap(&random[m][n], &random[m][n - 1]);
n--;
counter++;
break;
default:
printf(
"Please enter a valid character. Valid options are\ni j k and l.\n");
}
}
printf("\n****Congratulations****, you win the Game !!!\n\n"
"************Your score : %d************", counter);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment