Skip to content

Instantly share code, notes, and snippets.

@datatravelandexperiments
Created March 16, 2014 03:58
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save datatravelandexperiments/9578313 to your computer and use it in GitHub Desktop.
Save datatravelandexperiments/9578313 to your computer and use it in GitHub Desktop.
#include <curses.h>
#include <stdlib.h>
#include <time.h>
int b[32], *d=&b[16], q, v, y;
char*m[]={
"CBA@GFEDKJIHONML",
"@DHLAEIMBFJNCGKO",
"LHD@MIEANJFBOKGC",
"CGKOBFJNAEIM@DHL"
};
char*x[]={"won","lost","quit"};
void B(int m,int n) { for(int*p=b;p<d;++p) p[m]=p[n]; }
void C(int n) { char*s=m[n]; for(int*p=b;p<d;++p) *p=b[*s++-'0']; }
void E(int n) { B(16,0); C(n); }
void
L()
{
for (int *p = b; p < d; p += 4) {
for (int i = 0; i < 3; ++i) {
if (!p[i]) {
for (int j = i + 1; j < 4; ++j) {
if (p[j]) {
p[i] = p[j];
p[j] = 0;
y = 1;
break;
}
}
}
}
for (int i = 0; i < 3; ++i) {
if (p[i] && (p[i] == p[i + 1])) {
if ((p[i] *= 2) == 2048)
q = 1;
v += p[i];
for (int j = i + 1; j < 3; ++j) {
p[j] = p[j + 1];
}
p[3] = 0;
y = 1;
}
}
}
}
void X(int n) { E(n); L(); E(n); }
void D() { E(2); L(); E(3); }
void
F()
{
int t = v; y = 0;
B(16, 0); L(); C(0); L(); C(1); L(); C(2); L(); B(0, 16);
if (!y) q = 2;
v = t;
}
void N() {
int n; do n = random() & 0xF; while (b[n]);
b[n] = 2 + 2 * !(random() % 10);
}
void H() { for (int i = 0; i < 4; ++i) printw("+------"); printw("+\n"); }
void
P()
{
move(0, 0);
for (int i = 0; i < 4; ++i) {
H(); addch('|');
for (int j = 0; j < 4; ++j) {
int k = b[4 * i + j];
if (k) printw(" %4u |", k); else printw(" |");
}
addch('\n');
}
H(); printw("\n Score:%21u\n", v); refresh();
}
int
main()
{
initscr(); cbreak(); noecho(); nonl(); curs_set(0); keypad(stdscr,1); clear();
srandom(time(0)); N(); N(); P();
int c;
while (!q) {
y = 0;
switch (getch()) {
case 'q': q = 3; break;
case KEY_LEFT: L(); break;
case KEY_RIGHT: X(0); break;
case KEY_UP: X(1); break;
case KEY_DOWN: D(); break;
}
if (y) { N(); F(); }
P();
}
--q;
printw("\nYou %s!\n", x[q]);
refresh();
endwin();
exit(q);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment