我正在创建一个游戏,允许一个玩家通过键盘上的箭头键在用户输入的情况下在棋盘上移动。目标是收集板上的宝石并避免随机移动的怪物。我在让我的板子在 GUI 中绘制时遇到了问题。每个“tile”、“item”和“character”都是使用简单的通用绘制方法绘制的,例如 drawRect 和 drawOval。但是,我不知道如何将这些绘制在一组面板中。
我的问题是在构造函数中还是在绘制方法中?帮助!
public class LevelPanel extends JPanel {
private static Player player;
private Level level;
private JLabel gemLabel, scoreLabel, healthLabel;
private JPanel[][] squares;
private JPanel boardPanel;
private JOptionPane optionPane = new JOptionPane();
public LevelPanel() {
this.player = player;
setPreferredSize(new Dimension(300,300));
setBackground(Color.white);
setLayout(new GridLayout(10,10));
gemLabel = new JLabel("Gems Left: 0");
scoreLabel = new JLabel("Score: 0");
healthLabel = new JLabel("Health: 100");
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
squares[i][j] = new JPanel();
squares[i][j].setBackground(Color.white);
boardPanel.add(squares[i][j]);
}
}
add(gemLabel);
add(scoreLabel);
add(healthLabel);
add(boardPanel);
}
public void paint(Graphics g) {
super.paint(g);
level.draw(g);
}
private class KeyHandler extends KeyAdapter {
public void keyPressed (KeyEvent e) {
int keyCode = e.getKeyCode();
switch(keyCode) {
case KeyEvent.VK_UP:
player.move(-1,0);
break;
case KeyEvent.VK_DOWN:
player.move(1,0);
break;
case KeyEvent.VK_LEFT:
player.move(0,-1);
break;
case KeyEvent.VK_RIGHT:
player.move(0,1);
break;
}
gemLabel.setText("Gems Left: " + level.getNumGems());
scoreLabel.setText("Score: " + player.getScore());
healthLabel.setText("Health: " + player.getHealth());
repaint();
}
}