Java Snake

By pickle16 on Dec 13, 2010

meh just a snake game....i made this like a year ago when i was just learning java ;p

i was bored and saw no one has posted one so i figure i'll post the first one. :)

*known bugs:

  1. can't restart without refreshing page
  2. rapid movement causes snake to turn back into self

URL: http://picklecodes.co.cc/Games/Snake/

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.util.*;

public class Snake extends Applet implements KeyListener,  Runnable
{
  // The object we will use to write with instead of the standard screen graphics
  Graphics bufferGraphics;
  // The image that will contain everything that has been drawn on
  // bufferGraphics.
  Image offscreen;
  // To get the width and height of the applet.
  Dimension dim;
  Random r=new Random();
  Level level=new Level();

  boolean playedLastGame=false;
  int bodies=2;
  int lives=3;
  int countApple=0;
  Wall[] w = new Wall[500];
  Section[] s=new Section[300];
  Apple[] a=new Apple[10];
  MovePoint[] mp=new MovePoint[100];

  //credits
  String version = "1.0";
  boolean game,puase;
  boolean gameOver;
  int GameOverTimer=0;
  int x,y;

  //timer
  Thread t,t1;

  public void start(){
  t = new Thread(this);
  t.start();
}

public void run(){
    t1 = Thread.currentThread();
    while(t1 == t){
        updateSpace();
        try{
             t1.sleep(100);    
            }catch(InterruptedException e){}
        }
}

public void init() {
  // We'll ask the width and height by this
  dim = getSize();
  setBackground(Color.black);
  // Create an offscreen image to draw on
  // Make it the size of the applet, this is just perfect larger
  // size could slow it down unnecessary.
  offscreen = createImage(dim.width,dim.height);
  // by doing this everything that is drawn by bufferGraphics
  // will be written on the offscreen image.
  bufferGraphics = offscreen.getGraphics(); 

  for (int i=0; i < s.length; i++) { s[i]=null; }
  for (int i=0; i < w.length; i++) { w[i]=null; }
  for (int i=0; i < a.length; i++) { a[i]=null; }
  for (int i=0; i < mp.length; i++) { mp[i]=null; }
  level.setLevel(0);

  this.setFocusable(true);
  this.requestFocus();
 addKeyListener(this);
 game=false;
}

public void reinit() 
{
int tempGoal = level.getGoal();
level.reset();
level.setGoal(tempGoal + 5);
bodies=2;
countApple=0;

  for (int i=0; i < s.length; i++) { s[i]=null; }
  for (int i=0; i < w.length; i++) { w[i]=null; }
  for (int i=0; i < a.length; i++) { 
            a[i]=new Apple(); 
            a[i].init();
        for (int ii=0; ii < w.length; ii++) {
            if (w[ii] != null) {
while (w[ii].x == a[i].x && w[ii].y == a[i].y) { a[i].init(); ii=0; }
}
}

    }
  for (int i=0; i < mp.length; i++) { mp[i]=null; }
  s[0]=new Section();
  s[1]=new Section();
  s[2]=new Section();
  s[0].init(250,250,"right");
  s[1].init(245,250,"right");
  s[2].init(240,250,"right");
  s[0].setHead(true);
        puase=true;
}

public boolean updateSpace() {
  // Wipe off everything that has been drawn before
  // Otherwise previous drawings would also be displayed.
  bufferGraphics.clearRect(0,0,dim.width,dim.height);

if (game == false) {
if (gameOver == true) {
 bufferGraphics.setColor(Color.green);
 bufferGraphics.drawString("Game Over!",dim.width / 2 - 100,dim.height / 2);
 GameOverTimer++;
 if (GameOverTimer >= 10) { 
     gameOver=false;
     GameOverTimer=0;
    }
}
else {
 bufferGraphics.setColor(Color.green);
 bufferGraphics.drawString("Pickled Snake",dim.width / 2 - 100,dim.height / 2);
 bufferGraphics.drawString("Press Space to Start ",dim.width / 2 - 100,dim.height / 2 + 15);
}
}
else {

if (puase != true) {
  level.time+=0.1;
  level.time=Round(level.time,1);
}

  for (int i=0; i < s.length; i++) {
    if (s[i] != null) {
        if (puase != true) { s[i].move(); }
      //check collsion with apples
      if (bodies <= s.length) {
        for (int ii=0; ii < a.length; ii++) {
            if (a[ii] != null) {
          if (s[0].x == a[ii].x && s[0].y == a[ii].y) {   
            int X=s[bodies].x;
            int Y=s[bodies].y;
            String D=s[bodies].direction;
            bodies++;
            if (D == "up") {
              s[bodies]=new Section();
              s[bodies].init(X, Y+5, D);
            }
            if (D == "down") {
              s[bodies]=new Section();
              s[bodies].init(X, Y-5,  D);
            }
             if (D == "right") {
              s[bodies]=new Section();
              s[bodies].init(X-5, Y, D);
            }
             if (D == "left") {
              s[bodies]=new Section();
              s[bodies].init(X+5, Y, D);
            }
                 a[ii].init();
                  for (int iii=0; iii < w.length; iii++) {
            if (w[iii] != null) {
         while (w[iii].x == a[ii].x && w[iii].y == a[ii].y) { a[ii].init(); iii=0; }
    }
}
              countApple++;
              break;
          }
        }
       }
      }
       //check if snake section collides with self

              if (i != 0 && s[0].x == s[i].x && s[0].y == s[i].y || s[0].x < 0 || s[0].y < 0 ||  s[0].x > dim.width  || s[0].y > dim.height) { 
                  LoseLive();
                  return false;
            }

 //check if snake section is over move point if so then move in the direction told by move point
      for (int ii=0; ii < mp.length; ii++) {
        if (mp[ii] != null) {
          if (s[i].x == mp[ii].x && s[i].y == mp[ii].y) { 
            s[i].direction=mp[ii].direction;
            if (bodies == i) { mp[ii]=null; }
          }
        }
      }
      s[i].Paint(bufferGraphics);
    }
  }
          //paint walls
               for (int i=0; i < w.length; i++) { 
                   if (w[i] != null) {
                     //check if snake section collides with a wall
                   if (s[0].x == w[i].x && s[0].y == w[i].y) {
                     LoseLive();
                     return false;
                    } 
                   w[i].Paint(bufferGraphics);
                }
                }
  for (int i=0; i < a.length; i++) {
    a[i].Paint(bufferGraphics);
  }

    //check the level goal
            if (countApple >= level.getGoal()) { 
                level.setLevel(level.getLevel() + 1);
                reinit();
            }

  bufferGraphics.setColor(Color.orange);
  bufferGraphics.drawString("Time: "+ level.time,10,15);
  bufferGraphics.drawString("Lives: "+ lives,80,15);
  bufferGraphics.drawString("Level: "+ level.getLevel(),(dim.width / 2) - 75,15);
  bufferGraphics.drawString("Goal: "+ level.getGoal(),dim.width - 100,15);
  bufferGraphics.drawString("Apples:  "+ countApple,dim.width - 100,30);

  if (puase == true) {
bufferGraphics.setColor(Color.green);
bufferGraphics.drawString("Puase ",dim.width / 2 ,dim.height / 2);
}

}

 repaint();
 return true;
}
/** this controls the lives */
public void LoseLive() { 
lives--;
if (lives <= 0) { EndGame(); }
reinit();
}
/** this ends the game */
public void EndGame() { 
resetGame();
gameOver=true;
game=false; 
}
/** this resets the game and destroys everything not being used */
public void resetGame() {
level.reset();
lives=3;
 for (int i=0; i < s.length; i++) { s[i]=null; }
  for (int i=0; i < w.length; i++) { w[i]=null; }
  for (int i=0; i < a.length; i++) { a[i]=null; }
  for (int i=0; i < mp.length; i++) { mp[i]=null; }
}
//paint
public void paint(Graphics g) 
{

  //credits
  bufferGraphics.setColor(Color.orange);
  bufferGraphics.drawString("Java Snake game "+ version,10,470);
  bufferGraphics.drawString("By: Pickle",10,480);

  // draw the offscreen image to the screen like a normal image.
  // Since offscreen is the screen width we start at 0,0.
  g.drawImage(offscreen,0,0,this); 
}
public void update(Graphics g)  { paint(g); } 

//key events
public void keyPressed(KeyEvent e ) { 
if (puase != true) {
  switch (e.getKeyCode()) {
    case KeyEvent.VK_LEFT:  
    if (s[0].direction == "left" || s[0].direction == "right") {}
else {
      s[0].direction="left";
      for (int i=0; i < mp.length; i++) {
        if (mp[i] == null) {
          mp[i]=new MovePoint();
          mp[i].init(s[0].x,s[0].y,"left");
          break;
        }
      }
    }
    break;
    case KeyEvent.VK_RIGHT:
    if (s[0].direction == "left" || s[0].direction == "right") {}
else {
      s[0].direction="right";
      for (int i=0; i < mp.length;  i++) {
              if (mp[i] == null) {
           mp[i]=new MovePoint();
          mp[i].init(s[0].x,s[0].y,"right");
          break;
        }
      }
    }
    break;
    case KeyEvent.VK_UP: 
    if (s[0].direction == "up" || s[0].direction == "down") {}
else {
      s[0].direction="up";
      for (int i=0; i < mp.length;  i++) {
              if (mp[i] == null) {
          mp[i]=new MovePoint();
          mp[i].init(s[0].x,s[0].y,"up");
          break;
        }
      }
    }
    break;
    case KeyEvent.VK_DOWN:  
    if (s[0].direction == "up" || s[0].direction == "down") {}
else {
      s[0].direction="down";
      for (int i=0; i < mp.length;  i++) {
              if (mp[i] == null) {
          mp[i]=new MovePoint();       
          mp[i].init(s[0].x,s[0].y,"down");
          break;
        }
      }
    }
    break;
    case KeyEvent.VK_SPACE:  
    if (game == false) {
    game=true; 
    reinit();
}
    break;
  }
}

   if (e.getKeyChar() == 'p') {
    if (puase == true) { puase=false; }
else { puase=true; }
}

}

public void keyReleased( KeyEvent e ) { }
public void keyTyped( KeyEvent e ) {}

//for my rounding needs
public static float Round(float Rval, int Rpl) {
  float p = (float)Math.pow(10,Rpl);
  Rval = Rval * p;
  float tmp = Math.round(Rval);
  return (float)tmp/p;
}

/**
 * records Level Info
 */
private class Level {
int level = 0;
int goal=0;
float time = 0.0f;
public Level() { }

public void reset() {
goal=0;
time = 0.0f;
}
public void setLevel(int l) { level=l; }
public void setGoal(int g) { goal=g; }
public int getLevel() { return level; }
public int getGoal() { return goal; }
}

/**
*  record snake sections
*/
private class Section {
  int x,y;
  String direction=null;
  boolean head=false;
  public Section() { }
  public void init(int X, int Y,  String B) {
    direction=B;
    x=X;
    y=Y;
  }
  public void setHead(boolean h) { head=h; }
  public void move() {
    if (direction == "up") { y-=5; }
    if (direction == "down") { y+=5; }
    if (direction == "right") { x+=5; }
    if (direction == "left") { x-=5; }
  }
  public void Paint(Graphics g) {
      g.setColor(Color.green);
      g.fillOval(x,y,5,5);
      if (head == true) { 
      g.setColor(Color.black);
      g.fillOval(x - 2,y - 2,2,2);
      g.fillOval(x - 4,y - 2,2,2);
    }
  }
  //end class section
}

/**
* record Move point
*/
private class MovePoint {
  int x,y;
  String direction;
  public MovePoint() {  }
  public void init(int X, int Y, String B) {
    direction=B;
    x=X;
    y=Y;
  }
  //end class section
}
/**
*Draw Wall Randomly
*/
private class Wall  {
  int x,y;
  public Wall() { }
  public void init(int X, int Y) { 
    x=X - (X % 5);
    y=Y - (Y % 5);
  }
  public void Paint(Graphics g) {
      g.setColor(Color.gray);
      g.fillOval(x,y,5,5);
  }
  //end class Wall
}

/**
*Draw Apple Randomly
*/
private class Apple {
  int x,y;
  public Apple() { }
  public void init() { 
    int rand=r.nextInt(dim.width);
    x=rand - (rand % 5);
    rand=r.nextInt(dim.height);
    y=rand - (rand % 5);
  }
  public void Paint(Graphics g) {
      g.setColor(Color.red);
      g.fillOval(x,y,5,5);
  }
  //end class apple
}

//end
}

Comments

Sign in to comment.
Sangeetha   -  Oct 30, 2013

Can you please tell me how to run it?

KilllerX  -  Oct 30, 2013

How are you trying to run it, This is meant to be put on a website, and ran from there.

Sign in to comment

pickle16   -  Dec 17, 2010

yeah those the only two bugs that i found....
and to lazy to fix them. :p

 Respond  
Bielie   -  Dec 16, 2010

Needs fixes :p It looks nice but cant play. If u use the arrows to quik it gets a reset. You should make a clickeble start function and a total reset of the app after 2 seconds of game over. :)

 Respond  
pickle16   -  Dec 15, 2010

thanks! :s

 Respond  
sunslayer   -  Dec 14, 2010

@SunnyD press p to start the game

 Respond  
Sorasyn   -  Dec 14, 2010

The website Snake version doesn't run; it mis-spells pause and freezes I guess? Lol

 Respond  
Pasha_fail   -  Dec 14, 2010

Nice, I Like It Very Much :)

 Respond  
MixXeduP   -  Dec 14, 2010

Very nice. :)

shonil dabre  -  Jul 30, 2015

the game runs when u press "SPACE" button & then press"P" to start.the game starts..
Awsum program

Sign in to comment

Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.