ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
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.
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
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.
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.
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?
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...
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.
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.
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
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).
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.