Skip to content

Instantly share code, notes, and snippets.

@catull
Forked from justecorruptio/2048.c
Last active August 29, 2015 13:58
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 catull/10012420 to your computer and use it in GitHub Desktop.
Save catull/10012420 to your computer and use it in GitHub Desktop.
// Original file by Jay Chan:
// https://gist.github.com/justecorruptio/9967738
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#define SIDE 4
#define GRID (SIDE * SIDE)
int M[GRID];
int W;
int K[] = { 2, 3, 1, 0 };
int
cell (int d, int i, int j)
{
if (d <= 0) {
return SIDE * i + j;
}
return cell (d - 1, j, SIDE - 1 - i);
}
void
draw (int f, int d)
{
int k, i = SIDE, j, l, P;
for (; i--;) {
j = k = l = 0;
for (; k < SIDE;) {
if (j < SIDE) {
P = M[cell (d, i, j++)];
W |= P >> 11;
l *P && (f ? M[cell (d, i, k)] = l << (l == P) : 0, k++);
l = l ? (P ? (l - P ? P : 0) : l) : P;
}
else {
f ? M[cell (d, i, k)] = l : 0;
++k;
W |= 2 * !l;
l = 0;
}
}
}
}
void
step ()
{
int k, i = GRID + rand () & (GRID - 1);
for (; M[i & (GRID - 1)] * i; i--);
i ? M[i & (GRID - 1)] = 2 << (rand () % 2) : 0;
W = i = 0;
for (; i < SIDE; i++) {
draw (0, i);
}
// print the tiles onto the terminal
i = GRID;
puts ("\e[2J\e[H");
for (; i--;) {
if (M[i]) {
printf ("%4d|", M[i]);
} else {
printf ("%s", " |");
}
if (0 == (i % SIDE)) {
putchar ('\n');
}
}
if (!(W - 2)) {
// read input from keyboard
read (0, &k, 3);
draw (1, K[(k >> 16) & 3]);
step ();
}
}
int
main (void)
{
// clear the screen in preparation for the game
system ("stty cbreak");
/* intialize random number generator */
srand ((unsigned) time (NULL));
step ();
// game has finished by this point
puts (W & 1 ? "Won" : "Lost");
return 0;
}
//[2048]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment