LinuxQuestions.org
Download your favorite Linux distribution at LQ ISO.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices

Reply
 
Search this Thread
Old 07-19-2010, 10:23 AM   #1
Asido
Member
 
Registered: Jan 2010
Location: Denmark
Distribution: Gentoo, Archlinux, FreeBSD, Slackware
Posts: 84

Rep: Reputation: 24
problem with loading images (Java)


Hello. I am making a simple snake game and have problem when loading the images (apple, snakes head, snakes body). When running this code, I just see the JPanel with black background which I have created. Can anybody tell me where is my mistake?
I highlighted my code with image and paint method.

Code:
import java.awt.Container;
import java.awt.Graphics;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.ImageIcon;

class Snake extends JFrame {
	Snake(String title) {
		setTitle(title);
		setSize(300, 300);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
		
		Board b = new Board();
		Container c = getContentPane();
		c.setLayout(new BorderLayout());
		c.add(b.panel, BorderLayout.CENTER);
	}

	public static void main(String args[ ]) {
		new Snake("Snake game 2010 (c)");
	}
}

class Board extends JPanel implements ActionListener {
	private final int DELAY = 150;
	private final int WIDTH = 300;
	private final int HEIGHT = 300;
	private final int DOT_SIZE = 10;
	private final int ALL_DOTS_X = 30;
	private final int ALL_DOTS_Y = 30;
	
	private int x[ ] = new int[ALL_DOTS_X];
	private int y[ ] = new int[ALL_DOTS_Y];
	private int headX = x[(int)(ALL_DOTS_X / 2)];
	private int headY = y[(int)(ALL_DOTS_Y / 2)];
	private int bodyX = headX;
	private int bodyY = headY;
	private int appleX;
	private int appleY;
	private int bodySize = 3;

	private boolean inGame = true;
	private boolean left = true;
	private boolean up = false;
	private boolean right = false;
	private boolean down = false;
	private boolean appleStatus = false;
	
	JPanel panel;
	private Random random;
	private Timer timer;
	private Image apple;
	private Image head;
	private Image body;
	
	private Color backgroundColor = Color.BLACK;
	
	Board() {
		panel = new JPanel();
		panel.setSize(WIDTH, HEIGHT);
		panel.setBackground(backgroundColor);
		
		// images
		ImageIcon appleIcon = new ImageIcon(getClass().getResource("apple.png"));
		apple = appleIcon.getImage();
		ImageIcon headIcon = new ImageIcon(getClass().getResource("head.png"));
		head = headIcon.getImage();
		ImageIcon bodyIcon = new ImageIcon(getClass().getResource("body.png"));
		body = bodyIcon.getImage();
		
		for(int i = 0; i < (WIDTH / 10); i++)
			x[i] = i * DOT_SIZE;
		for(int i = 0; i < (HEIGHT / 10); i++)
			y[i] = i * DOT_SIZE;
		
		this.addKeyListener(new KeyAdapter() {
			public void keyPressed(KeyEvent event) {
				int keycode = event.getKeyCode();
				if(keycode == event.VK_UP && !down) {
					up = true;
					right = false;
					left = false;
					down = false;
				}
				if(keycode == event.VK_LEFT && !right) {
					left = true;
					right = false;
					up = false;
					down = false;
				}
				if(keycode == event.VK_RIGHT && !left) {
					right = true;
					left = false;
					up = false;
					down = false;
				}
				if(keycode == event.VK_DOWN && !up) {
					down = true;
					up = false;
					right = false;
					left = false;
				}
			}
		});
		
		timer = new Timer(DELAY, this);
//		timer.start();
	}
	
	void locateApple() {
		appleX = x[random.nextInt(30)];
		appleY = y[random.nextInt(30)];
	}
	
	public void paint(Graphics g) {
		super.paint(g);
		if(inGame) {
			if(!appleStatus) {
				locateApple();
				g.drawImage(apple, appleX, appleY, null);
				appleStatus = true;
			}
			
			g.drawImage(head, headX, headY, null);
			for(int i = bodySize; i == 0; i--) {
				bodyX = headX + i * DOT_SIZE;
				bodyY = headY;
				g.drawImage(body, bodyX, bodyY, null);
			}
		}
	}
	
	public void actionPerformed(ActionEvent event) {
//		if(up) {

//		}
	}
}
EDIT: Solved after 4 hours of testing and modifications

Last edited by Asido; 07-19-2010 at 03:16 PM.
 
Old 10-24-2010, 08:02 AM   #2
archtoad6
Senior Member
 
Registered: Oct 2004
Location: Houston, TX (usa)
Distribution: MEPIS, Debian, Knoppix,
Posts: 4,727
Blog Entries: 15

Rep: Reputation: 230Reputation: 230Reputation: 230
Great -- you fixed yourself & you let us know, thanks. Now, would you mind posting the actual solution -- it might help someone else. TIA.
 
Old 10-25-2010, 01:41 AM   #3
Asido
Member
 
Registered: Jan 2010
Location: Denmark
Distribution: Gentoo, Archlinux, FreeBSD, Slackware
Posts: 84

Original Poster
Rep: Reputation: 24
Quote:
Originally Posted by archtoad6 View Post
Great -- you fixed yourself & you let us know, thanks. Now, would you mind posting the actual solution -- it might help someone else. TIA.
Oh, that's an old post. This was the first real work I did with Java and first real application in my life I found the full code and I can post it here. The main problem I can see in the first post was that I add a panel created in that class, not the extended one.
Code:
import java.awt.Container;
import java.awt.Graphics;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Image;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.FontMetrics;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.ImageIcon;

import java.util.Random;

class Snake extends JFrame {
	Snake(String title) {
		setTitle(title);
		setSize(310, 335);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLocationRelativeTo(null);//jei null, padaro JFrame vidury ekrano
		setVisible(true);
		
		Board b = new Board();
		Container c = getContentPane();
		c.setLayout(new BorderLayout());
		c.add(b, BorderLayout.CENTER);
//		Board b = new Board();
//		b.setLayout(new BorderLayout());
//		setContentPane(b);
	}

	public static void main(String args[ ]) {
		new Snake("Snake game 2010 by Asido (c)");
	}
}

class Board extends JPanel implements ActionListener {
	private final int WIDTH = 302;
	private final int HEIGHT = 309;
	private final int DOT_SIZE = 10;
	private final int ALL_DOTS_X = 30;
	private final int ALL_DOTS_Y = 30;
	   
	private int x[ ] = new int[ALL_DOTS_X];
	private int y[ ] = new int[ALL_DOTS_Y];
	private int prevX[ ] = new int[ALL_DOTS_X * ALL_DOTS_Y];
	private int prevY[ ] = new int[ALL_DOTS_X * ALL_DOTS_Y];
	private int headX;
	private int headY;
	private int bodyX;
	private int bodyY;
	private int appleX;
	private int appleY;
	private int bodySize = 2;
	private int delay = 300;
	private int pausedDelay = 0;
	int score = 0;
	
	private boolean inGame = false;
	private boolean left = true;
	private boolean up = false;
	private boolean right = false;
	private boolean down = false;
	private boolean appleStatus = false;
	private boolean pause = false;
	   
	private Graphics g;
	private Font hugeFont = new Font("Luxi Mono", Font.BOLD, 30);
	private Font largeFont = new Font("Luxi Mono", Font.BOLD, 24);
	private Font smallFont = new Font("Luxi Mono", Font.PLAIN, 14);
	private Font tinyFont = new Font("Luxi Mono", Font.BOLD, 10);
	private Random random = new Random();
	private Timer timer;
	private Image apple;
	private Image head;
	private Image body;
	
	private Color backgroundColor = Color.BLACK;
	private Color stringColor = Color.WHITE;
	
	private MovementHandler movementHandler = new MovementHandler();
	private RestartHandler restartHandler = new RestartHandler();
	   
	Board() {
		addKeyListener(movementHandler);
		setSize(WIDTH, HEIGHT);
		setBackground(backgroundColor);
		
		// images
		ImageIcon appleIcon = new ImageIcon(Board.class.getResource("apple.png"));
		apple = appleIcon.getImage();
		ImageIcon headIcon = new ImageIcon(Board.class.getResource("head.png"));
		head = headIcon.getImage();
		ImageIcon bodyIcon = new ImageIcon(Board.class.getResource("body.png"));
		body = bodyIcon.getImage();
		
		timer = new Timer(delay, this);
        timer.start();
        
		setFocusable(true);//kad KeyEventai veiktu ant JPanel
		
		begining();
    }
   
    void locateApple() {
        appleX = x[random.nextInt(ALL_DOTS_X)];
        appleY = y[random.nextInt(ALL_DOTS_Y)];
        
        for(int i = 0; i < bodySize; i++) {
        	if((appleX == prevX[i] && appleY == prevY[i]) || (appleX == headX && appleY == headY))
        		locateApple();
        }
    }
    
    void begining() {
    	inGame = true;
    	left = true;
    	right = false;
    	up = false;
    	down = false;
    	
    	bodySize = 3;
    	score = 0;
    	
    	addKeyListener(movementHandler);
    	
    	for(int i = 0; i < (WIDTH / 10); i++)
			x[i] = i * DOT_SIZE;
		for(int i = 0; i < (HEIGHT / 10); i++)
			y[i] = i * DOT_SIZE;
		locateApple();
		headX = x[((int)(ALL_DOTS_X / 2))];
		headY = y[((int)(ALL_DOTS_Y / 2))];
		
		for(int i = 0; i < bodySize; i++) {
			prevX[i] = headX + i * DOT_SIZE;
			prevY[i] = headY;
		}
		
		setTimerDelay(200);
    }
    
    void setTimerDelay(int delay) {
    	timer.setDelay(delay);
    }
   
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if(inGame) {
            if(!appleStatus) {
                g.drawImage(apple, appleX, appleY, this);
            }
            
            g.setColor(stringColor);
            g.setFont(tinyFont);
            g.drawString("Score: " + score, 5, (HEIGHT - 1));
            g.setColor(Color.DARK_GRAY);
            g.drawLine(0, (HEIGHT - 10), WIDTH, (HEIGHT - 10));
            
            g.drawImage(head, headX, headY, this);
            for(int i = 0; i < bodySize; i++) {
                bodyX = prevX[i];
                bodyY = prevY[i];
                g.drawImage(body, bodyX, bodyY, this);
            }
            
            if(pause) {
            	g.setFont(hugeFont);
            	g.setColor(stringColor);
            	FontMetrics hugeFM = g.getFontMetrics(hugeFont);
            	g.drawString("Paused", ((WIDTH - hugeFM.stringWidth("Paused")) / 2), (HEIGHT / 2));
            }
            
            Toolkit.getDefaultToolkit().sync();
            g.dispose();
        }
        else 
        	gameOver(g);
    }
   
    void gameOver(Graphics g) {
    	String gameOverMessage = "Game Over";
    	String restartMessage = "Press 'R' to restart";
    	String scoreMessage = "Score: " + score;
    	
    	inGame = false;
    	g.setFont(largeFont);
    	g.setColor(stringColor);
    	FontMetrics largeFM = g.getFontMetrics(largeFont);
    	g.drawString(gameOverMessage, ((WIDTH - largeFM.stringWidth(gameOverMessage)) / 2), (HEIGHT / 2));
    	
    	removeKeyListener(movementHandler);
    	addKeyListener(restartHandler);
    	
    	FontMetrics hugeFM = g.getFontMetrics(hugeFont);
    	g.setFont(hugeFont);
    	g.drawString(scoreMessage, ((WIDTH - hugeFM.stringWidth(scoreMessage)) / 2), (HEIGHT / 3 * 2));
    	g.setFont(smallFont);
    	g.drawString(restartMessage, 10, (HEIGHT - 20));
    }
    
    void restart() {
    	begining();
    	repaint();
    	
    }
    
    void detectCollision() {
    	if(headX < 0 || headX > 290 || headY < 0 || headY > 290)
    		inGame = false;
    	if(bodySize > 3) {	
    		for(int i = 0; i < bodySize; i++) {
    			if(headX == prevX[i] && headY == prevY[i])
    				inGame = false;
    		}
    	}
    }
    
    void checkApple() {
    	if(appleX == headX && appleY == headY) {
    		bodySize++;
    		score += 100;
    		locateApple();
    		
/*    		switch(bodySize) {
    			case 10: setTimerDelay(190); break;
    			case 15: setTimerDelay(170); break;
    			case 20: setTimerDelay(150); break;
    			case 25: setTimerDelay(140); break;
    			case 30: setTimerDelay(130); break;
    			case 35: setTimerDelay(120); break;
    		}
*/    	}
    }
    
    void pause() {
    	if(pause) {
    		timer.stop();
    		repaint();
    	}
    	else
    		timer.start();
    }
    
    void move() {
    	for(int i = bodySize; i >= 0; i--) {
    		if(i > 0) {
    			prevX[i] = prevX[i-1];
    			prevY[i] = prevY[i-1];
    		}
    		else {
    			prevX[i] = headX;
    			prevY[i] = headY;
    		}
    	}
    	
    	if(up)
        	headY -= DOT_SIZE;
    	if(down)
    		headY += DOT_SIZE;
    	if(left)
    		headX -= DOT_SIZE;
    	if(right)
    		headX += DOT_SIZE;
    }
    
    public void actionPerformed(ActionEvent event) {
    	if(inGame) {	
    		detectCollision();
    		checkApple();
    		move();
    	}
    	repaint();
    }
    
    private class MovementHandler implements KeyListener {
    	public void keyPressed(KeyEvent event) {
    		int keycode = event.getKeyCode();
			if(keycode == KeyEvent.VK_UP && !down) {
				up = true;
				right = false;
				left = false;
				down = false;
			}
			if(keycode == KeyEvent.VK_LEFT && !right) {
               	left = true;
               	right = false;
               	up = false;
               	down = false;
            }
            if(keycode == KeyEvent.VK_RIGHT && !left) {
               	right = true;
               	left = false;
               	up = false;
               	down = false;
            }
            if(keycode == KeyEvent.VK_DOWN && !up) {
                down = true;
                up = false;
                right = false;
                left = false;
            }
            if(keycode == KeyEvent.VK_P || keycode == KeyEvent.VK_PAUSE) {
            	pause = !pause;
            	pause();
            }
    	}
    	
    	public void keyReleased(KeyEvent e) {}
    	public void keyTyped(KeyEvent e) {}
    }
    
    private class RestartHandler implements KeyListener {
    	public void keyPressed(KeyEvent event) {
    		int keycode = event.getKeyCode();
    		if(keycode == KeyEvent.VK_R)
    			restart();
    	}
    	
    	public void keyReleased(KeyEvent e) {}
    	public void keyTyped(KeyEvent e) {}
    }
}

Last edited by Asido; 10-25-2010 at 01:45 AM.
 
1 members found this post helpful.
Old 10-25-2010, 06:33 AM   #4
archtoad6
Senior Member
 
Registered: Oct 2004
Location: Houston, TX (usa)
Distribution: MEPIS, Debian, Knoppix,
Posts: 4,727
Blog Entries: 15

Rep: Reputation: 230Reputation: 230Reputation: 230
Thanks for responding w/ the solution.

A suggestion for the future: If you answer your own question, put the solution in a separate post; this does 2 good things:
  • It generates e-mail to anyone subscribed to either the thread or the forum.
  • It avoids the creation of oxymoronic 0-reply solved threads.

Last edited by archtoad6; 10-26-2010 at 06:24 AM. Reason: typo: "In" -> "It" (oops)
 
Old 10-26-2010, 04:05 AM   #5
Asido
Member
 
Registered: Jan 2010
Location: Denmark
Distribution: Gentoo, Archlinux, FreeBSD, Slackware
Posts: 84

Original Poster
Rep: Reputation: 24
Quote:
Originally Posted by archtoad6 View Post
Thanks for responding w/ the solution.

A suggestion for the future: If you answer your own question, put the solution in a separate post; this does 2 good things:
  • It generates e-mail to anyone subscribed to either the thread or the forum.
  • In avoids the creation of oxymoronic 0-reply solved threads.
Thank's for telling. I'll do it next time.
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Azureus Loading problem..[Java error] netpumber Slackware 5 03-03-2010 11:40 AM
images not loading on firefox divyashree Linux - Newbie 12 05-07-2009 12:13 AM
java works but I cannot login, loading and loading, firewall? Eric Vazquez Linux - Newbie 2 02-03-2009 08:57 PM
httpd.conf - problem with loading images proNick Linux - Newbie 2 01-31-2009 06:59 AM
Images not loading in website robojerk Linux - Newbie 1 02-17-2005 09:44 AM


All times are GMT -5. The time now is 10:51 PM.

Main Menu
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration