10 Replies - 53613 Views - Last Post: 21 June 2015 - 03:49 PM Rate Topic: -----

#1 sly  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 134
  • Joined: 05-December 08

Java Snake Game

Posted 31 January 2010 - 03:39 PM

Hi im making a snake game in java, and I have a question about graphics for the snake and the mice. Should I use JLabels for making the snake and mice? would that work? Because there needs to be a way for the snake to increase in size so would JLabels be capable of doing so? Or is it possible to use graphics for instance the snake could be a line that eats a bunch of circles (mice). Movement would be necessary though the keys which i have already implemented.

Please would someone point me in the right direction?

thanks!

Here is my code:


GameFrame.java

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.border.*;
import javax.swing.*;



	public class GameFrame extends JFrame {
	
	   private Movement movement1 = new Movement();
	   private Mouse mousemovement1 = new Mouse();
	
	public GameFrame() {
		
	super("Snake Game"); //Name of the JFrame

	
	
   //adding the key listener
	 this.addKeyListener(movement1);

			Image img = Toolkit.getDefaultToolkit().getImage("C:/Documents and Settings/Administrator/My Documents/My Pictures/snakelogo.GIF");
			  setIconImage(img);   //Image on top left corner
			  
	  
			  
			  
			  Dimension screenSize =			//Location of Frame on the Screen												
				  Toolkit.getDefaultToolkit().getScreenSize();
			   Dimension frameSize = getSize();
			   int x = (screenSize.width - frameSize.width) / 4;	
			   int y = (screenSize.height - frameSize.height) / 5;
			   setLocation(x, y);

			   JPanel jpanel_0 = new JPanel();
			   jpanel_0.setBackground(Color.cyan);
			   jpanel_0.add(new JLabel("Snake Game"));

			  
			   Container cp = getContentPane();
			   cp.add(jpanel_0,BorderLayout.CENTER);
			 

			   setSize(600, 450);
			   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			 
			   
			   
			 setVisible(true); //visibility of JFrame
			  
	}
	
			  public static void main(String[] args) {
				  new GameFrame();
				  
				  
				
				  Snake snake1 = new Snake();
				  
				  
				  
				  
				  
		 
		   }
			  
		}


Mouse.java
public class Mouse {

	
	
}




Movement.java

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;


public class Movement implements KeyListener{

	@Override
	 public void keyPressed(KeyEvent e) 
	{
	  
		if(e.getKeyChar() == 'a')
		{
	   
			System.out.println("you pressed a");
		
		}
		if(e.getKeyChar() == 's')
		{
	   
			System.out.println("you pressed s");
		   
		}
		if(e.getKeyChar() == 'w')
		{
		  
			System.out.println("you pressed w");
		 
		}
		if(e.getKeyChar() == 'd')
		{
		 
			System.out.println("you pressed d");
		
		}
	}

	@Override
	public void keyReleased(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyTyped(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}

}



Snake.java

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.border.*;


public class Snake {

}



Is This A Good Question/Topic? 0
  • +

Replies To: Java Snake Game

#2 Sloth  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 9
  • Joined: 31-January 10

Re: Java Snake Game

Posted 31 January 2010 - 05:16 PM

There are a few ways to do this. By convention, a snake is made up of many segments. For each movement, each segment takes the place of the segment in front of it. When it grows, a segment is added to the end. Create something to be segments, such as polygons, points, or a custom object. keep track of these by storing them in an array or list. Some ways are easier than others, or try a few others if you have trouble.

I would have a single variable that keeps track of the snake's direction.(From your code, it seems he'll be constantly moving, as he should). When one of the four keys is pressed, change the variable. Seperately, whenever the snake should move, update the head's position according to the variable. Remember, you'll also need to move each part to the previous one's old position. (part1 takes the head's old spot, part2 takes part1's old spot, etc).

Use some sort of check after each move to see if the snake's head caught a rat. If it did, add a part to it.

Hope this info was helpful. They're just suggestions, so code it whichever way you feel works best.
Was This Post Helpful? 0
  • +
  • -

#3 sly  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 134
  • Joined: 05-December 08

Re: Java Snake Game

Posted 31 January 2010 - 07:23 PM

Im having trouble currently adding graphics to my JPanel, I have created a new class called Snake to display the snake and that is were all of the graphics information on the snake is held....

I reconnect the Snake Class to the class with the main method so that it would show the graphics, but for some reason it doesn't...

I hope you can help!!! thanks!!!


GameFrame.java
import java.awt.*;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.border.*;
import javax.swing.*;



	public class GameFrame extends JFrame {
	
	   private Movement movement1 = new Movement();
	   private Snake snake1 =  new Snake();
	   private Mouse mousemovement1 = new Mouse();
	
	public GameFrame() {
		
	super("Snake Game"); //Name of the JFrame
	
	
	 this.addKeyListener(movement1);	//adding the key listener

			Image img = Toolkit.getDefaultToolkit().getImage("C:/Documents and Settings/Administrator/My Documents/My Pictures/snakelogo.GIF");
			  setIconImage(img);   //Image on top left corner
			  
	  
			  
			  
			  Dimension screenSize =			//Location of Frame on the Screen												
				  Toolkit.getDefaultToolkit().getScreenSize();
			   Dimension frameSize = getSize();
			   int x = (screenSize.width - frameSize.width) / 4;	
			   int y = (screenSize.height - frameSize.height) / 5;
			   setLocation(x, y);

			   
			   Container cp = getContentPane();			//Background color of the Frame
			   cp.setLayout(new FlowLayout());
			   cp.setBackground(Color.yellow);
			   
			   JPanel jpanel_0 = new JPanel();	  //Text on top of screen "Snake Game V.01" highlighted.
			   jpanel_0.add(new JLabel("Snake Game V.01"));		 
			   jpanel_0.setOpaque(true);
			   jpanel_0.setBackground(Color.green);
			   
			   Container cp1 = getContentPane();	//Centers the title "Snake Game V.01"
			   cp1.add(jpanel_0,BorderLayout.CENTER);
   
   
			   
			   setSize(600, 450); // Size of JFrame
			   
			   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);	 //Shuts down program once JFrame is closed   
			   
			   
			 setVisible(true); //visibility of JFrame
			 
			 
			  
	}
	
	
			  public static void main(String[] args) {
				  new GameFrame();
				  
				
			 
		 
		   }
			  
		}



Mouse.java
public class Mouse {

	
	
	
}





Movement.java
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;


public class Movement implements KeyListener{

	@Override
	 public void keyPressed(KeyEvent e) 
	{
	  
		if(e.getKeyChar() == 'a')
		{
	   
			System.out.println("you pressed a");
		
		}
		if(e.getKeyChar() == 's')
		{
	   
			System.out.println("you pressed s");
		   
		}
		if(e.getKeyChar() == 'w')
		{
		  
			System.out.println("you pressed w");
		 
		}
		if(e.getKeyChar() == 'd')
		{
		 
			System.out.println("you pressed d");
		
		}
	}

	@Override
	public void keyReleased(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyTyped(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}

}



Snake.java
import java.awt.*;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;
import javax.swing.*;
import javax.swing.JPanel;
import javax.swing.border.*;


public class Snake extends JPanel{

	
	  public void paintComponent(Graphics g) {
		  super.paintComponent(g); 

		  Graphics2D g2d = (Graphics2D) g;

		  g2d.setColor(Color.blue);

		  for (int i=0; i<=1000; i++) {
			  Dimension size = getSize();
			  Insets insets = getInsets();

			  int w =  size.width - insets.left - insets.right;
			  int h =  size.height - insets.top - insets.bottom;

			  Random r = new Random();
			  int x = Math.abs(r.nextInt()) % w;
			  int y = Math.abs(r.nextInt()) % h;
			  g2d.drawLine(x, y, x, y);
		  }
  }
}



Was This Post Helpful? 0
  • +
  • -

#4 ts230  Icon User is offline

  • D.I.C Head

Reputation: 11
  • View blog
  • Posts: 225
  • Joined: 11-July 09

Re: Java Snake Game

Posted 31 January 2010 - 07:27 PM

Try putting the painting code in the paint() method, e.g. just get rid of the Component part.
Was This Post Helpful? 0
  • +
  • -

#5 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon

Reputation: 2930
  • View blog
  • Posts: 11,201
  • Joined: 15-July 08

Re: Java Snake Game

Posted 31 January 2010 - 07:34 PM

You are only adding 1 JPanel to the main JFrame. Though you instantiate Snake, which is a subclass of JPanel, you cannot see it or interact with it until you add it to the JFrame, which you never do. You only add the cp1.add(jpanel_0,BorderLayout.CENTER); line but never do anything with snake1. If you ever need to have more than one different JPanels for 1 JFrame (as you seem to), I would look into State Machines. They allow for multiple states to run on the same JPanel.

Each state controls its own events, drawings, and updating. If this sounds interesting, stay tuned for one of my future blog entries: State Machines (actually, I'm working on the code for it now). But for now, make sure you do something with the snake1 JPanel.
Was This Post Helpful? 0
  • +
  • -

#6 sly  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 134
  • Joined: 05-December 08

Re: Java Snake Game

Posted 31 January 2010 - 08:04 PM

Is there a way to do this without using statemachines?

This post has been edited by sly: 31 January 2010 - 08:04 PM

Was This Post Helpful? 0
  • +
  • -

#7 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon

Reputation: 2930
  • View blog
  • Posts: 11,201
  • Joined: 15-July 08

Re: Java Snake Game

Posted 31 January 2010 - 08:28 PM

You could add it to the JFrame after the constructor, however adding and removing components from a JFrame outside of the constructor and constructor-help methods is NOT recommended as it causes many unknown effects
Was This Post Helpful? 0
  • +
  • -

#8 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon

Reputation: 2930
  • View blog
  • Posts: 11,201
  • Joined: 15-July 08

Re: Java Snake Game

Posted 31 January 2010 - 09:10 PM

Hey sly, I remeber seeing something almost exactly like this in the Java forum. Could you please pick one and not double post? It's confusing to see them both. Could a Mod or Admin merge these please?
Was This Post Helpful? 0
  • +
  • -

#9 NeoTifa  Icon User is offline

  • Whorediot
  • member icon





Reputation: 2998
  • View blog
  • Posts: 16,360
  • Joined: 24-September 08

Re: Java Snake Game

Posted 01 February 2010 - 09:57 AM

HOLY CRAP THAT DOT WAS SUPPOSED TO BE A MOUSE?!?!?! It's all so clear now! </life altering realization> I never really thought about it before; I just assumed he has a weird dot craving.... XD
Was This Post Helpful? 0
  • +
  • -

#10 SixOfEleven  Icon User is offline

  • using Caffeine;
  • member icon

Reputation: 947
  • View blog
  • Posts: 6,342
  • Joined: 18-October 08

Re: Java Snake Game

Posted 01 February 2010 - 03:44 PM

View PostDogstopper, on 31 Jan, 2010 - 11:10 PM, said:

Hey sly, I remeber seeing something almost exactly like this in the Java forum. Could you please pick one and not double post? It's confusing to see them both. Could a Mod or Admin merge these please?


Done. Thanks for catching this.

@OP:
Yes, please keep from posting multiple topics.
Was This Post Helpful? 0
  • +
  • -

#11 robinmau  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 21-June 15

Re: Java Snake Game

Posted 21 June 2015 - 03:49 PM

Here is my snake game which completely works. You can use some parts of the code (dont use all -.-/>) and the comments are there to guide you. Cheers!

Snake Summative Code
Game (Main)
package snake;

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JOptionPane;
import javax.swing.UIManager;

public class Game extends Core implements KeyListener {
	private static int difficulty = 0;


	// main method
	public static void main(String[] args) {

		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception alternate){
			
		}
		
		Object[] opts = { "Easy", "Normal", "Hard", "Insane", "Exit" };		//message box will ask for for the user to select difficulty
		 difficulty = JOptionPane.showOptionDialog(null, "Welcome to the Snake Game! \n you Can select a difficulty below \n (Level details)  \n Level easy and medium will have a grid and touching the walls won't kill you \n Levels hard and extreme won't have a grid and touching the walls will kill you \n each level higher gets faster and faster \n Remember to have fun! \n (Press exit to close the game)", //this will be displayed in the box
				"Snake", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,		//title of the message box
				null, opts, opts);

		if (difficulty == 0) {		//if difficulty easy is selected then
			sleep = 139;			//length of break until loop restarts (in milliseconds)
			grid = true;			//the grid will be visible to guide the user's movements
			new Game().run();		//starts game initiation
			
		} else if (difficulty == 1) {		//if difficulty medium is selected then
			sleep = 99;			//length of break until loop restarts (in milliseconds)
			grid = true;			//the grid will be visible to guide the user's movements
			new Game().run();		//starts game initiation
			
		} else if (difficulty == 2) {		//if difficulty hard is selected then
			sleep = 69;			//length of break until loop restarts (in milliseconds)
			grid = false;			//the grid will be absent to increase difficulty
			new Game().run();		//starts game initiation
			
		} else if (difficulty == 3) {		//if difficulty extreme is selected then
			sleep = 29;			//length of break until loop restarts (in milliseconds)
			grid = false;			//the grid will be absent to increase difficulty
			new Game().run();		//starts game initiation
			
		} else {
			System.exit(0);		//exit game
		}
		
		if(replay){
			main(null);
		}
	}

	ArrayList<Rectangle> snake;
	Rectangle food;		//declaring the food an area in coordinate space
	boolean up, down, left, right, eaten, dirChanged;		//Declaring booleans variables
	static boolean grid;		//Declaring grid variable
	int score;		//declaring score variable

	
	public void initializer() {		// initializer method
		super.initializer();
		gameFrame.addKeyListener(this);
		removeCursor();

		snake = new ArrayList<Rectangle>();		//snake's Initial shape size
		snake.add(new Rectangle(280, 240, 20, 20));
		snake.add(new Rectangle(281, 240, 20, 20));
		snake.add(new Rectangle(-20, -20, 20, 20));

		eaten = true;
		score = 0;
	}

	public void update() {		// updates the game
		food();
		
		dirChanged = false;

		// Collision between snake and itself
		for (int i = 0; i < snake.size(); i++) {
			for (int j = i + 1; j < snake.size(); j++) {
				if (snake.get(i).getLocation().x == snake.get(j).getLocation().x
						&& snake.get(i).getLocation().y == snake.get(j)
				.getLocation().y) {
					stop();		//exits out of the loop if the snake ate itself
					gameFrame.setVisible(false);
					JOptionPane.showMessageDialog(null, "You scored " + score,		//displays how much the user scored is a message box
							"Snake", JOptionPane.PLAIN_MESSAGE);
					replay = true;		//replays the game
				}
			}
		}

		// movement for snake
		for (int i = snake.size() - 1; i >= 0; i--) {
			
			if (up) {		//if up arrow was clicked
				try {		//checks if the snake is not already moving in the upwards direction
					snake.get(i).setLocation(snake.get(i - 1).x,
							snake.get(i - 1).y);
				} catch (Exception alternate ) {		//if not, then it will change the direction of the snake to move upwards
					if (snake.get(i).getLocation().y > 0) {
						snake.get(i).setLocation(snake.get(i).x,
								snake.get(i).y - 20);
					} else if ( (difficulty == 0) || (difficulty == 1)) {		// if difficulty is set to easy or medium then	
						snake.get(i).setLocation(snake.get(i).x,
								gameFrame.getHeight() - 20);		// snake will pop up in the other side of the frame, if hard or extreme, then you die
					}
				}
				
			} else if (down) {		//if down arrow was clicked
				try {			//checks if the snake is not already moving in the downwards direction
					snake.get(i).setLocation(snake.get(i - 1).x,
							snake.get(i - 1).y);
				} catch (Exception alternate) {		//if not, then it will change the direction of the snake to move downwards
					if (snake.get(i).getLocation().y < gameFrame.getHeight() - 20) {
						snake.get(i).setLocation(snake.get(i).x,	
								snake.get(i).y + 20);
					} else if ( (difficulty == 0) || (difficulty == 1)) {		// if difficulty is set to easy or medium then		
						snake.get(i).setLocation(snake.get(i).x, 0);		// snake will pop up in the other side of the frame, if hard or extreme, then you die
					}
				}
				
			} else if (left) {		//if left arrow was clicked
				try {			//checks if the snake is not already moving in the left direction
					snake.get(i).setLocation(snake.get(i - 1).x,
							snake.get(i - 1).y);
				} catch (Exception alternate) {		//if not, then it will change the direction of the snake to move left
					if (snake.get(i).getLocation().x > 0) {
						snake.get(i).setLocation(snake.get(i).x - 20,
								snake.get(i).y);
					} else if ( (difficulty == 0) || (difficulty == 1)) {	// if difficulty is set to easy or medium then			
						snake.get(i).setLocation(gameFrame.getWidth() - 20,
								snake.get(i).y);		// snake will pop up in the other side of the frame, if hard or extreme, then you die
					}
				}
				
			} else if (right) {		//if right arrow was clicked
				try {			//checks if the snake is not already moving in the right direction
					snake.get(i).setLocation(snake.get(i - 1).x,
							snake.get(i - 1).y);
				} catch (Exception alternate) {		//if not, then it will change the direction of the snake to move right
					if (snake.get(i).getLocation().x < gameFrame.getWidth() - 20) {
						snake.get(i).setLocation(snake.get(i).x + 20,
								snake.get(i).y);
					} else if ( (difficulty == 0) || (difficulty == 1)) {	// if difficulty is set to easy or medium then	
						snake.get(i).setLocation(0, snake.get(i).y);		// snake will pop up in the other side of the frame, if hard or extreme, then you die
					}
				}
			}
		}
	}

	// food method
	public void food() {
		if (eaten && up || eaten && down || eaten && left || eaten && right) {		//checks if food has been "eaten" by the four directions
			int x = new Random().nextInt(30) * 20;		//random x coordinate
			int y = new Random().nextInt(25) * 20;		//random y coordinate
			boolean spawn = true;		//spawns the food

			for (int i = 0; i < snake.size(); i++) {
				if (snake.get(i).x == x && snake.get(i).y == y) {
					spawn = false;		//doesn't spawn the food 
				}
			}

			if (spawn) {		//spawn point is not changed
				food = new Rectangle(x, y, 20, 20);		//location and size remain the same
				eaten = false;		//set as false to show that the food hasen't been eaten yet
			}
			
		} else if (food != null && !eaten) {	//if food is eaten then
			if (snake.get(0).x == food.x && snake.get(0).y == food.y) {		//food is set to a new location
				snake.add(new Rectangle(-20, -20, 20, 20));
				score++;		// adds one more point to the score
				eaten = true;		//remains true to show that the food has been eaten
			}
		}
	}

	// draw method
	public void draw(Graphics2D graphics) {	//setting up the graphics for the game
		
		graphics.setColor(Color.BLACK);		//the background color of the frame
		graphics.fillRect(0, 0, gameFrame.getWidth(), gameFrame.getHeight());		//so the color fills the entire background of the frame

		graphics.setColor(Color.GRAY);		//color of the grid
		if(grid){		//uses loops to draw the lines of the grid
			for (int x = 0; x < gameFrame.getWidth() / 20; x++) {
				for (int y = 0; y < gameFrame.getHeight() / 20; y++) {
					graphics.drawRect(x * 20, y * 20, 20, 20);
				}
			}
		}
		
		if (!eaten) {
			graphics.fill(food);		//jumps to the food method
		}
		
		graphics.setColor(Color.WHITE);		//color of words and snake
		for (int i = snake.size() - 1; i >= 0; i--) {
			graphics.fill(snake.get(i));		//white color is filled into the snake pieces
		}

		graphics.setFont(new Font("Dialog", Font.PLAIN, 16));
		graphics.drawString("Score: " + score, 2, 17);		//sets the location and displays the score on the frame
		graphics.drawString("Press Escape to quit", 450, 17);		//sets the location and displays the keys to exit the game
		if(!up && !down && !left && !right){	//checks as long as any directional keys aren't pressed
			graphics.drawString("Press Up, down, left or right to start game", 130, 17);	//sets the location and displays the directions of the game
		}
	}


	public void keyPressed(KeyEvent alternate) {	// Key listeners
		
		if (alternate.getKeyCode() == KeyEvent.VK_ESCAPE) {		//if escape on the keyboard is pressed then
			stop();		//quite the game
			
		} else if (alternate.getKeyCode() == KeyEvent.VK_UP && !down && !dirChanged) {	//if up key is pressed then
			dirChanged = true;		//the direction is to be changed
			up = true;			//all directions are false except up
			down = false;
			left = false;
			right = false;
			
		} else if (alternate.getKeyCode() == KeyEvent.VK_DOWN && !up && !dirChanged) {	//if down key is pressed then
			dirChanged = true;		//the direction is to be changed
			up = false;			//all directions are false except down
			down = true;
			left = false;
			right = false;
			
		} else if (alternate.getKeyCode() == KeyEvent.VK_LEFT && !right && !dirChanged) {	//if left key is pressed then
			dirChanged = true;		//the direction is to be changed
			up = false;			//all directions are false except left
			down = false;
			left = true;
			right = false;
			
		} else if (alternate.getKeyCode() == KeyEvent.VK_RIGHT && !left && !dirChanged) {	//if right key is pressed then
			dirChanged = true;		//the direction is to be changed
			up = false;			//all directions are false except right
			down = false;
			left = false;
			right = true;
		}
	}

	public void keyReleased(KeyEvent alternate) {
	}

	public void keyTyped(KeyEvent alternate) {
	}
}

Core 
package snake;

import java.awt.*;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import javax.swing.*;

public abstract class Core {
	
	boolean running;		//declaring variables
	static boolean replay;
	JFrame gameFrame;
	

	public void stop(){		//stop method
		running = false;	// games stop running
	}
	

	public void run(){		//call initializer and gameloop
		
		try{
			initializer();	//jumps to public void initializer to setup the JFrame
			gameLoop();		//jumps to public void gameLoop to start the game
		}finally{
			if(!replay){	//if the user doesn't want to replay the program then
				System.exit(0);		//it exits the program
			}
		}
	}
	
	public void initializer(){
		
		gameFrame = new JFrame();	//creates a new JFrame 
		
		gameFrame.setUndecorated(true);		//so we can "decorate" the frame
		gameFrame.setIgnoreRepaint(true);	//repaints set by the windows programs will be ignored
		gameFrame.setResizable(false);	//the user can not resize the frame
		
		gameFrame.setSize(600, 500);		//size of the JFrame
		gameFrame.setLocationRelativeTo(null);	/** search what this does **/
		
		gameFrame.setFont(new Font("Arial", Font.PLAIN, 24));	//sets the font and size of the words that are to be displayed
		gameFrame.setBackground(Color.BLACK);	//Color of the background
		gameFrame.setForeground(Color.WHITE);	
		gameFrame.setVisible(true);		//so we can see the JFrame
		
		gameFrame.createBufferStrategy(2);	//a new strategy for multi-buffering is set on this component
		replay = false;
		running = true;
	}
	
	static long sleep;		//the time break
	
	
	public void gameLoop(){	//main game loop
		
		while(running){		//while the game is still going
			Graphics2D graphics = (Graphics2D) gameFrame.getBufferStrategy().getDrawGraphics();
			draw(graphics);		//to initiate the code to draw the grid
			graphics.dispose();
			this.update();		//restarts the loop of the game, checks if the snake has eaten the food, itself and if any arrow was pressed for movement
			
			if(gameFrame != null){
				BufferStrategy s = gameFrame.getBufferStrategy();
				if(!s.contentsLost()){
					s.show();
				}
			}
			
			try{
				Thread.sleep(sleep);
			}catch(Exception alternate){}
		}
	}
	

	public abstract void update();	//update game
	
	
	public abstract void draw(Graphics2D graphics);	//draws to the screen
	

	public void removeCursor(){		//this method makes the cursor invisible when brought onto the frame of the game
		BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
		Cursor blankCursor = Toolkit.getDefaultToolkit().createCustomCursor(cursorImg, new Point(0, 0), "blank cursor");
		gameFrame.setCursor(blankCursor);
	}
}

This post has been edited by modi123_1: 22 June 2015 - 06:43 AM
Reason for edit:: Please use the 'code' button in the editor to apply code tags for readability.

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1