• fullscreen
  • SnakeFood.pde
  • SnakePart.pde
  • paul_s_snake.pde
  • class SnakeFood { 
      int x, y; 
      SnakeFood() { 
        x = int(random(width/20))*20; 
        y = int(random(height/20))*20;
      } 
      void display() { 
        fill(219, 20, 20); 
        strokeWeight(5);
        rect(x, y, 20, 20);
      }
    }
    
    class SnakePart { 
      int x, y; 
      SnakePart(int newX, int newY) { 
        x = newX; 
        y = newY;
      } 
      void display() { 
        fill(0,0,255,76); 
        ellipseMode(CORNER); 
        ellipse(x, y, 20, 20);
      }
    } 
    
    
    char direction;
     
    ArrayList snake = new ArrayList();
    SnakePart head;
    SnakeFood food;
     
    void setup(){
      frameRate(8);
      snake.add(new SnakePart(0,0));
      food = new SnakeFood();
      size(400,400);
      smooth();
    }
     
    void draw(){
      background(50,10);
      head = (SnakePart)snake.get(0);
      moveBody();
      moveHead();
      checkGameOver();
      //Check if the snake ate the food
      if(dist(head.x, head.y, food.x, food.y) < 5){
        food = new SnakeFood();
        snake.add(new SnakePart(head.x, head.y));
      }
      // Draw everything to the screen.
      food.display();
      for(int i = 0; i < snake.size(); i++){
        SnakePart sp = (SnakePart)snake.get(i);
        sp.display();
      }
    }
     
    void keyPressed(){
      if(key == 'a' || key == 'A') direction = 'w';
      if(key == 'd' || key == 'D') direction = 'e';
      if(key == 'w' || key == 'W') direction = 'n';
      if(key == 's' || key == 'S') direction = 's';
    }
     
    void moveHead(){
      switch(direction){
      case 'n':
        head.y -= 20;
        break;
      case 's':
        head.y += 20;
        break;
      case 'e':
        head.x += 20;
        break;
      case 'w':   
        head.x -= 20;
        break;
      }
    }
     
    void moveBody(){
      for(int i = snake.size()-1; i > 0; i--){
        SnakePart front = (SnakePart)snake.get(i-1);
        SnakePart back = (SnakePart)snake.get(i);
        back.x = front.x;
        back.y = front.y;
      }
    }
     
    void checkGameOver(){
      for(int i = 1; i < snake.size(); i++){
        SnakePart sp = (SnakePart)snake.get(i);
        if(dist(head.x, head.y, sp.x, sp.y) < 5){
          println("GAME OVER!");
          noLoop();
        }
      }
      if(head.x < 0 || head.x > width || head.y < 0 || head.y > height){
        println("GAME OVER!");
        noLoop();
      }
    }
    

    code

    tweaks (0)

    about this sketch

    This sketch is running as Java applet, exported from Processing.

    license

    advertisement

    Joshua Moody

    Snake

    Add to Faves Me Likey@!
    You must login/register to add this sketch to your favorites.

    A classic game with and Arraylist

    You need to login/register to comment.