Snek program (Snake)

A simple snake (snek) program! It is 39 lines long (while auto formatting it ctrl + t). It way shorter then my previous attempts! It’s all thanks to PVectors!

int w = 20, h = 20, scl = 30, maxAge = 10, x = 10, y = 10, dir = 3, fx = (int)random(w), fy = (int)random(h);
PVector cell[][] = new PVector[w][h];
void setup() {
  size(600, 600);
  for (int i = 0; i < w; i++) for (int j = 0; j < h; j++) cell[i][j] = new PVector(i, j, 0);
  frameRate(5);
}
void draw() {
  background(0);
  x += ((dir == 3)? 1 : ((dir == 2)? -1 : 0));
  y += ((dir == 0)? -1 : ((dir == 1)? 1 : 0));
  if (x > w-1) x = 0;
  if (x < 0) x = w-1;
  if (y > h-1) y = 0;
  if (y < 0) y = h-1;
  if (cell[x][y].z == 0) {
    cell[x][y] = new PVector(x, y, 1);
  } else noLoop();
  if (x == fx && y == fy) {
    maxAge++;
    fx = floor(random(w));
    fy = floor(random(h));
  }
  for (int i = 0; i < w; i++) for (int j = 0; j < h; j++) {
    if (cell[i][j].z == 0) fill(  (((fx == i && fy == j)? color(255, 0, 0) : color(0))) ); 
    else {
      fill( map(cell[i][j].z, 0, maxAge, 255, 0) );
      cell[i][j] = new PVector(i, j, cell[i][j].z+1);
      if (cell[i][j].z > maxAge) cell[i][j] = new PVector(i, j, 0);
    }
    rect(i*scl, j*scl, scl, scl);
  }
}
void keyPressed() {
  if (keyCode == UP || key == 'w') dir = 0;
  if (keyCode == DOWN || key == 's') dir = 1;
  if (keyCode == LEFT || key == 'a') dir = 2;
  if (keyCode == RIGHT || key == 'd') dir = 3;
}

2 Likes

I guess something is wrong here. Turning 90 degrees is OK, but going 180 (opposite) freezes the sketch. Also, It would be nice to see it as an embedded p5.js iframe to play it right along here.

how do I do that? (imbed it? And do I have to write it in p5.js?)

You can use other embeds like from openprocessing, and use java, just change the address.

<iframe src="https://editor.p5js.org/your-sketch-page"
width="100%" height="510" allowfullscreen frameborder="0"
marginwidth="0" marginheight="0"></iframe>