Skip to content

Instantly share code, notes, and snippets.

@Introscopia
Last active December 15, 2023 16:39
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 Introscopia/16da8a46f8aaa295fa9d00bc82625862 to your computer and use it in GitHub Desktop.
Save Introscopia/16da8a46f8aaa295fa9d00bc82625862 to your computer and use it in GitHub Desktop.
spiral-2048
// reverse engineering of:
// https://twitter.com/kitasenjudesign/status/1732795192934338954
int W = 32;
float e;
int [][] values;
int [][] copy;
int cx, cy, dir;
boolean spiraling = true;
int[] dx = { 1, 0, -1, 0 };
int[] dy = { 0, 1, 0, -1 };
void setup() {
size(600, 600);
e = width / float(W);
values = new int[W][W];
copy = new int[W][W];
cx = 0;
cy = 0;
dir = 0;
textAlign(LEFT, TOP);
//frameRate(12);
noLoop();
}
void draw() {
if ( spiraling ) {
values[cx][cy] = 1;
cx += dx[dir];
cy += dy[dir];
if ( cx + dx[dir] < 0 || cy + dy[dir] < 0 || cx + dx[dir] >= W || cy + dy[dir] >= W ) {
dir = (dir+1) % 4;
} else if ( values[ cx+dx[dir] ][ cy+dy[dir] ] != 0 ) {
dir = (dir+1) % 4;
if ( values[ cx+dx[dir] ][ cy+dy[dir] ] != 0 ) {
values[cx][cy] = 1;
spiraling = false;
println("Done!");
}
}
}
for(int j = 0; j < W; j++) {
for(int i = 0; i < W; i++) {
if( values[i][j] > 0 ){
int V = values[i][j];
boolean block = true;
for(int x = i; x < i+2*V; x++) {
for(int y = j; y < j+2*V; y++) {
if( x >= W || y >= W || values[x][y] != V ){
block = false;
break;
}
}
if(!block) break;
}
if( block ){
for(int x = i; x < i+2*V; x++) {
for(int y = j; y < j+2*V; y++) {
values[x][y] = 2*V;
}
}
i += 2*V -1;
}
}
}
}
/*
for (int i = 0; i < W; i++) {
for (int j = 0; j < W; j++) {
if ( values[i][j] > 0 ){
fill(255);stroke(0);
rect( i*e, j*e, e, e );
fill(0);
text( values[i][j], i*e, j*e );
}
}
}
noFill();
stroke(0,0,255);
rect( cx*e, cy*e, e, e );
*/
for (int j = 0; j < W; j++) {
for (int i = 0; i < W; i++) {
copy[i][j] = values[i][j];
}
}
background(0);
noStroke();
fill(255,0,0);
for (int j = 0; j < W; j++) {
for (int i = 0; i < W; i++) {
if ( copy[i][j] > 0 ){
int V = copy[i][j];
circle( e*(i+(V/2.0)), e*(j+(V/2.0)), e*V );
for(int x = i; x < i+V; x++) {
for(int y = j; y < j+V; y++) {
copy[x][y] = 0;
}
}
}
}
}
}
void keyPressed(){
if( key == ' ' ) noLoop();
if( key == 'l' ) loop();
if( key == '.' ) redraw();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment