Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- void show_array(int (*)[4]);
- void move_tile(int (*)[4], char);
- int check_win(int (*)[4]);
- main(){
- char key;
- int array[4][4]={
- {1, 2, 3, 4},
- {5, 6, 7, 8},
- {9, 10, 11, 12},
- {13, 14, 16, 15}
- };
- do{
- show_array(array);
- key=getchar();
- move_tile(array, key);
- while ((key = getchar()) != '\n' && key != EOF) { } /* clear stdin buffer */
- }while((check_win(array))==0);
- puts("You won");
- return 0;
- }
- void show_array(int (*arrayPtr)[4]){
- int i, j;
- system("clear");
- puts("Use wasd to play");
- for(i=0;i<4;i++){
- for(j=0;j<4;j++)
- if(arrayPtr[i][j]!=16)
- printf("%d\t", arrayPtr[i][j]);
- else
- printf("\t");
- puts("");
- }
- }
- void move_tile(int (*arrayPtr)[4], char c){
- void get_current_pos(int (*)[4], int *, int *);
- int i, j;
- get_current_pos(arrayPtr, &i, &j);
- switch(c){
- case 'w':
- if(i<3){
- arrayPtr[i][j]^=arrayPtr[i+1][j]^=arrayPtr[i][j]^=arrayPtr[i+1][j]; /* fast and hot swap */
- }
- else{
- puts("Illegal operation: press enter to continue");
- getchar();
- }
- break;
- case 'd':
- if(j>0){
- arrayPtr[i][j]^=arrayPtr[i][j-1]^=arrayPtr[i][j]^=arrayPtr[i][j-1]; /* fast and hot swap */
- }
- else{
- puts("Illegal operation: press enter to continue");
- getchar();
- }
- break;
- case 's':
- if(i>0){
- arrayPtr[i][j]^=arrayPtr[i-1][j]^=arrayPtr[i][j]^=arrayPtr[i-1][j]; /* fast and hot swap */
- }
- else{
- puts("Illegal operation: press enter to continue");
- getchar();
- }
- break;
- case 'a':
- if(j<3){
- arrayPtr[i][j]^=arrayPtr[i][j+1]^=arrayPtr[i][j]^=arrayPtr[i][j+1]; /* fast and hot swap */
- }
- else{
- puts("Illegal operation: press enter to continue");
- getchar();
- }
- break;
- default:
- puts("Wrong key: press enter to continue");
- getchar();
- }
- }
- int check_win(int (*arrayPtr)[4]){
- int flag=1;
- int i, j;
- for(i=0;i<4;i++)
- for(j=0;j<4;j++)
- (arrayPtr[i][j]==(4*i+j+1))?:(flag=0);
- return flag;
- }
- void get_current_pos(int (*arrayPtr)[4], int * m, int * n){
- int i, j;
- for(i=0;i<4;i++)
- for(j=0;j<4;j++)
- if(arrayPtr[i][j]==16){
- *m=i;
- *n=j;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement