【发布时间】:2015-03-26 06:34:07
【问题描述】:
我有三个班级,并且正在尝试制作一个游戏,让用户根据骰子滚动的内容沿着网格移动。
我有我的主要 BoardGame 类,包含 GUI 和当前是 Jlabel 图像的计数器(我愿意接受关于我可以使用什么来代替 JLabel 的建议 - 我自己不太确定)。我有一个 Grid 类,我将它排列成一个二维数组并在 BoardGame 类中调用了一个实例,我有一个骰子类,它从 1-6 中滚动一个随机数。
我试图让我的计数器从网格上的第一个方格开始,然后以从左到右、从右到左的方式前进。但是,我不确定如何让计数器首先在网格中移动。希望如果我能弄清楚这一点,我相信我可以实现它们通过模具移动特定数量。
提前感谢您的帮助
游戏板类:
public class GameBoard extends javax.swing.JFrame {
private JLabel Board;
private JLabel GreenDot;
private JLabel redDot;
private JButton startButton;
private Grid grid;
private Die die;
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Grid grid = new Grid();
GameBoard inst = new GameBoard(grid);
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public GameBoard(Grid grid) {
super();
this.grid = grid;
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
getContentPane().setLayout(null);
{
redDot = new JLabel();
getContentPane().add(redDot);
redDot.setText("jLabel1");
redDot.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/download.png")));
redDot.setBounds(220, 434, 20, 12);
redDot.setBorder(new LineBorder(new java.awt.Color(0,0,0), 1, false));
}
{
GreenDot = new JLabel();
getContentPane().add(GreenDot);
GreenDot.setText("jLabel1");
GreenDot.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/3d-green-ball-th.png")));
GreenDot.setBounds(222, 453, 21, 13);
GreenDot.setBorder(new LineBorder(new java.awt.Color(0,0,0), 1, false));
}
{
startButton = new JButton();
getContentPane().add(startButton);
startButton.setText("Start Game");
startButton.setBounds(64, 443, 83, 23);
}
{
Board = new JLabel();
getContentPane().add(Board);
Board.setLayout(null);
Board.setText("jLabel1");
Board.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/board.jpg")));
Board.setBounds(204, -1, 742, 484);
}
pack();
this.setSize(963, 523);
} catch (Exception e) {
//add your error handling code here
e.printStackTrace();
}
}
}
网格类:
public class Grid {
int[][] multi = {
{ 0, 0,-1, 0, 0,-1, 0,-1, 0, 0},
{ 0, 0, 0, 0, 0, 0,-1, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
{ 0,-1, 0,-1, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0,-1, 0, 0, 1},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{ 1, 0, 0, 0, 0, 0, 0, 1, 0, 0},
{ 0, 0, 0,-1, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 1, 0, 0, 0, 0, 1, 0}
};
}
模具类:
public class Die {
public Die() {
}
public void dieRoll() {
int SIDES = 6;
int roll = (int) (Math.random() * SIDES) + 1;
System.out.println(roll);
}
}
【问题讨论】:
-
您将不得不以不同的方式考虑它。您可以假装它,而不是试图“物理地”移动一个对象。您可以在网格中设置一系列
JLabels(将它们维护在数组的List中)并简单地更改它们的icon属性以指示它们在板上的位置 - 作为一个想法。此外,如果您使用类似OverlayLayout的东西,您甚至可以叠加多层网格,以便添加其他元素