标签:
code:
1 // Original file by Jay Chan: 2 // https://gist.github.com/justecorruptio/9967738 3 4 #include <stdio.h> 5 #include <stdlib.h> 6 #include <unistd.h> 7 #include <time.h> 8 9 #define GRID_LEN 16 10 11 int M[GRID_LEN]; 12 int X = GRID_LEN; 13 int W; 14 int k; 15 int K[] = { 2, 3, 1 }; 16 17 18 int 19 w (int d, int i, int j) 20 { 21 if (d <= 0) { 22 return 4 * i + j; 23 } 24 25 return w (d - 1, j, 3 - i); 26 } 27 28 void 29 s (int f, int d) 30 { 31 int i = 4, j, l, P; 32 33 for (; i--;) { 34 j = k = l = 0; 35 36 for (; k < 4;) { 37 if (j < 4) { 38 P = M[w (d, i, j++)]; 39 W |= P >> 11; 40 l *P && (f ? M[w (d, i, k)] = l << (l == P) : 0, k++); 41 l = l ? (P ? (l - P ? P : 0) : l) : P; 42 } 43 else { 44 f ? M[w (d, i, k)] = l : 0; 45 ++k; 46 W |= 2 * !l; 47 l = 0; 48 } 49 } 50 } 51 } 52 53 void 54 T () 55 { 56 int i = X + rand () % X; 57 58 for (; M[i % X] * i; i--); 59 60 i ? M[i % X] = 2 << rand () % 2 : 0; 61 W = i = 0; 62 63 for (; i < 4; i++) { 64 s (0, i); 65 } 66 67 // Prints the tiles onto the terminal 68 i = X; 69 puts ("\e[2J\e[H"); 70 71 for (; i--;) { 72 if (M[i]) { 73 printf ("%4d|", M[i]); 74 } else { 75 printf ("%s", " |"); 76 } 77 78 // every 4th cell is followed by a line-break 79 if (0 == (i & 3)) { 80 putchar (‘\n‘); 81 } 82 } 83 84 // read input from keyboard 85 if (!(W - 2)) { 86 read (0, &k, 3); 87 s (1, K[(k >> X) % 4]); 88 T (); 89 } 90 } 91 92 int 93 main (void) 94 { 95 // Uses stty to clear the screen in preparation for the game 96 system ("stty cbreak"); 97 98 /* Intializes random number generator */ 99 srand ((unsigned) time (NULL)); 100 101 T (); 102 103 // Game has finished by this point 104 // If win, display "WIN". Otherwise, display "LOSE". 105 puts (W & 1 ? "WIN" : "LOSE"); 106 107 return 0; 108 }
可通过gcc编译,在console下玩。
ref: https://gist.github.com/anirudh-chhangani/9989292
modified by catnull
标签:
原文地址:http://www.cnblogs.com/forcheryl/p/4603990.html