# Snake Game Code

**URL:** https://discourse.processing.org/t/snake-game-code/1725
**Category:** Coding Questions
**Created:** [July 12, 2018, 7:20pm UTC](https://discourse.processing.org/t/snake-game-code/1725 "2018-07-12T19:20:53Z")
**Posts on this page:** 20
**Page:** 1

<div class="post-metadata">

### Author: ![nofil7](https://avatars.discourse-cdn.com/v4/letter/n/e95f7d/32.png) [@nofil7](https://discourse.processing.org/u/nofil7)
#### Post date: [July 12, 2018, 7:20pm UTC](https://discourse.processing.org/t/snake-game-code/1725/1 "2018-07-12T19:20:54Z")

</div>

Snake Code assignment

---

<div class="post-metadata">

### Author: ![Kevin](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/kevin/32/2297_2.png) [@Kevin](https://discourse.processing.org/u/Kevin)
#### Post date: [July 12, 2018, 7:22pm UTC](https://discourse.processing.org/t/snake-game-code/1725/2 "2018-07-12T19:22:15Z")

</div>

Sorry, but that’s not really how this works. We can’t just do you work for you.

However, if you [break your problem down into smaller steps](http://happycoding.io/tutorials/how-to/program) and take those steps on one at a time, we’ll be happy to help you- for free!

Which part of this are you stuck on?

---

<div class="post-metadata">

### Author: ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)
#### Post date: [July 12, 2018, 7:56pm UTC](https://discourse.processing.org/t/snake-game-code/1725/3 "2018-07-12T19:56:52Z")

</div>

- [https://Forum.Processing.org/two/discussions/tagged?Tag=%23snake](https://Forum.Processing.org/two/discussions/tagged?Tag=%23snake)

---

<div class="post-metadata">

### Author: ![nofil7](https://avatars.discourse-cdn.com/v4/letter/n/e95f7d/32.png) [@nofil7](https://discourse.processing.org/u/nofil7)
#### Post date: [July 12, 2018, 8:24pm UTC](https://discourse.processing.org/t/snake-game-code/1725/4 "2018-07-12T20:24:08Z")

</div>

So I’ve done so far which is like the first three steps  
Can you please help from there onwards?

```auto
final int X_SPEED = 1;
final int Y_SPEED = 1;

int headX = 250;
int headY = 250;

final int SNAKE_SIZE=15;

int applex= (round(random(97))+10)+80;
int appley= (round(random(97))+10)+80;

void setup()
{
  size(500,500);
}

void draw()
{
  background(192);
  fill(255);
  moveSnake();
  
  if(headX >= 500 || headX <= 0)
  {
    background(0); 
  }
  
  if(headY >= 500 || headY <= 0)
  {
    background(0); 
  }
  
  fill(255,0,0);
   stroke(0);
   rect(applex,appley,8,8);
}

void moveSnake()
{
  if(keyCode == RIGHT)
  {
    drawSnakeX();
    headX += X_SPEED; 
  }
  else if(keyCode == LEFT)
  {
    drawSnakeX();
    headX -= X_SPEED;
  }
  else if(keyCode == UP)
  {
    drawSnakeY();
    headY -= Y_SPEED;
  }
  else if(keyCode == DOWN)
  {
    drawSnakeY();
    headY += Y_SPEED;
  }
}

void drawSnakeX()
{
  for(int i = 0; i < 3; i++)
  {
    if(keyCode == RIGHT)
    {
       ellipse(headX - i*SNAKE_SIZE, headY, SNAKE_SIZE, SNAKE_SIZE); 
    }
    else if(keyCode == LEFT)
    {
       ellipse(headX + i*SNAKE_SIZE, headY, SNAKE_SIZE, SNAKE_SIZE);
    }
  }
}

void drawSnakeY()
{
  for(int i = 0; i < 3; i++)
  {
    if(keyCode == UP)
    {
       ellipse(headX, headY + i*SNAKE_SIZE, SNAKE_SIZE, SNAKE_SIZE);
    }
    else if(keyCode == DOWN)
    {
       ellipse(headX, headY - i*SNAKE_SIZE, SNAKE_SIZE, SNAKE_SIZE);
    }
  }
}

```

---

<div class="post-metadata">

### Author: ![Kevin](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/kevin/32/2297_2.png) [@Kevin](https://discourse.processing.org/u/Kevin)
#### Post date: [July 12, 2018, 8:35pm UTC](https://discourse.processing.org/t/snake-game-code/1725/5 "2018-07-12T20:35:45Z")

</div>

When posting code, please format it using the `</>` code button.

Looks like a good start. What does this code do? What’s the next thing you’re trying to add? Where are you stuck?

---

<div class="post-metadata">

### Author: ![nofil7](https://avatars.discourse-cdn.com/v4/letter/n/e95f7d/32.png) [@nofil7](https://discourse.processing.org/u/nofil7)
#### Post date: [July 12, 2018, 8:54pm UTC](https://discourse.processing.org/t/snake-game-code/1725/6 "2018-07-12T20:54:45Z")

</div>

Its drawing the food object in a random location and the snake moves perfectly as well  
Next I want the snake to hit the food object and as it does so it should increase the snake length by 1  
Also when the snake eats the food object the object has to be drawn to a new random location

---

<div class="post-metadata">

### Author: ![TfGuy44](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/tfguy44/32/41_2.png) [@TfGuy44](https://discourse.processing.org/u/TfGuy44)
#### Post date: [July 12, 2018, 9:14pm UTC](https://discourse.processing.org/t/snake-game-code/1725/7 "2018-07-12T21:14:16Z")

</div>

Okay. So you need to determine if the snakes head has reached the target. You know where the snake’s head is. You know how big it is. You know where the target is. You know how big it is. What can you say about the distance between the head and the target’s positions in relationship to their sizes when they two things are touching?

When that condition is true, you can increase the snake’s length, and give the target a new random position.

Try just writing the code that does this on it’s own, and post it here so we can work with you on it.

---

<div class="post-metadata">

### Author: ![nofil7](https://avatars.discourse-cdn.com/v4/letter/n/e95f7d/32.png) [@nofil7](https://discourse.processing.org/u/nofil7)
#### Post date: [July 12, 2018, 10:03pm UTC](https://discourse.processing.org/t/snake-game-code/1725/8 "2018-07-12T22:03:32Z")

</div>

So I did this I dont really understand how I am to approach this

```auto
void display() //Displaying the snake and the apple
{
  if (headX==applex && headY==appley)
  {
    snakeSize=round(random(3)+1);
    redo=true;
    while(redo)
    {
      applex=(round(random(47))+1)+8;
      appley=(round(random(47))+1)+8;
      for(int i=1; i<snakeSize; i++)
      {
        if (applex==headX*i && appley== headY*i)
        {
          redo=true;
        }
        else
        {
          redo=false;
          i=1000;
        }
      }
    }
  }
  stroke(255,255,255);
  fill(0);
  ellipse(headX,headY,8,8);
  fill(255);
  ellipse(headX*snakeSize,headY*snakeSize,8,8);
}

void checkdead() //Ending the game
{
  for(int i=2;i<snakeSize;i++)
  {
    if (headX==headX*i && headY==headY*i)
    {
      fill(255);
      rect(125,125,160,100);
      fill(0);
      text("EXIT",200,150);
      text("RESTART",200,175);
      text("PRESS SHIFT TO RESTART",200,200);
      stopgame=true;
    }
  }
}

```

---

<div class="post-metadata">

### Author: ![TfGuy44](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/tfguy44/32/41_2.png) [@TfGuy44](https://discourse.processing.org/u/TfGuy44)
#### Post date: [July 12, 2018, 11:23pm UTC](https://discourse.processing.org/t/snake-game-code/1725/9 "2018-07-12T23:23:47Z")

</div>

You have a lot of code and it’s not clear what a lot of it is doing. I would suggest that you put in some comments explaining each and every line.

This is, essentailly, rubber duck coding. Explain your code to yourself (and us!) via comments, and in doing so, you will see what is wrong with it.

Here are some comments to start you off. These are not in order! You will have to put them in the right places in your code…

```auto
// Determine if the snake's position the same as the target's position.
// Give the target a new X position.
// Give the target a new Y position.
// Increase the snake's length.
// Draw the snake, each time the loop runs one shape is drawn.
// Draw one shape.
// Draw the target.
// The setup function, which runs once when the sketch starts.
// A reset function, which gives all game variables their initial values.
// The snake starts in the middle of the screen.
// The target has a random position.
// This function determines which way the snake needs to move.
// This moves the snake.
```

---

<div class="post-metadata">

### Author: ![dan850](https://avatars.discourse-cdn.com/v4/letter/d/e9c0ed/32.png) [@dan850](https://discourse.processing.org/u/dan850)
#### Post date: [July 13, 2018, 12:29am UTC](https://discourse.processing.org/t/snake-game-code/1725/10 "2018-07-13T00:29:02Z")

</div>

@nofil7, These posts can potentially help you get an idea on how to solve your problem. But, its important to work through the problem solving process.

---

<div class="post-metadata">

### Author: ![nofil7](https://avatars.discourse-cdn.com/v4/letter/n/e95f7d/32.png) [@nofil7](https://discourse.processing.org/u/nofil7)
#### Post date: [July 13, 2018, 4:07am UTC](https://discourse.processing.org/t/snake-game-code/1725/11 "2018-07-13T04:07:17Z")

</div>

This is my code so far that draws the snake,moves it and also draws the target.Need help with step 4 and step 5 now as I mentioned in my first post

```auto
final int X_SPEED = 1;
final int Y_SPEED = 1;

int headX = 250;
int headY = 250;

int snakeSize=15;

int applex= (round(random(97))+10)+80;
int appley= (round(random(97))+10)+80;

boolean redo=true;
boolean stopgame=false;

void setup()
{
  size(500,500);
}

void draw()
{
  background(192);
  fill(255);
  moveSnake();
  
  if(headX >= 500 || headX <= 0)
  {
    background(0); 
  }
  
  if(headY >= 500 || headY <= 0)
  {
    background(0); 
  }
  
  fill(255,0,0);
   stroke(0);
   rect(applex,appley,8,8);
}

void moveSnake() //For moving the snake
{
  if(keyCode == RIGHT)
  {
    drawSnakeX();
    headX += X_SPEED; 
  }
  else if(keyCode == LEFT)
  {
    drawSnakeX();
    headX -= X_SPEED;
  }
  else if(keyCode == UP)
  {
    drawSnakeY();
    headY -= Y_SPEED;
  }
  else if(keyCode == DOWN)
  {
    drawSnakeY();
    headY += Y_SPEED;
  }
}

void drawSnakeX() //Drawing the snake X-Axis
{
  for(int i = 0 ; i < 3; i++)
  {
    if(keyCode == RIGHT)
    {
       ellipse(headX - i*snakeSize, headY, snakeSize, snakeSize); 
    }
    else if(keyCode == LEFT)
    {
       ellipse(headX + i*snakeSize, headY, snakeSize, snakeSize);
    }
  }
}

void drawSnakeY() //Drawing the snake Y-Axis
{
  for(int i = 0; i < 3; i++)
  {
    if(keyCode == UP)
    {
       ellipse(headX, headY + i*snakeSize, snakeSize, snakeSize);
    }
    else if(keyCode == DOWN)
    {
       ellipse(headX, headY - i*snakeSize, snakeSize, snakeSize);
    }
  }
}

void display() //Displaying the snake and the apple
{
  if (headX==applex && headY==appley)
  {
    snakeSize=round(random(30)+1);
    redo=true;
    while(redo)
    {
      applex=(round(random(97))+10)+80;
      appley=(round(random(497))+10)+80;
      for(int i=0; i<snakeSize; snakeSize++)
      {
        if (applex==headX*i && appley== headY*i)
        {
          redo=true;
        }
        else
        {
          redo=false;
        }
      }
    }
  }
  stroke(255,255,255);
  fill(0);
  ellipse(headX,headY,8,8);
  fill(255);
  ellipse(headX*snakeSize,headY*snakeSize,8,8);
}

void checkdead() //Ending the game
{
  for(int i=2;i<snakeSize;i++)
  {
    if (headX==headX*i && headY==headY*i)
    {
      fill(255);
      rect(125,125,160,100);
      fill(0);
      text("EXIT",200,150);
      text("RESTART",200,175);
      text("PRESS SHIFT TO RESTART",200,200);
      stopgame=true;
    }
  }
}

```

---

<div class="post-metadata">

### Author: ![TfGuy44](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/tfguy44/32/41_2.png) [@TfGuy44](https://discourse.processing.org/u/TfGuy44)
#### Post date: [July 13, 2018, 6:18am UTC](https://discourse.processing.org/t/snake-game-code/1725/12 "2018-07-13T06:18:56Z")

</div>

You have to attempt to do it yourself. Where is your attempt at a `checkIfTargetHit()` function?

Do the snake head and the target collide only when their X and Y positions are exactly the same?

Consider:

![DoesCollide](https://canada1.discourse-cdn.com/flex036/uploads/processingfoundation1/original/1X/bb0be1e97aa53af9b8e223967fd5592bc284b40f.png)

---

<div class="post-metadata">

### Author: ![nofil7](https://avatars.discourse-cdn.com/v4/letter/n/e95f7d/32.png) [@nofil7](https://discourse.processing.org/u/nofil7)
#### Post date: [July 13, 2018, 4:06pm UTC](https://discourse.processing.org/t/snake-game-code/1725/13 "2018-07-13T16:06:53Z")

</div>

I have been attempting to do it by myself that is why I asked for your help in the first place.I wrote the code and it doesn’t works

---

<div class="post-metadata">

### Author: ![nofil7](https://avatars.discourse-cdn.com/v4/letter/n/e95f7d/32.png) [@nofil7](https://discourse.processing.org/u/nofil7)
#### Post date: [July 15, 2018, 12:30am UTC](https://discourse.processing.org/t/snake-game-code/1725/14 "2018-07-15T00:30:36Z")

</div>

This is my check if snake hits the border function

```auto
if(headX >= 500 || headX <= 0)
  {
    background(0); 
  }
  
  if(headY >= 500 || headY <= 0)
  {
    background(0); 
  }

```

---

<div class="post-metadata">

### Author: ![nofil7](https://avatars.discourse-cdn.com/v4/letter/n/e95f7d/32.png) [@nofil7](https://discourse.processing.org/u/nofil7)
#### Post date: [July 15, 2018, 12:32am UTC](https://discourse.processing.org/t/snake-game-code/1725/15 "2018-07-15T00:32:01Z")

</div>

Seriously guys I attempted everything before coming to this forum.If you guys are just asking me to attempt something I already attempted and failed then how is it helping my cause

---

<div class="post-metadata">

### Author: ![TfGuy44](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/tfguy44/32/41_2.png) [@TfGuy44](https://discourse.processing.org/u/TfGuy44)
#### Post date: [July 15, 2018, 1:07am UTC](https://discourse.processing.org/t/snake-game-code/1725/16 "2018-07-15T01:07:07Z")

</div>

Please post your entire current code that shows your attempt at everything. So far you have asked us to do your work for you, and claimed you have tried to do it yourself. You need to show us you have attempted it.

Also include a description of exactly what is not working. Which lines of code do you think are the problem? What is your sketch doing (or not doing) that it shouldn’t (or should) be?

---

<div class="post-metadata">

### Author: ![nofil7](https://avatars.discourse-cdn.com/v4/letter/n/e95f7d/32.png) [@nofil7](https://discourse.processing.org/u/nofil7)
#### Post date: [July 15, 2018, 2:35am UTC](https://discourse.processing.org/t/snake-game-code/1725/17 "2018-07-15T02:35:36Z")

</div>

I just posted my whole code saying it is not working as far as hitting the target is concerned

I REPEAT AGAIN

The snake moves,target appears,hits the borders and restarts

I want the snake to hit the target and grow

---

<div class="post-metadata">

### Author: ![TfGuy44](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/tfguy44/32/41_2.png) [@TfGuy44](https://discourse.processing.org/u/TfGuy44)
#### Post date: [July 15, 2018, 5:02am UTC](https://discourse.processing.org/t/snake-game-code/1725/18 "2018-07-15T05:02:34Z")

</div>

Step 4 includes a direction to write a `checkIfTargetHit()` function. This function will determine if the snake has hit the target.

None of the code you have posted so far includes this function.

PLEASE ATTEMPT TO WRITE THIS FUNCTION. PLEASE POST YOUR ATTEMPT AT WRITING THIS FUNCTION. WITHOUT SEEING THE CODE OF YOUR ATTEMPT, WE ARE AT A LOSS AS TO HOW TO HELP YOU MAKE IT WORK.

… And this is coming from the forum regular who is the most likely to just write it for you. You’ve got to put some effort in.

---

<div class="post-metadata">

### Author: ![Rodri](https://avatars.discourse-cdn.com/v4/letter/r/5daacb/32.png) [@Rodri](https://discourse.processing.org/u/Rodri)
#### Post date: [March 28, 2020, 6:34pm UTC](https://discourse.processing.org/t/snake-game-code/1725/21 "2020-03-28T18:34:16Z")

</div>

Guys, is this too much code for a simple snake game? :

```auto
ArrayList<Integer> x = new ArrayList<Integer>(), y = new ArrayList<Integer>();
int speedinv = 4;
int scl = 10;
int hx=1,hy = 1,apx = int(int(random(scl,width-scl))/scl), apy = int(int(random(scl,height-scl))/scl), dir = 1,start = 0;
int[] dx = {0,1,0,-1}; 
int[] dy = {-1,0,1,0};
void setup() {
  size(400,400);
  background(250);
  stroke(250);
  strokeWeight(3);
  for(int i = 0 ; i < width ; i+=scl) {line(0+i,0,0+i,height);};
  for(int i = 0 ; i < height ; i+=scl) {line(0,0+i,width,0+i);};
  x.add(1);
  y.add(1);
}

void draw() {
  background(250);
  stroke(250);
  for(int i = 0 ; i < width ; i+=scl) {line(0+i,0,0+i,height);};
  for(int i = 0 ; i < height ; i+=scl) {line(0,0+i,width,0+i);};
  stroke(0);
  strokeWeight(14);
  line(0,0,width,0);
  line(width,0,width,height);
  line(width,height,0,height);
  line(0,height,0,0);
  strokeWeight(3);
  for(int i = 0 ; i < x.size() ; i++) {
    fill(0,255,0);
    rect(x.get(i)*scl, y.get(i)*scl, scl,scl);
    fill(255,0,0);
    rect(apx*scl,apy*scl,scl,scl);
  }
  
  if (frameCount%speedinv==0) {
  if ((dir == 0) && (hy > 0)) {hy -= 1;};
  if ((dir == 1) && (hx<width/scl-1)) {hx += 1;};
  if ((dir == 2) && (hy<height/scl-1)) {hy += 1;};
  if ((dir == 3) && (hx > 0)) {hx -= 1;};
  x.add(0,x.get(0)+dx[dir]);
  y.add(0,y.get(0)+dy[dir]);
  for(int i=1;i<x.size();i++) {if(x.get(0)==x.get(i)&&y.get(0)==y.get(i)) {exit();}};
  
  
  
  if (hx == apx && hy == apy) {
  apx = int(int(random(scl,width-scl))/scl);
  apy = int(int(random(scl,height-scl))/scl);
  } else {
    x.remove(x.size()-1);
    y.remove(y.size()-1);
  }
  
 } if(hx - 1 == -1) {exit();};if(hy - 1 == -1) {exit();};if(hx - (width/scl-2) > 0) {exit();};if(hy - (height/scl-2) > 0) {exit();};
} void keyPressed() {
  if ((key == 'w') && (dir != 2) && (hy > 0)) {dir = 0;};if ((key == 'd') && (dir != 3) && (hx<width/scl-1)) {dir = 1;};if ((key == 's') && (dir != 0) && (hy<height/scl-1)) {dir = 2;};if ((key == 'a') && (dir != 1) && (hx > 0)) {dir = 3;};
}

```

---

<div class="post-metadata">

### Author: ![Snake](https://avatars.discourse-cdn.com/v4/letter/s/50afbb/32.png) [@Snake](https://discourse.processing.org/u/Snake)
#### Post date: [April 3, 2020, 2:43am UTC](https://discourse.processing.org/t/snake-game-code/1725/22 "2020-04-03T02:43:36Z")

</div>

Is This The Final Completed Product

[Next page](https://discourse.processing.org/t/snake-game-code/1725.md?page=2)
