LinuxQuestions.org
Go Job Hunting at the LQ Job Marketplace
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 02-24-2004, 02:49 PM   #1
titanium_geek
Senior Member
 
Registered: May 2002
Location: Melbourne Australia
Distribution: it died/ macosx
Posts: 2,478

Rep: Reputation: 50
java arrays and objects


how do you reference objects from an array?

My project is to make a slider game (you know those 9 piece puzzle games with one piece missing? you slide around the squares to complete the picture).

I have decided to use arrays for this one, as I have not used them before, and it will be a good learning exercise.

Ok so this is the array related code:
Code:
//the buttons for the grid (the puzzle pieces!)
  JButton a = new JButton();
  JButton b = new JButton();
  JButton c = new JButton();
  JButton d = new JButton();
  JButton e = new JButton();
  JButton f = new JButton();
  JButton g = new JButton();
  JButton h = new JButton();
  JButton i = new JButton();
  
  //boolean variables for the game mechanism
  boolean tl = false;
  boolean tc = false;
  boolean tr = false;
  boolean ml = false;
  boolean mc = false;
  boolean mr = false;
  boolean bl = false;
  boolean bc = false;
  boolean br = true;
  
  //the array (the key part of the program)
  String[] blocks = {"a","b","c","d","e","f","g","h","i"};
  String[] legal = {"tl","tc","tr","ml","mc","mr","bl","bc","br"};
  String[] location = new String[9];
how do you make an array of objects
how do you make an array controll objects?
location: what do I use instead of String?

sorry if this is confusing, by all means, ask me to clarify.

titanium_geek.
 
Old 02-24-2004, 03:24 PM   #2
Looking_Lost
Senior Member
 
Registered: Apr 2003
Location: Eire
Distribution: Slackware 12.0, OpenSuse 10.3
Posts: 1,120

Rep: Reputation: 45
You mean like this ?

JButton[] buttons=new JButton[9];

or

JButton[][] buttons=new JButton[3][3]; which represents your grid better



which are an arrays with the capacity to hold 9 JButtons and can ue used, well, like you'd use an array or can be manipulated by the Array class, depends really what you're ultimately going to do with it.

Not sure at all what you're meaning about the location String
 
Old 02-24-2004, 03:33 PM   #3
titanium_geek
Senior Member
 
Registered: May 2002
Location: Melbourne Australia
Distribution: it died/ macosx
Posts: 2,478

Original Poster
Rep: Reputation: 50
thanks!.
will try and think of a non confusing explaination of what I'm trying to do.

titanium_geek
 
Old 02-24-2004, 03:46 PM   #4
german
Member
 
Registered: Jul 2003
Location: Toronto, Canada
Distribution: Debian etch, Gentoo
Posts: 312

Rep: Reputation: 30
If you're making a slider game you'd do well to make an array of Objects which represent one of the eight movable tiles, then have a property of each which indicates its location, allowable moves, etc. etc. and manipulate them in the game's logic code. So you have something like

Code:
Tile[] tiles = new Tile[9]; // one of them is always null

/*
tiles wd map to a real puzzle like this:

 0  1  2
 3  4  5
 6  7  8
*/



public void move(int idx, int newIdx) {
  if(idx == null) return; // cannot move an empty space
  if(newIdx != null) return; // cannot move on top of another piece

 // move the first,
  tiles[newIdx] = tiles[idx];

// and then make sure the other is null (arrays can contain the same object twice).
  tiles[idx] = null;  
}
Then you just need to do things like repaint the screen, check if they've won, etc.

HTH

B.

Last edited by german; 02-24-2004 at 03:49 PM.
 
Old 02-24-2004, 09:02 PM   #5
german
Member
 
Registered: Jul 2003
Location: Toronto, Canada
Distribution: Debian etch, Gentoo
Posts: 312

Rep: Reputation: 30
You prompted my interests, titanium_geek, so I wrote one since my last post... It's an excellent project to learn how to deal with arrays. If you need any pointers just ask.

B.
 
Old 03-01-2004, 05:16 PM   #6
titanium_geek
Senior Member
 
Registered: May 2002
Location: Melbourne Australia
Distribution: it died/ macosx
Posts: 2,478

Original Poster
Rep: Reputation: 50
german: thankyou thankyou thankyou thankyou.
can you make it an applet and put it up so I can see it? just out of interests sake.

and, what are the tiles? how would you put them on a screen?
My friend wrote a java tictac toe program, using buttons and a grid layout nested in a border layout. would I use buttons?

rock on
titanium_geek
 
Old 03-01-2004, 09:23 PM   #7
german
Member
 
Registered: Jul 2003
Location: Toronto, Canada
Distribution: Debian etch, Gentoo
Posts: 312

Rep: Reputation: 30
This is exactly what I wrote out of pure interest based on the fact I hadn't done it... making an Applet out of this code would be relatively trivial...

Code:
/*
 * Created on Feb 24, 2004
 *
 * Sliding Puzzle
 */
package jamin.puzzles.slidingpuzzle;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.util.*;
import java.io.*;
/**
 * @author Ben Clarke
 *  
 */
public class SlidingPuzzle extends JPanel 
		implements Comparator, MouseListener, ActionListener {
	private static final int MAX_SIZE = 640;
	private Random random = new Random(System.currentTimeMillis());
	private Dimension gridSize;
	private Tile[][] tiles, randomized;
	private int totalMoves = 0;
	private BufferedImage img = null;
	private byte[] imgData = null;
	private boolean showNumbers = true;
	private JFrame frame;
	
	public SlidingPuzzle(int rows, int cols) {
		init(rows,cols);
	}
	
	private void init(int rows, int cols) {
		gridSize = new Dimension(cols, rows);
		tiles = new Tile[cols][rows];
		for (int i = 0; i < tiles.length; i++) {
			for (int j = 0; j < tiles[i].length; j++) {
				int n = (j * tiles.length) + i + 1;
				if (n < rows * cols) {
					tiles[i][j] = new Tile();
					tiles[i][j].setIdx(n);
					tiles[i][j].setName(String.valueOf(n));
				}
			}
		}
		randomize();
		addMouseListener(this);
		img = null;
	}
	
	public void loadImage(File f) {
		try {
			RandomAccessFile file = new RandomAccessFile(f, "r");
			imgData = new byte[(int) file.length()];
			file.readFully(imgData);
			file.close();
			img = null;
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	private void randomize() {
		ArrayList list = new ArrayList();
		for (int i = 0; i < tiles.length; i++)
			for (int j = 0; j < tiles[i].length; j++) {
				list.add(tiles[i][j]);
			}
		for (int i = 0; i < 100; i++) {
			Collections.sort(list, this);
		}
		
		randomized = new Tile[tiles.length][tiles[0].length];
		
		for (int i = 0; i < tiles.length; i++)
			for (int j = 0; j < tiles[i].length; j++) {
				int n = (j * tiles.length) + i;
				randomized[i][j] = (Tile) list.get(n);
			}
		repaint();
	}
	
	public int compare(Object a, Object b) {
		// gross misuse of a nice sorting algorithm
		return random.nextInt(100) - 50 > 0 ? 1 : -1;
	}
	public void mouseClicked(MouseEvent evt) {
		Point p = evt.getPoint();
		Dimension tileSize = new Dimension(getSize().width / gridSize.width,
				getSize().height / gridSize.height);
		Tile target = null;
		Point emptyIdx = null;
		Point targetIdx = null;
		for (int i = 0; i < randomized.length; i++) {
			for (int j = 0; j < randomized[i].length; j++) {
				int x = (tileSize.width) * i;
				int y = (tileSize.height) * j;
				if(p.x > x && p.x < x + tileSize.width 
				&& p.y > y && p.y < y + tileSize.height) {
					target = randomized[i][j];
					targetIdx = new Point(i, j);
				}
				if (randomized[i][j] == null)
					emptyIdx = new Point(i, j);
			}
		}
		if (target != null) {
			if (targetIdx.equals(emptyIdx))
				return;
			if (targetIdx.x == emptyIdx.x) {
				int deltaY = Math.max(targetIdx.y, emptyIdx.y)
						- Math.min(targetIdx.y, emptyIdx.y);
				if (targetIdx.y > emptyIdx.y) {
					for (int i = emptyIdx.y; i < targetIdx.y; i++) {
						randomized[targetIdx.x][i] = randomized[targetIdx.x][i + 1];
					}
				} else {
					for (int i = emptyIdx.y; i > targetIdx.y; i--) {
						randomized[targetIdx.x][i] = randomized[targetIdx.x][i - 1];
					}
				}
				totalMoves += deltaY;
				randomized[targetIdx.x][targetIdx.y] = null;
			} else if (targetIdx.y == emptyIdx.y) {
				int deltaX = Math.max(targetIdx.x, emptyIdx.x)
						- Math.min(targetIdx.x, emptyIdx.x);
				if (targetIdx.x > emptyIdx.x) {
					for (int i = emptyIdx.x; i < targetIdx.x; i++) {
						randomized[i][targetIdx.y] = randomized[i + 1][targetIdx.y];
					}
				} else {
					for (int i = emptyIdx.x; i > targetIdx.x; i--) {
						randomized[i][targetIdx.y] = randomized[i - 1][targetIdx.y];
					}
				}
				totalMoves += deltaX;
				randomized[targetIdx.x][targetIdx.y] = null;
			}
			repaint();
			boolean hasWon = true;
			for (int i = 0; i < tiles.length; i++)
				for (int j = 0; j < tiles[i].length; j++) {
					int n = (j * tiles.length) + i + 1;
					if (tiles[i][j] != null && tiles[i][j] != randomized[i][j])
						hasWon = false;
				}
			if (hasWon) {
				JOptionPane.showMessageDialog(this, "You Won in " + totalMoves
						+ " moves!\nCongratulations.");
				totalMoves = 0;
				randomize();
			}
		}
	}
	public void mouseEntered(MouseEvent evt) {}
	public void mouseExited(MouseEvent evt) {}
	public void mousePressed(MouseEvent evt) {}
	public void mouseReleased(MouseEvent evt) {}
	
/**
 * PAINT
 */
	public void paint(Graphics g) {
		Dimension tileSize = new Dimension(getSize().width / gridSize.width,
				getSize().height / gridSize.height);
		
		g.setColor(Color.black);
		g.fillRect(0,0,getSize().width,getSize().height);
		
		if(
		(img == null 
		|| img.getWidth() != getSize().width 
		|| img.getHeight() != getSize().height)
		&& imgData != null) {
			
			Image image = Toolkit.getDefaultToolkit().createImage(imgData);
			MediaTracker tracker = new MediaTracker(this);
			tracker.addImage(image, 0);
			try {
				tracker.waitForID(0);
			} catch (InterruptedException ie) {}
			
//			int imgX = image.getWidth(this);
//			int imgY = image.getHeight(this);
//			
//			if(imgX > MAX_SIZE) {
//				imgY = calculateHeight(MAX_SIZE,imgY,imgX);
//				imgX = MAX_SIZE;
//			} else
//			if(imgY > MAX_SIZE) {
//				imgX = calculateWidth(MAX_SIZE,imgY,imgX);
//				imgY = MAX_SIZE;
//			}
//			
//			frame.setSize(imgX,imgY + 20);
//			setSize(imgX,imgY);
//			
			tileSize = new Dimension(getSize().width / gridSize.width,
					getSize().height / gridSize.height);
			
			img = new BufferedImage(
					getSize().width,
					getSize().height,
					BufferedImage.TYPE_INT_RGB
			);
			
			Graphics2D g2d = img.createGraphics();
			g2d.drawImage(image,0,0,getSize().width,getSize().height,this);
			
			for(int i=0; i<tiles.length; i++) {
				for(int j=0; j<tiles[i].length; j++) {
					
					int x = (tileSize.width) * i;
					int y = (tileSize.height) * j;
//					g2d.setClip(x, y, tileSize.width, tileSize.height);
					
					if (tiles[i][j] != null) {
						tiles[i][j].setImage(
								img.getSubimage(
										x, 
										y, 
										tileSize.width, 
										tileSize.height
								)
						);
					}
				}
			}
		}
		
		for (int i = 0; i < randomized.length; i++) {
			for (int j = 0; j < randomized[i].length; j++) {
				int x = (tileSize.width) * i;
				int y = (tileSize.height) * j;
				g.setClip(x, y, tileSize.width, tileSize.height);
				
				if (randomized[i][j] != null) {
					if(img != null) {
						
						g.drawImage(
								randomized[i][j].getImage(),
								x,
								y,
								tileSize.width,
								tileSize.height,
								this
						);
					} else {
						((Graphics2D)g).setPaint(new GradientPaint(
								0,0,Color.orange,
								getSize().width,getSize().height,Color.blue)
						);
						g.fillRect(x, y, tileSize.width, tileSize.height);					
					}
									
					if(showNumbers) {
						g.setColor(Color.green);
						g.drawString(randomized[i][j].getName(), x
							+ (tileSize.width / 2), y + (tileSize.height / 2));
					}
				} else {
					g.setColor(Color.darkGray);
					g.fillRect(x,y,tileSize.width,tileSize.height);
				}
				g.setColor(Color.black);
				g.drawRect(x, y, tileSize.width, tileSize.height);
			}
		}
	}
	
	private class Tile {
		private String name;
		private int idx;
		private BufferedImage img;
		
		public int getIdx() {
			return idx;
		}
		public void setIdx(int idx) {
			this.idx = idx;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public void setImage(BufferedImage image) {
			this.img = image;
		}
		public BufferedImage getImage() { return img; }
	}
	
	public JMenuBar buildMenu() {
		
		JMenuBar bar = new JMenuBar();
		JMenu menu = new JMenu("File");
		JMenuItem item = new JMenuItem("Exit");
		item.addActionListener(this);
		menu.add(item);
		bar.add(menu);
		menu = new JMenu("Options");
		
		item = new JMenuItem("3x3");
		item.addActionListener(this);
		menu.add(item);
		item = new JMenuItem("4x4");
		item.addActionListener(this);
		menu.add(item);
		item = new JMenuItem("6x6");
		item.addActionListener(this);
		menu.add(item);
		item = new JMenuItem("12x12");
		item.addActionListener(this);
		menu.add(item);
		
		menu.addSeparator();
		
		item = new JMenuItem("Choose Background...");
		item.addActionListener(this);
		menu.add(item);
		
		item = new JMenuItem("Toggle Tile Numbers");
		item.addActionListener(this);
		menu.add(item);
		
		bar.add(menu);
		
		return bar;
	}
	
	public void actionPerformed(ActionEvent evt) {
		String cmd = evt.getActionCommand();
		if("3x3".equals(cmd)) {
			init(3,3);
		} else
		if("4x4".equals(cmd)) {
			init(4,4);			
		} else
		if("6x6".equals(cmd)) {
			init(6,6);
		} else
		if("12x12".equals(cmd)) {
			init(12,12);
		} else
		if("Exit".equals(cmd)) {
			System.exit(0);
		} else
		if("Choose Background...".equals(cmd)) {
			JFileChooser chooser = new JFileChooser(System.getProperty("User.home"));
			int result = chooser.showOpenDialog(this);
			if(result == JFileChooser.APPROVE_OPTION) {
				File selected = chooser.getSelectedFile();
				loadImage(selected);
				repaint();
			}
		}  else
		if("Toggle Tile Numbers".equals(cmd)) {
			showNumbers = !showNumbers;
			repaint();
		}
	}
	
	private int calculateWidth(int height, int imgHeight, int imgWidth) {
	    float h = (float)height;
	    float ih = (float)imgHeight;
	    float iw = (float)imgWidth;

	    float x = h / ih;
	    return (int)(iw * x);
	}

	private int calculateHeight(int width, int imgHeight, int imgWidth) {
	    float w = (float)width;
	    float ih = (float)imgHeight;
	    float iw = (float)imgWidth;

	    float x = w / iw;
	    return (int)(ih * x);
	}
	
	public JFrame initFrame() {
		frame = new JFrame("Sliding Puzzle");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().add(this);
		frame.setJMenuBar(buildMenu());
		frame.setSize(300,300);
		frame.setVisible(true);
		return frame;
	}
	
	public static void main(String[] args) throws Exception {
		SlidingPuzzle sp = new SlidingPuzzle(3,3);
		sp.initFrame();
		sp.repaint();
	}
}
I had to cut and paste it in pieces so if it don't work then tell me where it blows up, but there's some stuff removed cuz I couldn't get the frame to resize to the image proportions, with the maximum width or height being 640 pixels (the frame wd resize, but the image and tiles wd not).

Anyway, good luck in porting it to an applet, shouldn't be too hard...

B.

Last edited by german; 03-04-2004 at 05:02 PM.
 
Old 03-02-2004, 05:59 AM   #8
titanium_geek
Senior Member
 
Registered: May 2002
Location: Melbourne Australia
Distribution: it died/ macosx
Posts: 2,478

Original Poster
Rep: Reputation: 50
thanks german, that is really helpful. I want to try and actuallly get a program off the ground, at the moment, I have a lot of half finished projects.

rock on.
titanium_geek
 
Old 03-04-2004, 04:35 PM   #9
titanium_geek
Senior Member
 
Registered: May 2002
Location: Melbourne Australia
Distribution: it died/ macosx
Posts: 2,478

Original Poster
Rep: Reputation: 50
I get errors.

Umm.. could you make it an applet so I can see what it looks like? please?

thanks

titanium_geek
 
Old 03-04-2004, 05:00 PM   #10
german
Member
 
Registered: Jul 2003
Location: Toronto, Canada
Distribution: Debian etch, Gentoo
Posts: 312

Rep: Reputation: 30
um... what errors do you get? I can run it as an applet simply by creating the following class and running it in the JDK applet viewer....

Code:
import javax.swing.JApplet;
import java.awt.HeadlessException;

public class SlidingPuzzleApplet extends JApplet {
	
	public SlidingPuzzleApplet() throws HeadlessException {
		super();
	}
	
	public void init() {
		SlidingPuzzle sp = new SlidingPuzzle(3,3);
		getContentPane().add(sp);
		setJMenuBar(sp.buildMenu());
		repaint();
	}
}
Also note I replaced the SlidingPuzzle class above, it was cut and pasted as a whole this time in case I made a mistake copying it before...

HTH

B.

Last edited by german; 03-04-2004 at 05:03 PM.
 
Old 03-05-2004, 05:40 AM   #11
titanium_geek
Senior Member
 
Registered: May 2002
Location: Melbourne Australia
Distribution: it died/ macosx
Posts: 2,478

Original Poster
Rep: Reputation: 50
umm... compiles ok... but doesn't run. I want to see what it looks like, could you put it online as an applet? do you have a web page?

Thankyou so much. I am close to getting this program done, as soon as school work lets up.

titanium_geek
 
Old 03-05-2004, 10:47 AM   #12
german
Member
 
Registered: Jul 2003
Location: Toronto, Canada
Distribution: Debian etch, Gentoo
Posts: 312

Rep: Reputation: 30
atm I barely have an internet connection unfortunately... what errors do you get trying to run it? This is approximately what it looks like when it's running...

[ 7 ][ 2 ]
[ 6 ][ 4 ][ 1 ]
[ 8 ][ 5 ][ 3 ]

except there's a gradient going from top left to bottom right fading blue->orange unless you load an image from the options menu.

B.
 
Old 03-05-2004, 02:56 PM   #13
german
Member
 
Registered: Jul 2003
Location: Toronto, Canada
Distribution: Debian etch, Gentoo
Posts: 312

Rep: Reputation: 30
Ok titanium_geek, I put it up for you. It crashes my firefox whenever I look at it, but so does every other applet so I don't think it's my code... it's at

http://german.is-a-geek.com/applet.php

edit: the tripod ads were breaking it for some reason... and it was the version of java I was using (1.5 beta) which was crashing firefox... I switched it back to 1.4.2_02 and it works fine... I also added a small method to load images from URL's, and the PHP just lists some images I have on that server so you can choose your background (cuz the one in the menu don't work, because of applet security restrictions).

B.

Last edited by german; 03-05-2004 at 04:12 PM.
 
Old 03-07-2004, 02:21 PM   #14
titanium_geek
Senior Member
 
Registered: May 2002
Location: Melbourne Australia
Distribution: it died/ macosx
Posts: 2,478

Original Poster
Rep: Reputation: 50
thanks german.
I appreciate it.
 
  


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
java objects zaicheke Programming 3 03-23-2005 07:21 AM
java + arrays dilberim82 Programming 3 02-12-2005 03:33 PM
segmentation error c++ arrays with objects ajay_linux LQ Suggestions & Feedback 0 04-30-2004 12:21 PM
arrays of pointers to class objects tdurden Programming 5 12-16-2002 11:47 AM
Objects in Java? mikeshn Programming 0 06-11-2002 11:21 AM


All times are GMT -5. The time now is 11:07 PM.

Main Menu
Advertisement
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