Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 2 of 2 FirstFirst 12
Results 26 to 36 of 36

Thread: Java SnakeGame

  1. #26
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Java SnakeGame

    Are those two files: a small, complete program that compiles, executes and shows the problem?

    What is supposed to happen when the code is executed?
    I get some green squares in the upper left and some red squares that jump around.
    If you don't understand my answer, don't ignore it, ask a question.

  2. #27
    Junior Member
    Join Date
    Apr 2014
    Posts
    18
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Java SnakeGame

    It's suposed to be a snake game. I said at first that the snake (green squares) does not move, and apples (red circles) are spawned everywhere. Do you realy not know what a snake game is? The green squares move and get 1 apple at a time, then they grow in lenght.

  3. #28
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Java SnakeGame

    The code needs lots of debugging so you can see what it is doing when it executes. Try adding println() statements to the different methods to see where the code is executing or not executing.

    Also you need to remove ALL the ONE TIME code from the paint() method. It should go in the class's constructor. With Swing classes, you should override paintComponent(), not paint().
    If you don't understand my answer, don't ignore it, ask a question.

  4. #29
    Junior Member
    Join Date
    Apr 2014
    Posts
    18
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Java SnakeGame

    Done, apple spawn only once. Checked every method with println, they work. No erors. Still the snake does not move when i press keys, i'm pretty sure it has something to do with the KeyListener, but i dont know what.

    This is the new code:Game.txt

  5. #30
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Java SnakeGame

    Please post the code on the forum, not as an attachment.

    Still the snake does not move when i press keys
    Is the key listener method being called? Did the println() you put in that method print anything?

    Copy the full text of the print outs and paste it here that shows how the code is executing.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #31
    Junior Member
    Join Date
    Apr 2014
    Posts
    18
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Java SnakeGame

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.image.BufferedImage;
    import java.util.LinkedList;
    import java.util.Random;
     
    import javax.swing.JFrame;
    import javax.swing.JPanel;
     
     
     
    public class Game extends JPanel implements Runnable{
     
    	private static final long serialVersionUID = 1L;
    	private final int BOX_HEIGHT = 15;
    	private final int BOX_WIDTH = 15;
    	private final int GRID_WIDTH = 25;
    	private final int GRID_HEIGHT = 25;
     
    	private Key key;
    	private boolean right = false, left = false, up = false, down = false;
     
    	private LinkedList<Point> snake;
    	private Point fruit;
     
    	private Thread runThread;
    	private Graphics globalGraphics;
    	private int score = 0;
     
    	public static void main(String[] args) {
    		JFrame frame = new JFrame("Snake");
    		Game game = new Game();
    		frame.add(game);
    		frame.setSize(406, 430);
    		frame.setVisible(true);
    		frame.setResizable(false);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		game.run();
    	}
     
    	public void paintComponent(Graphics g)
    	{	if (runThread == null)
    			{	this.setPreferredSize(new Dimension(406, 430));
    				globalGraphics = g.create();
    				key = new Key();
    				addKeyListener(key);
    				runThread = new Thread(this);
    				runThread.start();
    			}
    		draw(globalGraphics);
    	}
     
    	public void GenerateDefaultSnake()
    	{	score = 0;
    		snake.clear();
     
    		snake.add(new Point(5,4));
    		snake.add(new Point(5,3));
    		snake.add(new Point(5,2));
     
    	}
     
    	public void draw(Graphics g)
    	{
    		g.clearRect(0, 0, BOX_WIDTH * GRID_WIDTH + 10, BOX_HEIGHT * GRID_HEIGHT + 20);
     
    		BufferedImage buffer = new BufferedImage(BOX_WIDTH * GRID_WIDTH + 10, BOX_HEIGHT * GRID_HEIGHT + 20, BufferedImage.TYPE_INT_ARGB);
    		Graphics bufferGraphics = buffer.getGraphics();
     
    		drawFruit(bufferGraphics);
    		drawGrid(bufferGraphics);
    		drawSnake(bufferGraphics);
    		drawScore(bufferGraphics);
     
     
    		g.drawImage(buffer, 0, 0, BOX_WIDTH * GRID_WIDTH + 10,  BOX_HEIGHT * GRID_HEIGHT + 20, this);
    	}
     
    public void move()
    	{
    		Point head = snake.peekFirst();
    		Point newPoint = head;
     
    		if(up == true){
    			newPoint = new Point(head.x, head.y - 1);
    		}
    		if(down == true){
    			newPoint = new Point(head.x, head.y + 1);
    		}
    		if(left == true){
    			newPoint = new Point(head.x - 1, head.y);
    		}
    		if(right == true){
    			newPoint = new Point(head.x + 1, head.y);
    		}
     
    		snake.remove(snake.peekLast());
     
    		if (newPoint.equals(fruit))
    		{
     
    			score+=10;
     
    			Point addPoint = (Point) newPoint.clone();
     
    			if(up == true){
    				newPoint = new Point(head.x, head.y - 1);
    			}
    			if(down == true){
    				newPoint = new Point(head.x, head.y + 1);
    			}
    			if(left == true){
    				newPoint = new Point(head.x - 1, head.y);
    			}
    			if(right == true){
    				newPoint = new Point(head.x + 1, head.y);
    			}
     
    			snake.push(addPoint);
    			placeFruit();
     
    		}
    		else if (newPoint.x < 0 || newPoint.x > (GRID_WIDTH - 1))
    		{			
    			return;
    		}
    		else if (newPoint.y < 0 || newPoint.y > (GRID_HEIGHT - 1))
    		{		
    			return;
    		}
    		else if (snake.contains(newPoint))
    		{		
    			return;
    		}		
    		snake.push(newPoint);
    	}
     
    	public void drawScore(Graphics g)
    	{
    		g.drawString("Score: " + score, 0, BOX_HEIGHT * GRID_HEIGHT + 10);
    	}
     
    	public void drawGrid(Graphics g)
    	{
     
    		g.drawRect(0, 0, GRID_WIDTH * BOX_WIDTH, GRID_HEIGHT * BOX_HEIGHT);
     
    		for (int x = BOX_WIDTH; x < GRID_WIDTH * BOX_WIDTH; x+=BOX_WIDTH)
    		{
    			g.drawLine(x, 0, x, BOX_HEIGHT * GRID_HEIGHT);
    		}
     
    		for (int y = BOX_HEIGHT; y < GRID_HEIGHT * BOX_HEIGHT; y+=BOX_HEIGHT)
    		{
    			g.drawLine(0, y, GRID_WIDTH * BOX_WIDTH, y);
    		}
    	}
     
    	public void drawSnake(Graphics g)
    	{
    		g.setColor(Color.GREEN);
    		for (Point p : snake)
    		{
    			g.fillRect(p.x * BOX_WIDTH, p.y * BOX_HEIGHT, BOX_WIDTH, BOX_HEIGHT);
    		}
    		g.setColor(Color.BLACK);
    	}
     
    	public void drawFruit(Graphics g)
    	{
    		g.setColor(Color.RED);
    		g.fillOval(fruit.x * BOX_WIDTH, fruit.y * BOX_HEIGHT, BOX_WIDTH, BOX_HEIGHT);
    		g.setColor(Color.BLACK);
    	}
     
    	public void placeFruit()
    	{
    		Random rand = new Random();
    		int randomX = rand.nextInt(GRID_WIDTH);
    		int randomY = rand.nextInt(GRID_HEIGHT);
    		Point randomPoint = new Point(randomX, randomY);
    		while (snake.contains(randomPoint))
    		{
    			randomX = rand.nextInt(GRID_WIDTH);
    			randomY = rand.nextInt(GRID_HEIGHT);
    			randomPoint = new Point(randomX, randomY);
    		}
    		fruit = randomPoint;
    	}
     
    	public class Key implements KeyListener{
     
    	@Override
    	public void keyPressed(KeyEvent e) {
    		int key = e.getKeyCode();
     
    			if(key == KeyEvent.VK_UP && !down)
    			{
    				up = true;
    				left = false;	
    				right = false;
    			}
     
    			if(key == KeyEvent.VK_DOWN && !up)
    			{
    				down = true;
    				left = false;	
    				right = false;
    			}
     
    			if(key == KeyEvent.VK_LEFT && !right)
    			{
    				up = false;
    				down = false;	
    				left = true;
    			}
     
    			if(key == KeyEvent.VK_RIGHT && !left)
    			{
    				up = false;
    				down = false;	
    				right = true;
    			}
     
    		}
     
    	@Override
    	public void keyReleased(KeyEvent e) {
    		// TODO Auto-generated method stub
     
    	}	
     
    	@Override
    	public void keyTyped(KeyEvent e) {
    		// TODO Auto-generated method stub
     
    	}
    	}
     
     
     
    	@Override
    	public void run() {
    		while (true) {
    			if (snake == null)
    			{		snake = new LinkedList<Point>();	
    					GenerateDefaultSnake();
    					placeFruit();					
    			}
    			setPreferredSize(new Dimension(406, 430));			
    			repaint();
    			move();		
    			try
    			{
    				Thread.currentThread();
    				Thread.sleep(100);				
    			}
    			catch(Exception e)
    			{
    				e.printStackTrace();
    			}	
    		}
     
    	}
     
    }

    Yeah, sorry, but when i tried at first to put all the code on forum, it did not work.

    GenerateDefaultSnake
    placeFruit
    run
    move
    draw
    run
    move
    drawFruit
    drawGrid
    drawSnake
    drawScore
    run
    move
    paintComponent
    draw
    drawFruit
    drawGrid
    drawSnake
    drawScore
    paintComponent
    Last edited by RigaCrypto; April 24th, 2014 at 12:54 PM.

  7. #32
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Java SnakeGame

    Where are the println() statements? You need to leave them in to show me how you were using them for debugging.

    There still is code in the paintComponent() method that should NOT be there. Move the one time initialization code to the class's constructor. The same with code in the run() method. It should be in the constructor , not inside a loop in run().

    Where is the full text of the print outs and paste it here that shows how the code is executing that I requested?
    If you don't understand my answer, don't ignore it, ask a question.

  8. The Following User Says Thank You to Norm For This Useful Post:

    RigaCrypto (April 24th, 2014)

  9. #33
    Junior Member
    Join Date
    Apr 2014
    Posts
    18
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Java SnakeGame

    Yeah, i dont know man, you are of no help to me. Im new to this, like watching tutorials on youtube new, and i try to do what you tell me, but then i get more erors. It seams to me that you dont try to understand the code and you only give me general advice. Don't get me wrong i appreciate your help, but is frustrating when i try to do what you ask and i get more and more erors.

    So let's leave it to that.

  10. #34
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Java SnakeGame

    i get more and more erors.
    If you want help with error messages, you should copy the full text and paste it here.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #35
    Junior Member
    Join Date
    Apr 2014
    Posts
    18
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Java SnakeGame

    Ok, so the problem is, like i said, the KeyListener. I did some research and seams like KeyListener dose not work on JFrame, its something about the components and foucs(only the component with the focus will send the keyevents, or something like that). Now, i found some fixes but i dont know how to insert them in the code. If someone can make the adjustments needed to make the KeyListener work, i will be most grateful.

  12. #36
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Java SnakeGame

    You need to set the component that has the listeners so that it can get the focus. The setFocusable method will do that.
    If you don't understand my answer, don't ignore it, ask a question.

Page 2 of 2 FirstFirst 12