You are viewing our Forum Archives. To view or take place in current topics click here.
[JAVA] Snake Game Source Code Released
Posted:
[JAVA] Snake Game Source Code ReleasedPosted:
Status: Offline
Joined: May 22, 201113Year Member
Posts: 235
Reputation Power: 9
Status: Offline
Joined: May 22, 201113Year Member
Posts: 235
Reputation Power: 9
Someone has asked me to release my source code for my snake game. Here it is.
The frame setup and the overall navigation of the project
The Title menu
The games (Campaign, Snake Original, Snake Colored)
The levels. This is the design and creation of the levels
Notes
Lastly I have fixed the glitch with the HighScores message appearing more then once. You can either compile the code given, or you can download it here: [ Register or Signin to view external links. ]
The frame setup and the overall navigation of the project
package SnakeTimer;
import javax.swing.*;
public class snake {
private SnakeG sg = new SnakeG ();
private SnakeMenu sm = new SnakeMenu ();
private JFrame frame;
private CSnakeG csg = new CSnakeG ();
private OSnakeG osg = new OSnakeG ();
public snake (){
frame = new JFrame ("Snake - v2.0");
frame.setSize (500,500);
frame.setResizable (false);
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.add (sm);
frame.setVisible (true);
sm.startMenu(this);
}
public void campaign (){
frame.remove (sm);
frame.add(sg);
frame.validate();
sg.startGraphics(this);
}
public void freeRunNorm(){
frame.remove(sm);
frame.add (osg);
frame.validate();
osg.startGraphics(this);
}
public void freeRunRainbow (){
frame.remove(sm);
frame.add(csg);
frame.validate();
csg.startGraphics(this);
}
public void highScore (){
}
public void menu (int option){
if (option == 1)
frame.remove(sg);
else if (option == 2)
frame.remove(osg);
else if (option == 3)
frame.remove(csg);
frame.add (sm);
frame.validate ();
sm.startMenu(this);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
snake s = new snake ();
}
}
The Title menu
package SnakeTimer;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class SnakeMenu extends JPanel implements MouseListener, MouseMotionListener{
private int mx, my;
private Rectangle campaign = new Rectangle (50,50,160,50);
private Rectangle freePlayN = new Rectangle (50,125,160,50);
private Rectangle freePlayC = new Rectangle (50,200,160,50);
private Rectangle highScore = new Rectangle (50,275,160,50);
private snake snake;
private Color campSel = Color.black;
private Color fPSel = Color.black;
private Color fPCSel = Color.black;
private Color hSSel = Color.black;
public void startMenu (snake s){
snake = s;
addMouseListener (this);
addMouseMotionListener (this);
repaint ();
}
public void paintComponent (Graphics g){
super.paintComponent (g);
g.setColor(Color.orange);
g.fillRect (50,50,160,50);
g.setColor(Color.LIGHT_GRAY);
g.fillRect (50,125,160,50);
g.setColor(Color.magenta);
g.fillRect (50,200,160,50);
g.setColor (Color.red);
g.fillRect (50,275,160,50);
g.setColor (Color.black);
g.setFont (new Font ("Arial", 20,20));
g.setColor(campSel);
g.drawString("Campaign", 80, 80);
g.setColor(fPSel);
g.drawString("Free Play", 80, 155);
g.setColor(fPCSel);
g.drawString("Free Play - Color", 55, 230);
g.setColor(hSSel);
g.drawString("High Scores", 75, 305);
g.setColor(Color.red);
g.setFont (new Font ("Arial", 15,15));
g.drawString ("Use the arrow keys to move", 253,150);
g.drawString("Catch the black circle (target)", 250, 170);
g.drawString ("Avoid the brown walls", 265,190);
g.drawString("Press \"T\" to return to Menu", 260,210);
g.drawString ("Press any other button to pause", 250,230);
}
@Override
public void mouseDragged(MouseEvent arg0) {
}
@Override
public void mouseMoved(MouseEvent e) {
mx = e.getX();
my = e.getY();
campSel = Color.black;
fPSel = Color.black;
fPCSel = Color.black;
hSSel = Color.black;
if (campaign.contains (mx,my)){
campSel = Color.white;
}
else if (freePlayN.contains(mx,my)){
fPSel = Color.white;
}
else if (freePlayC.contains(mx,my)){
fPCSel = Color.white;
}
else if (highScore.contains(mx,my)){
hSSel = Color.white;
}
repaint();
}
@Override
public void mouseClicked(MouseEvent arg0) {
}
@Override
public void mouseEntered(MouseEvent arg0) {
}
@Override
public void mouseExited(MouseEvent arg0) {
}
@Override
public void mousePressed(MouseEvent e) {
if (campaign.contains(mx,my)){
removeMouseListener(this);
removeMouseMotionListener(this);
snake.campaign();
}
else if (freePlayN.contains(mx,my)){
removeMouseListener(this);
removeMouseMotionListener(this);
snake.freeRunNorm();
}
else if (freePlayC.contains(mx,my)){
removeMouseListener(this);
removeMouseMotionListener(this);
snake.freeRunRainbow();
}
else if (highScore.contains(mx,my)){
JOptionPane.showMessageDialog(null, "This Option has not been implemented yet!");
}
}
@Override
public void mouseReleased(MouseEvent arg0) {
}
}
The games (Campaign, Snake Original, Snake Colored)
package SnakeTimer;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class SnakeG extends JPanel implements KeyListener, Runnable, ActionListener{
private Vector<Point> snake = new Vector<Point> (5,10);
private Point target;
private Rectangle targetRect;
private Rectangle frameRect = new Rectangle (0,0,490,470);
private int score = 0;
private boolean alive = true;
private Vector<Rectangle> snakeRectangle = new Vector<Rectangle> (5,10);
private int level = 0;
private Level1 l1 = new Level1 ();
private Level2 l2 = new Level2 ();
private Level3 l3 = new Level3 ();
private Level4 l4 = new Level4 ();
private Level5 l5 = new Level5 ();
private Level6 l6 = new Level6 ();
private boolean lvlup = false;
private boolean restart = true;
private snake snakeClass;
private Timer timer = new Timer (75,this);
private Thread thread;
private boolean returnToMenu;
public void startGraphics (snake s){
snakeClass = s;
score = 0;
snake.removeAllElements();
snakeRectangle.removeAllElements();
this.addKeyListener(this);
setup ();
}
private void setup() {
// TODO Auto-generated method stub
System.out.println ("Width: " + this.getWidth() + "\tHeight: " + this.getHeight());
repaint();
grabFocus();
snake.add (new Point (250,230));
genTarget();
snakeRectangle.add(new Rectangle (250,230,10,10));
runThread = true;
timer.start();
}
private void addBall() {
if (previous.equals("right")){
snake.add (new Point (snake.lastElement().x - 10, snake.lastElement().y));
}
if (previous.equals("left")){
snake.add (new Point (snake.lastElement().x + 10, snake.lastElement().y));
}
if (previous.equals("up")){
snake.add (new Point (snake.lastElement().x, snake.lastElement().y + 10));
}
if (previous.equals("down")){
snake.add (new Point (snake.lastElement().x, snake.lastElement().y - 10));
}
snakeRectangle.add(new Rectangle ((int)snake.lastElement().x, (int) snake.lastElement().y, 10,10));
}
public void paintComponent (Graphics g){
//TODO GRAPHICS AREA
super.paintComponent (g);
// print snake
for (Point x : snake){
if (snake.elementAt(0) == x){
g.setColor (Color.black);
}
else {
g.setColor(new Color (100,100,100));
}
g.fillOval((int)x.getX(),(int)x.getY(),10, 10);
}
g.setColor (Color.black);
// check for death
if (alive == false && runThread == false){
System.out.println ("Lost message entered");
g.setFont (new Font ("Arail", 30,30));
g.drawString("You Lose!", 200, 220);
g.setFont (new Font ("Arial", 10,10));
g.drawString("Press N for a new Game", 210,230);
g.setFont(new Font ("Arial", 17,17));
g.drawString("Your Final Snake Size Was: " + snake.size(), 160, 250);
}
else if (alive = true && wasPressed == false && level != 0 && restart == false){
g.setFont (new Font ("Arail", 30,30));
g.drawString("Level UP!", 200, 220);
}
// print snake size
else {
g.setFont(new Font ("Arial", 15,15));
g.drawString("Snake size: " + snake.size(), 200, 220);
}
// draw score and target
g.setFont(new Font ("Arial", 15,15));
g.drawString("Score: " + score, 220, 15);
g.fillOval((int)(target.getX()), (int)(target.getY()), 10,10);
//////////////////////////
/////////LEVELS///////////
//////////////////////////
if (level == 0){}
else if (level == 1 && runThread == true){
g.setColor (new Color (92,51,23));
for (Point x : l1.wall){
g.fillRect(x.x, x.y, (int)((l1.wallRect.elementAt(l1.wall.indexOf(x))).getWidth()), (int)((l1.wallRect.elementAt(l1.wall.indexOf(x))).getHeight()));
}
}
else if (level == 2 && runThread == true){
g.setColor (new Color (92,51,23));
for (Point x : l2.wall){
g.fillRect(x.x, x.y, (int)((l2.wallRect.elementAt(l2.wall.indexOf(x))).getWidth()), (int)((l2.wallRect.elementAt(l2.wall.indexOf(x))).getHeight()));
}
}
else if (level == 3 && runThread == true){
g.setColor (new Color (92,51,23));
for (Point x : l3.wall){
g.fillRect(x.x, x.y, (int)((l3.wallRect.elementAt(l3.wall.indexOf(x))).getWidth()), (int)((l3.wallRect.elementAt(l3.wall.indexOf(x))).getHeight()));
}
}
else if (level == 4 && runThread == true){
g.setColor (new Color (92,51,23));
for (Point x : l4.wall){
g.fillRect(x.x, x.y, (int)((l4.wallRect.elementAt(l4.wall.indexOf(x))).getWidth()), (int)((l4.wallRect.elementAt(l4.wall.indexOf(x))).getHeight()));
}
}
else if (level == 5 && runThread == true){
g.setColor (new Color (92,51,23));
for (Point x : l5.wall){
g.fillRect(x.x, x.y, (int)((l5.wallRect.elementAt(l5.wall.indexOf(x))).getWidth()), (int)((l5.wallRect.elementAt(l5.wall.indexOf(x))).getHeight()));
}
}
else if (level == 6 && runThread == true){
g.setColor (new Color (92,51,23));
for (Point x : l6.wall){
g.fillRect(x.x, x.y, (int)((l6.wallRect.elementAt(l6.wall.indexOf(x))).getWidth()), (int)((l6.wallRect.elementAt(l6.wall.indexOf(x))).getHeight()));
}
g.setColor (Color.white);
g.setFont(new Font ("Arial", 20,20));
g.drawString("You won!", 205, 260);
g.setFont(new Font ("Arial", 15,15));
g.drawString("What has been created", 175,275);
}
}
private String previous;
private boolean wasPressed = false;
private boolean pressed = false;
private boolean up,down,left,right;
private boolean pause = false;
@Override
public void keyPressed(KeyEvent e) {
System.out.println ("KeyListener");
int key = e.getKeyCode();
up = false;
down = false;
left = false;
right = false;
pause = false;
System.out.println (pressed);
if (key == KeyEvent.VK_UP && runThread == true){
up = true;
previous = "up";
}
else if (key == KeyEvent.VK_DOWN && runThread == true){
down = true;
previous = "down";
}
else if (key == KeyEvent.VK_LEFT && runThread == true){
left = true;
previous = "left";
}
else if (key == KeyEvent.VK_RIGHT && runThread == true){
right = true;
previous = "right";
}
else if (key == KeyEvent.VK_N && runThread == false){
restart = true;
resetGame();
}
else if (key == KeyEvent.VK_T){
runThread = false;
previous = "a";
returnToMenu = true;
}
else {
pause = true;
}
if (previous == null){
runThread = true;
}
if (pause){
timer.stop();
}
else {
timer.start();
}
}
//TODO Reset Game
private void resetGame() {
snake.removeAllElements();
snakeRectangle.removeAllElements();
target = null;
targetRect = null;
wasPressed = false;
up = false; down = false; left = false; right = false;
score = 0;
alive = true;
lvlup = false;
setup();
}
@Override
public void keyReleased(KeyEvent e) {
wasPressed = true;
}
@Override
public void keyTyped(KeyEvent e){}
private boolean runThread = true;
@Override
public void run() {
System.out.println ("Started Thread");
//System.out.println ("Up: " + up + "\tDown: " + down + "\tLeft: " + left + "\tRight: " + right);
//moving the snake
if (up == true){
//System.out.println ("entered if");
for (int i = snake.size() - 1; i > -1; i--){
if (i == 0){
snake.firstElement().y -= 10;
}
else {
snake.elementAt(i).y = snake.elementAt(i - 1).y;
}
}
}
else if (down == true){
for (int i = snake.size() - 1; i > -1; i--){
if (i == 0){
snake.firstElement().y += 10;
}
else {
snake.elementAt(i).y = snake.elementAt(i - 1).y;
}
}
}
else if (left == true){
for (int i = snake.size() - 1; i > -1; i--){
if (i == 0){
snake.firstElement().x -= 10;
}
else {
snake.elementAt(i).x = snake.elementAt(i - 1).x;
}
}
}
else if (right == true){
for (int i = snake.size() - 1; i > -1; i--){
if (i == 0){
snake.firstElement().x += 10;
}
else {
snake.elementAt(i).x = snake.elementAt(i - 1).x;
}
}
}
//System.out.println ("At start of turning");
//Turning the snake
if (wasPressed == true){
if (previous.equals ("up")){
for (int i = snake.size() - 1; i > 0; i--){
snake.elementAt(i).x = snake.elementAt(i - 1).x;
}
}
else if (previous.equals("down")){
for (int i = snake.size() - 1; i > 0; i--){
snake.elementAt(i).x = snake.elementAt(i - 1).x;
}
}
else if (previous.equals("left")){
for (int i = snake.size() - 1; i > 0; i--){
snake.elementAt(i).y = snake.elementAt(i - 1).y;
}
}
else if (previous.equals("right")){
for (int i = snake.size() - 1; i > 0; i--){
snake.elementAt(i).y = snake.elementAt(i - 1).y;
}
}
else {
}
}
updateRect();
collisionDetect();
lvlUp();
repaint();
if (lvlup == true){
runThread = false;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (lvlup == true){
resetGame();
}
if (returnToMenu == true){
timer.stop();
returnToMenu = false;
removeKeyListener (this);
snakeClass.menu(3);
}
}
//TODO Level UP
private void lvlUp() {
if (level == 0 && score >= 20){
level += 1;
lvlup = true;
score = 0;
restart = false;
}
else if (level == 1 && score >= 25){
level += 1;
lvlup = true;
score = 0;
restart = false;
}
else if (level == 2 && score >= 30){
level += 1;
lvlup = true;
score = 0;
restart = false;
}
else if (level == 3 && score >= 35){
level += 1;
lvlup = true;
score = 0;
restart = false;
}
else if (level == 4 && score >= 40){
level += 1;
lvlup = true;
score = 0;
restart = false;
}
else if (level == 5 && score >= 45){
level += 1;
lvlup = true;
score = 0;
restart = false;
}
}
private void updateRect() {
for (int i = 0; i < snake.size(); i++){
snakeRectangle.get(i).setLocation(snake.elementAt(i));
}
}
//TODO Collision Detection
private void collisionDetect() {
// check if lost game
for (int i = 0; i < snake.size(); i++){
//System.out.println("Z: " + z + " I " + i);
if (i == 0){
//System.out.println("z = i accessed");
}
else {
if (snakeRectangle.firstElement().contains((snakeRectangle.elementAt(i).getX()), (snakeRectangle.elementAt(i).getY()))){
//System.out.println("2 elements are the same");
lost();
}
}
}
// check if hit walls
if (level == 1){
for (Rectangle rect : l1.wallRect){
if (rect.contains(snakeRectangle.firstElement().x, snakeRectangle.firstElement().y)){
lost();
}
}
}
else if (level == 2){
for (Rectangle rect : l2.wallRect){
if (rect.contains(snakeRectangle.firstElement().x, snakeRectangle.firstElement().y)){
lost();
}
}
}
else if (level == 3){
for (Rectangle rect : l3.wallRect){
if (rect.contains(snakeRectangle.firstElement().x, snakeRectangle.firstElement().y)){
lost();
}
}
}
else if (level == 4){
for (Rectangle rect : l4.wallRect){
if (rect.contains(snakeRectangle.firstElement().x, snakeRectangle.firstElement().y)){
lost();
}
}
}
else if (level == 5){
for (Rectangle rect : l5.wallRect){
if (rect.contains(snakeRectangle.firstElement().x, snakeRectangle.firstElement().y)){
lost();
}
}
}
else if (level == 6){
for (Rectangle rect : l6.wallRect){
if (rect.contains(snakeRectangle.firstElement().x, snakeRectangle.firstElement().y)){
lost();
}
}
}
if (!frameRect.contains(snake.firstElement())){
lost();
}
// check if target hit
if (snakeRectangle.firstElement().contains(target)){
addBall();
genTarget();
}
}
private void lost() {
timer.stop();
runThread = false;
alive = false;
repaint();
}
//TODO Generate Target
private void genTarget (){
target = new Point ((int) (Math.random () * 48)* 10,(int) (Math.random () * 47) * 10);
if (level == 1){
for (Rectangle rect : l1.wallRect){
if (rect.contains(target)){
genTarget();
}
}
}
else if (level == 2){
for (Rectangle rect : l2.wallRect){
if (rect.contains(target)){
genTarget();
}
}
}
else if (level == 3){
for (Rectangle rect : l3.wallRect){
if (rect.contains(target)){
genTarget();
}
}
}
else if (level == 4){
for (Rectangle rect : l4.wallRect){
if (rect.contains(target)){
genTarget();
}
}
}
else if (level == 5){
for (Rectangle rect : l5.wallRect){
if (rect.contains(target)){
genTarget();
}
}
}
else if (level == 6){
for (Rectangle rect : l6.wallRect){
if (rect.contains(target)){
genTarget();
}
}
}
System.out.println (target);
targetRect = new Rectangle (target, new Dimension (10,10));
if (snake.size() <= 10){
score += 1;
}
else if (snake.size() <= 20){
score += 2;
}
else if (snake.size() <= 30){
score += 3;
}
else if (snake.size() <= 40){
score += 4;
}
else {
score += 5;
}
repaint();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
thread = new Thread (this);
thread.start ();
}
}
package SnakeTimer;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class OSnakeG extends JPanel implements KeyListener, Runnable, ActionListener{
private Vector<Point> snake = new Vector<Point> (5,10);
private Point target;
private Rectangle targetRect;
private Rectangle frameRect = new Rectangle (0,0,490,470);
private snake snakeClass;
private Timer timer = new Timer (75,this);
private Vector<Rectangle> snakeRectangle = new Vector<Rectangle> (5,10);
private Thread thread;
private boolean returnToMenu = false;
public void startGraphics (snake s){
snakeClass = s;
snake.removeAllElements();
snakeRectangle.removeAllElements();
this.addKeyListener(this);
setup();
}
private void setup() {
// TODO Auto-generated method stub
repaint();
grabFocus();
snake.add (new Point (250,250));
genTarget();
snakeRectangle.add(new Rectangle (250,250,10,10));
oRunThread = true;
timer.start();
}
private void addBall() {
// TODO Auto-generated method stub
if (previous.equals("right")){
snake.add (new Point (snake.lastElement().x - 10, snake.lastElement().y));
}
if (previous.equals("left")){
snake.add (new Point (snake.lastElement().x + 10, snake.lastElement().y));
}
if (previous.equals("up")){
snake.add (new Point (snake.lastElement().x, snake.lastElement().y + 10));
}
if (previous.equals("down")){
snake.add (new Point (snake.lastElement().x, snake.lastElement().y - 10));
}
snakeRectangle.add(new Rectangle ((int)snake.lastElement().x, (int) snake.lastElement().y, 10,10));
}
public void paintComponent (Graphics g){
//TODO GRAPHICS AREA
super.paintComponent (g);
for (Point x : snake){
g.fillOval((int)x.getX(),(int)x.getY(),10, 10);
}
if (oRunThread == false){
System.out.println ("Lost message entered");
g.setFont (new Font ("Arail", 30,30));
g.drawString("You Lose!", 200, 220);
g.setFont (new Font ("Arial", 10,10));
g.drawString("Press N for a new Game", 210,230);
g.setFont(new Font ("Arial", 17,17));
g.drawString("Your Final Snake Size Was: " + snake.size(), 160, 250);
}
else {
g.setFont(new Font ("Arial", 15,15));
g.drawString("Snake size: " + snake.size(), 210, 220);
}
g.fillOval((int)(target.getX()), (int)(target.getY()), 10,10);
}
private String previous;
private boolean wasPressed = false;
private boolean pressed = false;
private boolean up,down,left,right;
private boolean pause = false;
@Override
public void keyPressed(KeyEvent e) {
System.out.println ("KeyListener");
int key = e.getKeyCode();
up = false;
down = false;
left = false;
right = false;
pause = false;
System.out.println (pressed);
if (key == KeyEvent.VK_UP && oRunThread == true){
up = true;
previous = "up";
}
else if (key == KeyEvent.VK_DOWN && oRunThread == true){
down = true;
previous = "down";
}
else if (key == KeyEvent.VK_LEFT && oRunThread == true){
left = true;
previous = "left";
}
else if (key == KeyEvent.VK_RIGHT && oRunThread == true){
right = true;
previous = "right";
}
else if (key == KeyEvent.VK_N && oRunThread == false){
resetGame();
}
else if (key == KeyEvent.VK_T){
oRunThread = false;
previous = "a";
returnToMenu = true;
}
else {
pause = false;
}
if (previous == null){
oRunThread = true;
}
if (pause == true){
timer.stop();
}
else {
timer.start();
}
}
private void resetGame() {
// TODO Auto-generated method stub
snake.removeAllElements();
snakeRectangle.removeAllElements();
target = null;
targetRect = null;
wasPressed = false;
setup();
}
@Override
public void keyReleased(KeyEvent e) {
wasPressed = true;
}
@Override
public void keyTyped(KeyEvent e){}
private boolean oRunThread = true;
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println ("Started Thread");
System.out.println ("Up: " + up + "\tDown: " + down + "\tLeft: " + left + "\tRight: " + right);
//moving the snake
if (up == true){
System.out.println ("entered if");
for (int i = snake.size() - 1; i > -1; i--){
if (i == 0){
snake.firstElement().y -= 10;
}
else {
snake.elementAt(i).y = snake.elementAt(i - 1).y;
}
}
}
else if (down == true){
for (int i = snake.size() - 1; i > -1; i--){
if (i == 0){
snake.firstElement().y += 10;
}
else {
snake.elementAt(i).y = snake.elementAt(i - 1).y;
}
}
}
else if (left == true){
for (int i = snake.size() - 1; i > -1; i--){
if (i == 0){
snake.firstElement().x -= 10;
}
else {
snake.elementAt(i).x = snake.elementAt(i - 1).x;
}
}
}
else if (right == true){
for (int i = snake.size() - 1; i > -1; i--){
if (i == 0){
snake.firstElement().x += 10;
}
else {
snake.elementAt(i).x = snake.elementAt(i - 1).x;
}
}
}
System.out.println ("At start of turning");
//Turning the snake
if (wasPressed == true){
if (previous.equals ("up")){
for (int i = snake.size() - 1; i > 0; i--){
snake.elementAt(i).x = snake.elementAt(i - 1).x;
}
}
else if (previous.equals("down")){
for (int i = snake.size() - 1; i > 0; i--){
snake.elementAt(i).x = snake.elementAt(i - 1).x;
}
}
else if (previous.equals("left")){
for (int i = snake.size() - 1; i > 0; i--){
snake.elementAt(i).y = snake.elementAt(i - 1).y;
}
}
else if (previous.equals("right")){
for (int i = snake.size() - 1; i > 0; i--){
snake.elementAt(i).y = snake.elementAt(i - 1).y;
}
}
else {}
}
updateRect();
collisionDetect();
repaint();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (returnToMenu == true){
timer.stop();
returnToMenu = false;
removeKeyListener (this);
snakeClass.menu(2);
}
}
private void updateRect() {
// TODO Auto-generated method stub
for (int i = 0; i < snake.size(); i++){
snakeRectangle.get(i).setLocation(snake.elementAt(i));
}
}
private void collisionDetect() {
// TODO Auto-generated method stub
for (int i = 0; i < snake.size(); i++){
//System.out.println("Z: " + z + " I " + i);
if (i == 0){
System.out.println("z = i accessed");
}
else {
if (snakeRectangle.firstElement().contains((snakeRectangle.elementAt(i).getX()), (snakeRectangle.elementAt(i).getY()))){
System.out.println("2 elements are the same");
lost();
}
}
}
if (!frameRect.contains(snake.firstElement())){
lost();
}
if (snakeRectangle.firstElement().contains(target)){
addBall();
genTarget();
}
}
private void lost() {
// TODO Auto-generated method stub
oRunThread = false;
timer.stop();
repaint();
}
private void genTarget (){
target = new Point ((int) (Math.random () * 48)* 10,(int) (Math.random () * 47) * 10);
System.out.println (target);
targetRect = new Rectangle (target, new Dimension (10,10));
repaint();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
thread = new Thread (this);
thread.start();
}
}
package SnakeTimer;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class CSnakeG extends JPanel implements KeyListener, Runnable, ActionListener{
private Vector<Point> snake = new Vector<Point> (5,10);
private Point target;
private Rectangle targetRect;
private Rectangle frameRect = new Rectangle (0,0,490,470);
private Vector<Color> snakeColor = new Vector<Color> (5,10);
private Color targetColor;
private Vector<Rectangle> snakeRectangle = new Vector<Rectangle> (5,10);
private snake snakeClass;
private Timer timer = new Timer (75,this);
private Thread thread;
public void startGraphics (snake s){
snakeClass = s;
this.addKeyListener(this);
setup();
}
private void setup() {
// TODO Auto-generated method stub
snake.removeAllElements();
snakeRectangle.removeAllElements();
snakeColor.removeAllElements();
targetColor = null;
repaint();
grabFocus();
snake.add (new Point (250,250));
genTarget();
snakeRectangle.add(new Rectangle (250,250,10,10));
snakeColor.add(Color.black);
runThread = true;
timer.start();
}
private void addBall() {
// TODO Auto-generated method stub
snakeColor.add(targetColor);
if (previous.equals("right")){
snake.add (new Point (snake.lastElement().x - 10, snake.lastElement().y));
}
if (previous.equals("left")){
snake.add (new Point (snake.lastElement().x + 10, snake.lastElement().y));
}
if (previous.equals("up")){
snake.add (new Point (snake.lastElement().x, snake.lastElement().y + 10));
}
if (previous.equals("down")){
snake.add (new Point (snake.lastElement().x, snake.lastElement().y - 10));
}
snakeRectangle.add(new Rectangle ((int)snake.lastElement().x, (int) snake.lastElement().y, 10,10));
}
public void paintComponent (Graphics g){
//TODO GRAPHICS AREA
super.paintComponent (g);
for (Point x : snake){
g.setColor(snakeColor.elementAt(snake.indexOf(x)));
g.fillOval((int)x.getX(),(int)x.getY(),10, 10);
}
g.setColor (Color.black);
if (runThread == false){
System.out.println ("Lost message entered");
g.setFont (new Font ("Arail", 30,30));
g.drawString("You Lose!", 200, 220);
g.setFont (new Font ("Arial", 10,10));
g.drawString("Press N for a new Game", 210,230);
g.setFont(new Font ("Arial", 17,17));
g.drawString("Your Final Snake Size Was: " + snake.size(), 160, 250);
}
else {
g.setFont(new Font ("Arial", 15,15));
g.drawString("Snake size: " + snake.size(), 210, 220);
}
g.setColor(targetColor);
g.fillOval((int)(target.getX()), (int)(target.getY()), 10,10);
}
private String previous;
private boolean wasPressed = false;
private boolean pressed = false;
private boolean up,down,left,right;
private boolean pause;
@Override
public void keyPressed(KeyEvent e) {
System.out.println ("KeyListener");
int key = e.getKeyCode();
up = false;
down = false;
left = false;
right = false;
pause = false;
System.out.println (pressed);
if (key == KeyEvent.VK_UP && runThread == true){
up = true;
previous = "up";
}
else if (key == KeyEvent.VK_DOWN && runThread == true){
down = true;
previous = "down";
}
else if (key == KeyEvent.VK_LEFT && runThread == true){
left = true;
previous = "left";
}
else if (key == KeyEvent.VK_RIGHT && runThread == true){
right = true;
previous = "right";
}
else if (key == KeyEvent.VK_N && runThread == false){
resetGame();
}
else if (key == KeyEvent.VK_T){
runThread = false;
previous = "a";
returnToMenu = true;
}
else {
pause = true;
}
if (previous == null){
runThread = true;
}
if (pause == true){
timer.stop();
}
else {
timer.start();
}
}
private boolean returnToMenu = false;
private void resetGame() {
// TODO Auto-generated method stub
snake.removeAllElements();
snakeRectangle.removeAllElements();
target = null;
targetRect = null;
wasPressed = false;
setup();
}
@Override
public void keyReleased(KeyEvent e) {
wasPressed = true;
}
@Override
public void keyTyped(KeyEvent e){}
private boolean runThread = true;
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println ("Started Thread");
System.out.println ("Up: " + up + "\tDown: " + down + "\tLeft: " + left + "\tRight: " + right);
//moving the snake
if (up == true){
System.out.println ("entered if");
for (int i = snake.size() - 1; i > -1; i--){
if (i == 0){
snake.firstElement().y -= 10;
}
else {
snake.elementAt(i).y = snake.elementAt(i - 1).y;
}
}
}
else if (down == true){
for (int i = snake.size() - 1; i > -1; i--){
if (i == 0){
snake.firstElement().y += 10;
}
else {
snake.elementAt(i).y = snake.elementAt(i - 1).y;
}
}
}
else if (left == true){
for (int i = snake.size() - 1; i > -1; i--){
if (i == 0){
snake.firstElement().x -= 10;
}
else {
snake.elementAt(i).x = snake.elementAt(i - 1).x;
}
}
}
else if (right == true){
for (int i = snake.size() - 1; i > -1; i--){
if (i == 0){
snake.firstElement().x += 10;
}
else {
snake.elementAt(i).x = snake.elementAt(i - 1).x;
}
}
}
System.out.println ("At start of turning");
//Turning the snake
if (wasPressed == true){
if (previous.equals ("up")){
for (int i = snake.size() - 1; i > 0; i--){
snake.elementAt(i).x = snake.elementAt(i - 1).x;
}
}
else if (previous.equals("down")){
for (int i = snake.size() - 1; i > 0; i--){
snake.elementAt(i).x = snake.elementAt(i - 1).x;
}
}
else if (previous.equals("left")){
for (int i = snake.size() - 1; i > 0; i--){
snake.elementAt(i).y = snake.elementAt(i - 1).y;
}
}
else if (previous.equals("right")){
for (int i = snake.size() - 1; i > 0; i--){
snake.elementAt(i).y = snake.elementAt(i - 1).y;
}
}
else {}
}
updateRect();
collisionDetect();
repaint();
//System.out.println ("before sleep. runThread: " + runThread);
try {
//System.out.println ("before sleep. runThread: " + runThread);
Thread.sleep(100);
//System.out.println ("After sleep. runThread: " + runThread);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println ("After sleep. runThread: " + runThread);
if (returnToMenu == true){
timer.stop();
returnToMenu = false;
removeKeyListener (this);
snakeClass.menu(3);
}
}
private void updateRect() {
// TODO Auto-generated method stub
for (int i = 0; i < snake.size(); i++){
snakeRectangle.get(i).setLocation(snake.elementAt(i));
}
}
private void collisionDetect() {
// TODO Auto-generated method stub
for (int i = 0; i < snake.size(); i++){
//System.out.println("Z: " + z + " I " + i);
if (i == 0){
System.out.println("z = i accessed");
}
else {
if (snakeRectangle.firstElement().contains((snakeRectangle.elementAt(i).getX()), (snakeRectangle.elementAt(i).getY()))){
System.out.println("2 elements are the same");
lost();
}
}
}
if (!frameRect.contains(snake.firstElement())){
lost();
}
if (snakeRectangle.firstElement().contains(target)){
addBall();
genTarget();
}
}
private void lost() {
// TODO Auto-generated method stub
runThread = false;
timer.stop();
repaint();
}
private void genTarget (){
target = new Point ((int) (Math.random () * 48)* 10,(int) (Math.random () * 47) * 10);
System.out.println (target);
targetRect = new Rectangle (target, new Dimension (10,10));
int colorGen = (int) (Math.random() * 10);
if (colorGen == 0){
targetColor = Color.red;
}
else if (colorGen == 1){
targetColor = Color.blue;
}
else if (colorGen == 2){
targetColor = Color.green;
}
else if (colorGen == 3){
targetColor = Color.yellow;
}
else if (colorGen == 4){
targetColor = Color.gray;
}
else if (colorGen == 5){
targetColor = Color.cyan;
}
else if (colorGen == 6){
targetColor = Color.orange;
}
else if (colorGen == 7){
targetColor = Color.magenta;
}
else if (colorGen == 8){
targetColor = Color.pink;
}
else if (colorGen == 9){
targetColor = Color.white;
}
repaint();
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
thread = new Thread (this);
thread.start();
}
}
The levels. This is the design and creation of the levels
package SnakeTimer;
import java.util.Vector;
import java.awt.*;
class Level1 {// X level
Vector<Point> wall = new Vector<Point> (5,10);
Vector<Rectangle> wallRect = new Vector<Rectangle> (5,10);
public Level1(){
// diagonally right - down
wall.add (new Point (20, 20));
wall.add (new Point (120, 120));
wall.add (new Point (220, 220));
wall.add (new Point (320, 320));
wall.add (new Point (420, 420));
//diagonally right - up
wall.add (new Point (20, 420));
wall.add (new Point (120, 320));
wall.add (new Point (320, 120));
wall.add (new Point (420, 20));
//rectangles for the points
wallRect.add (new Rectangle (20, 20, 20, 20));
wallRect.add (new Rectangle (120, 120, 20, 20));
wallRect.add (new Rectangle (220, 220, 20, 20));
wallRect.add (new Rectangle (320, 320, 20, 20));
wallRect.add (new Rectangle (420, 420, 20, 20));
wallRect.add (new Rectangle (20, 420, 20, 20));
wallRect.add (new Rectangle (120, 320, 20, 20));
wallRect.add (new Rectangle (320, 120, 20, 20));
wallRect.add (new Rectangle (420, 20, 20, 20));
}
};
class Level2 {// + level
Vector<Point> wall = new Vector<Point> (5,10);
Vector<Rectangle> wallRect = new Vector<Rectangle> (5,10);
public Level2(){
wall.add (new Point (240, 20));
wall.add (new Point (240, 260));
wall.add (new Point (0, 230));
wall.add (new Point (270, 230));
wallRect.add (new Rectangle (240, 20, 10, 180));
wallRect.add (new Rectangle (240, 260, 10, 220));
wallRect.add (new Rectangle (0, 230, 220, 10));
wallRect.add (new Rectangle (270, 230, 230, 10));
}
};
class Level3 { // double T or I level
Vector<Point> wall = new Vector<Point> (5,10);
Vector<Rectangle> wallRect = new Vector<Rectangle> (5,10);
public Level3 (){
wall.add (new Point (20,20)); // top bar
wall.add (new Point(240,20)); // top shaft
wall.add (new Point (240,240));// bottom shaft
wall.add (new Point (20,430));// bottom bar
wallRect.add (new Rectangle (20,20,450,20)); // top bar
wallRect.add (new Rectangle (240,20,20,180));// top shaft for T
wallRect.add (new Rectangle (240,240,20,210)); // bottom shaft for T
wallRect.add (new Rectangle (20,430,450,20)); // bottom bar
}
};
class Level4 { // Pillars
Vector<Point> wall = new Vector<Point> (5,10);
Vector<Rectangle> wallRect = new Vector<Rectangle> (5,10);
public Level4(){
wall.add (new Point (20,20));
wall.add (new Point (60,20));
wall.add (new Point (100,20));
wall.add (new Point (140,20));
wall.add (new Point (180,20));
wall.add (new Point (220,20));
wall.add (new Point (220,240));
wall.add (new Point (260,20));
wall.add (new Point (260,240));
wall.add (new Point (300,20));
wall.add (new Point (340,20));
wall.add (new Point (380,20));
wall.add (new Point (420,20));
wall.add (new Point (460,20));
wallRect.add (new Rectangle (20,20,20,430));
wallRect.add (new Rectangle (60,20,20,430));
wallRect.add (new Rectangle (100,20,20,430));
wallRect.add (new Rectangle (140,20,20,430));
wallRect.add (new Rectangle (180,20,20,430));
wallRect.add (new Rectangle (220,20,20,180));
wallRect.add (new Rectangle (220,240,20,210));
wallRect.add (new Rectangle (260,20,20,180));
wallRect.add (new Rectangle (260,240,20,210));
wallRect.add (new Rectangle (300,20,20,430));
wallRect.add (new Rectangle (340,20,20,430));
wallRect.add (new Rectangle (380,20,20,430));
wallRect.add (new Rectangle (420,20,20,430));
wallRect.add (new Rectangle (460,20,20,430));
}
};
class Level5 { // U and N
Vector<Point> wall = new Vector<Point> (5,10);
Vector<Rectangle> wallRect = new Vector<Rectangle> (5,10);
Level5 () {
// U
wall.add(new Point (20,20)); // |
wall.add(new Point (20,430));// _
wall.add(new Point (450,20)); // |
// N
wall.add(new Point (60,20));// |
wall.add(new Point (80,20));// top of n
wall.add(new Point (410,20));//|
// U
wall.add(new Point (100,60));
wall.add(new Point (100,390));
wall.add(new Point (370,60));
wallRect.add (new Rectangle (20,20,20,430));
wallRect.add (new Rectangle (20,430,450,20));
wallRect.add (new Rectangle (450,20,20,430));
wallRect.add (new Rectangle (60,20,20,390));
wallRect.add (new Rectangle (80,20,350,20));
wallRect.add (new Rectangle (410,20,20,390));
wallRect.add (new Rectangle (100,60,20,330));
wallRect.add (new Rectangle (100,390,290,20));
wallRect.add (new Rectangle (370,60,20,330));
}
};
class Level6 {
Vector<Point> wall = new Vector<Point> (5,10);
Vector<Rectangle> wallRect = new Vector<Rectangle> (5,10);
Level6 (){
wall.add (new Point (170,240));
wallRect.add(new Rectangle (190,240,160,80));
}
}
Notes
-I have not implemented the high scores. I am having trouble using the High score class, and I have not yet figured out how to use Java with JDBC and MySQL to make an online high score database.
-If you wish to add in a new level then rename level 6 (the campaign completed level), and then put it at the end. you will need to modify the paintComponent to make sure it prints correctly. You will also need to modify the collision detection area to make sure that the correct collision detection is on.
Then you will need to make a new level and then add your blocks (wall is for the position, while wallRect is for the collision detection). You will also need to copy the else if for another level in the collision detection and then change the value of the class. You must also create a new variable for the class (I have done this at the top of the SnakeG file). If you are having any trouble with this just ask and I can clarify.
Lastly I have fixed the glitch with the HighScores message appearing more then once. You can either compile the code given, or you can download it here: [ Register or Signin to view external links. ]
You are viewing our Forum Archives. To view or take place in current topics click here.