Skip to content

Instantly share code, notes, and snippets.

@adnils
Created April 5, 2014 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adnils/9993846 to your computer and use it in GitHub Desktop.
Save adnils/9993846 to your computer and use it in GitHub Desktop.
2048 in C
// Original file by Jay Chan:
// https://gist.github.com/justecorruptio/9967738
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#define GRID_LEN 16
int M[GRID_LEN];
int X = GRID_LEN;
int W;
int k;
int K[] = { 2, 3, 1 };
int
w (int d, int i, int j)
{
if (d <= 0) {
return 4 * i + j;
}
return w (d - 1, j, 3 - i);
}
void
s (int f, int d)
{
int i = 4, j, l, P;
for (; i--;) {
j = k = l = 0;
for (; k < 4;) {
if (j < 4) {
P = M[w (d, i, j++)];
W |= P >> 11;
l *P && (f ? M[w (d, i, k)] = l << (l == P) : 0, k++);
l = l ? (P ? (l - P ? P : 0) : l) : P;
}
else {
f ? M[w (d, i, k)] = l : 0;
++k;
W |= 2 * !l;
l = 0;
}
}
}
}
void
T ()
{
int i = X + rand () % X;
for (; M[i % X] * i; i--);
i ? M[i % X] = 2 << rand () % 2 : 0;
W = i = 0;
for (; i < 4; i++) {
s (0, i);
}
// Prints the tiles onto the terminal
i = X;
puts ("\e[2J\e[H");
for (; i--;) {
if (M[i]) {
printf ("%4d|", M[i]);
} else {
printf ("%s", " |");
}
// every 4th cell is followed by a line-break
if (0 == (i & 3)) {
putchar ('\n');
}
}
// read input from keyboard
if (!(W - 2)) {
read (0, &k, 3);
s (1, K[(k >> X) % 4]);
T ();
}
}
int
main (void)
{
// Uses stty to clear the screen in preparation for the game
system ("stty cbreak");
/* Intializes random number generator */
srand ((unsigned) time (NULL));
T ();
// Game has finished by this point
// If win, display "WIN". Otherwise, display "LOSE".
puts (W & 1 ? "WIN" : "LOSE");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment