【发布时间】:2018-07-29 04:55:49
【问题描述】:
我正在构建一个游戏,目标是让骑士在世界各地移动,并能够与其他骑士战斗。
我有一个启动游戏的 Main 类:
public class Main {
public static void main(String[] args) {
new Game();
}
}
创建 JFrame 的类 Game:
import java.awt.GridLayout;
import javax.swing.JFrame;
public class Game {
public Game() {
JFrame frame = new JFrame();
frame.setTitle("Knights Tournament");
frame.add(new Board());
frame.setSize(700, 700);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
还有一个类 Board(你猜对了!)创建了 GameBoard:
public class Board extends JPanel {
Tile[][] grid = new Tile[15][15];
public Board(){
// Create the grid
CreateGrid();
// Add the player
grid[0][0] = new Player(0, 0);
}
// Method that creates a grid of tiles
private void CreateGrid() {
setLayout(new GridLayout (15, 15));
for(int i = 0; i < 15; i++){
for(int j = 0; j < 15; j++){
grid[i][j] = new Tile(i, j);
add(grid[i][j]);
}
}
}
}
网格最初由 15x15 个图块组成。
public class Tile extends JButton implements ActionListener {
public int xCo;
public int yCo;
public Tile(int x, int y) {
setXCo(x);
setYCo(y);
}
public void setXCo(int x) {
this.xCo = x;
}
public void setYCo(int y) {
this.yCo = y;
}
public int getXCo() {
return xCo;
}
public int getYCo() {
return yCo;
}
}
我面临的问题如下:我想用另一个扩展图块的类 Player 替换 grid[0][0]。 tile 和 player 之间的区别在于 Jbutton 会收到一条说“P”的文本,我试过这个:
public class Player extends Tile{
public Player(int x, int y) {
super(x, y);
this.setText("P");
}
}
在类板的构造函数中,我尝试将 grid[0][0] 从 tile 更改为 player,以便它显示 P,但由于某种原因它没有这样做(它确实改变了 grid[0] 的类型][0] 给玩家...)希望有人能提供帮助。
【问题讨论】:
-
为什么不直接更新现有的
Title状态而不是在板上替换它? -
玩家类将获得额外的变量,如“攻击”、“防御”等……我还将添加我能够与之战斗的敌人。要检查图块是否包含敌人,我想使用 instanceof 函数...
-
所以如果你明白我的意思的话,瓷砖应该被玩家替换
-
这个信息应该是模型层的一部分,而不是 UI,UI 代表模型的状态,模型管理事物的工作方式,控制器管理两者之间的交互...
标签: java swing user-interface jbutton