所以基本上我正在使用 javafx 创建一个游戏板,我有一个单元格状态类,此时根据单元格中的内容返回一个字符值。所以基本上如果单元格是空的,它返回' '
,如果我有一个玩家,它返回'@'
,依此类推不同的单元状态。我只是想知道如何返回图像而不是字符。
public class Cell {
CellState cellState;
public Cell(CellState newCellState) {
cellState = newCellState;
}
public CellState getCellState() {
return cellState;
}
public void setCellState(CellState newCellState)
{
cellState = newCellState;
}
public char displayCellState()
{
return getCellStateCharacter(cellState);
}
public char getCellStateCharacter(CellState newCellState)
{
switch (newCellState)
{
case EMPTY:
return ' ';
case PLAYER:
return '@';
case MONSTER:
return '&';
case POISON:
return '*';
case BLOCKED:
return '#';
default:
return ' ';
}
}
}
MY CELL STATE CLASS
public enum CellState
{
EMPTY,
PLAYER,
MONSTER,
POISON,
BLOCKED
};
public class GameBoard {
static final int BOARD_WIDTH = 10;
static final int BOARD_HEIGHT = 10;
Cell[][] boardCells;
int width;
int height;
public GameBoard()
{
boardCells = new Cell[BOARD_WIDTH][BOARD_HEIGHT];
width = BOARD_WIDTH;
height = BOARD_HEIGHT;
}
public void initGameBoard()
{
for (int i = 0; i < height; ++i)
{
for (int j = 0; j < width; ++j)
{
boardCells[j][i] = new Cell(CellState.EMPTY);
}
}
boardCells[0][0].setCellState(CellState.PLAYER);
boardCells[2][4].setCellState(CellState.MONSTER);
boardCells[2][6].setCellState(CellState.MONSTER);
boardCells[7][8].setCellState(CellState.POISON);
boardCells[5][0].setCellState(CellState.BLOCKED);
boardCells[5][1].setCellState(CellState.BLOCKED);
boardCells[5][2].setCellState(CellState.BLOCKED);
boardCells[5][3].setCellState(CellState.BLOCKED);
}
public String displayBoard()
{
String output = "";
output +="| |";
for (int i = 0; i < width; ++i)
{
output +=i + "|";
}
output +="\n";
for (int j = 0; j < height; ++j)
{
output +="|" + j + "|";
for (int k = 0; k < width; ++k)
{
output +=boardCells[k][j].displayCellState() + "|";
}
output +="\n";
}
return output;
}
}
答案 0 :(得分:1)
enums are classes too。因此,当CellState枚举表示您的状态时,最好将给定状态的所有相关信息直接编码到CellState类中。那将包括角色和图像。
import javafx.scene.image.Image;
public enum CellState {
EMPTY(' ', "empty.png"),
PLAYER('@', "player.png"),
MONSTER('&', "monster.png"),
POISON('*', "poison.png"),
BLOCKED('#', "blocked.png");
private final char cellChar;
private final Image cellImage;
CellState(char cellChar, String imageLoc) {
this.cellChar = cellChar;
this.image = new Image(imageLoc);
}
public char getChar() {
return cellChar;
}
public Image getImage() {
return cellImage;
}
@Override
public String toString() {
return Character.toString(cellChar);
}
}
然后您像以前一样保留您的单元格API,但是您可以放弃getCellStateCharacter()
方法并将其用法替换为cell.getCellState().getChar()
,对于图像类似,它将是cell.getCellState().getImage()
。
要了解Image构造函数从何处获取图像,请参阅:
如果您想从类路径中获取图像(例如,当图像打包在jar中时),您可以使用:
new Image(getClass().getResourceAsStream("player.png"))
以上内容将从CellState.class文件所在的类路径中的同一文件夹中获取图像。
答案 1 :(得分:0)
我猜你可以使用字节数组进行图像返回,然后在屏幕上显示