Возможно, вы захотите изменить свой код, сохранив местоположение игрока только в классе Player
, что затруднит жизнь. Я также предложил бы добавить флаг в класс Cell
, указав, находится ли игрок внутри, например.
class Cell {
public int index;
private Player playerInCell;
public Cell(int index) {
this.index = index;
}
public void setPlayerInCell(Player p){
this.playerInCell = p;
}
public void clearPlayerInCell(){
this.playerInCell = null;
}
public Player getPlayerInCell(){
return this.playerInCell;
}
}
Затем при перемещении игрока в Cell
вы можете очистить их от предыдущего Cell
и установить их в новой и в вашей Paint()
функции, если игрок присутствует, цвет ячейки в.
Другое дело, если вы хотите придерживаться своего метода, ваша проблема вызвана тем, что вы меняете только свойство index
на класс Cell
, вы также должны либо изменить позицию Cell
в массиве cells[]
, либо просто изменить currentCell
Недвижимость Player
, в противном случае ваш игрок всегда остается в одном месте. Вот пример изменения Player
«s currentCell
свойства:
public void move() {
Cell currentCell = player.currentCell;
Cell nextCell = null;
for (int i = 0; i < cells.length; i++) {
if (cells[i] == currentCell && i+1 < cells.length){
nextCell = cells[i+1];
break;
}
}
if (nextCell != null)
player.currentCell = nextCell;
else{
//Error handling, next cell not found
}
board.paint();
}
[Редактировать]
Я сделал некоторые основные код очистки, некоторые из способов, вы делали то, было немного странно, я надеюсь, вы не возражаете, вот классы, которые изменили:
Главная
public class Main extends Application {
private Cell cells[] = new Cell[5];
private Player player;
private Board board;
Button move = new Button("move");
public Main() throws Exception{
for (int i = 0; i < cells.length; i++) {
cells[i] = new Cell(i);
}
this.player = new Player(cells[0]);
this.board = new Board(player, cells);
}
@Override
public void start(Stage primaryStage) throws Exception{
BorderPane pane = new BorderPane();
pane.setCenter(board);
pane.setBottom(move);
Scene scene = new Scene(pane,400,80);
primaryStage.setTitle("Move");
primaryStage.setScene(scene);
primaryStage.show();
move.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
move();
}
});
}
public void move() {
//Get current players cell, we want to move them one right
Cell currentCell = player.getCurrentCell();
Cell nextCell = null;
//Searching for current cell in board, if found we need to clear the player from it and select the next cell
for (int i = 0; i < cells.length; i++) {
if (cells[i] == currentCell && i+1 < cells.length){
cells[i].clearPlayerInCell();
nextCell = cells[i+1];
break;
}
}
//We found it, let's move the player
if (nextCell != null) {
player.setCurrentCell(nextCell);
nextCell.setPlayerInCell(player);
}
//We didn't find it, or our index was out of range, what do we do now?
else{
//Error handling, next cell not found
//Example, let's put them back at the start
player.setCurrentCell(cells[0]);
cells[0].setPlayerInCell(player);
cells[cells.length-1].clearPlayerInCell();
}
board.paint();
}
public static void main(String[] args) {
launch(args);
}
}
Совет
public class Board extends Pane {
private Player player;
private Cell cells[];
private final int CELLWIDTH = 40;
private final int CELLHEIGHT = 40;
private final int LMARGIN = 100;
public Board(Player p, Cell cells[]) {
player = p;
this.cells = cells;
paint();
}
public Cell[] getCells(){
return this.cells;
}
public Player getPlayer() {
return player;
}
public void paint() {
//Clear previous cells, we don't need them now
getChildren().clear();
//Redraw them
for(Cell cell : cells){
Rectangle r1 = new Rectangle(xCor(cell.getIndex()), 0, CELLWIDTH, CELLHEIGHT);
r1.setStroke(Color.BLACK);
//We've found a player in the cell, let's colour it black
if (cell.getPlayerInCell() != null)
r1.setFill(Color.BLACK);
//No, player in this cell, white it is
else
r1.setFill(Color.WHITE);
getChildren().add(r1);
}
}
private int xCor(int col) {
return LMARGIN + col * CELLWIDTH;
}
}
Игрок
public class Player {
private Cell currentCell;
public Player(Cell cell) throws Exception {
this.currentCell = cell;
cell.setPlayerInCell(this);
}
public Cell getCurrentCell(){
return this.currentCell;
}
public void setCurrentCell(Cell cell){
this.currentCell = cell;
}
}
Cell
public class Cell {
private int index;
private Player playerInCell;
public Cell(int index) {
this.index = index;
}
public void setPlayerInCell(Player p){
this.playerInCell = p;
}
public void clearPlayerInCell(){
this.playerInCell = null;
}
public Player getPlayerInCell(){
return this.playerInCell;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
То, что сейчас работает и я могу переместить ячейку вместе, я также установить его так, чтобы ячейка возвращается к началу, если игрок достигает конца, но это пример ле. Он работает с использованием свойства Cell
playerInCell
, если это не null, то мы знаем, что игрок находится в ячейке и может покрасить его в черный цвет. Если он равен нулю, в ячейке нет игрока, и мы можем покрасить его в белый цвет. Это также позволяет вам в будущем, возможно, иметь больше игроков с разными цветами. Хотя я не знаю, какова ваша конечная цель. Надеюсь, что это помогает, и если вы хотите какой-либо дальнейших объяснений, не стесняйтесь спросить
Кроме того, для дальнейшего чтения, см here, почему лучше использовать поглотитель и сеттеры, как я
Кроме того, рассуждение позади этого бита код:
move.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
move();
}
});
Это потому, что я использую Java 1.7 вместо Java 1.8 и не может использовать предикаты, вы должны быть безопасными, чтобы изменить что move.setOnAction(e -> this.move());
вместо этого.
Вы проверили код, который я разместил, это решило вашу проблему? – Draken
Почему вы создаете второй экземпляр 'Main'? Shcould будет 'move.setOnAction (e -> this.move());' Также вы добавляете все больше и больше 'Rectangle' в 'Board', но не удаляете их. Это специально? – fabian
Обновлен ответ и заставил его работать на моем, надеюсь, что он поможет – Draken