我是Java的新手,我有这个学校的任务来编写康威的生命游戏。我正在努力的任务是从文件中读取模式。到目前为止,我从我学校的教程中得到了这段代码:
@FXML
private void readFromFile(){
FileChooser fileChooser = new FileChooser();
File openFile = fileChooser.showOpenDialog(null);
if(openFile == null){
return;
}
try (BufferedReader reader = Files.newBufferedReader(openFile.toPath())){
String line;
while ((line = reader.readLine()) != null){
addMessage(line);
}
}catch (IOException ex){
showIOErrorAlert(ex);
}
}
@FXML
private void showIOErrorAlert(IOException ex){
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText("IOException, filen cannot be open: " + ex);
alert.show();
}
代码打开一个窗口,我可以从磁盘中选择一个文件(我已经下载了rle格式的所有模式,我希望打开它们的格式,因为这是分配要求)。但是当我选择一个文件时没有任何反应,没有错误,没有。这项工作需要做什么?我需要在这里编写解析器吗?阅读格式。我正在使用mvc模型和java fxml这是我的Cell类:
public class Cell extends Rectangle{
public static final int CELL_SIZE = 5;
private boolean alive;
public Cell(){
super(CELL_SIZE, CELL_SIZE);
setAlive(false);
}
public void setAlive(boolean bool){
alive = bool;
if (alive){
setFill(Color.WHITE);
} else {
setFill(Color.BLACK);
}
}
public boolean isAlive(){
return alive;
}
}
Board class:
public class Board {
public static final int COLUMNS = 90;
public static final int ROWS = 210;
private Cell[][] generation;
public Board(){
generation = new Cell[COLUMNS][ROWS];
for(int x = 0; x < COLUMNS; x++){
for(int y = 0; y < ROWS; y++){
generation[x][y] = new Cell();
}
}
}
public Cell[][] getBoard(){
return generation;
}
public void fill(){
Random rand = new Random();
for(int x = 0; x < COLUMNS; x++){
for(int y = 0; y < ROWS; y++){
generation[x][y].setAlive(rand.nextBoolean());
}
}
}
public void reset(){
for(int x = 0; x < COLUMNS; x++){
for(int y = 0; y < ROWS; y++){
generation[x][y].setAlive(false);
}
}
}
public int countNeighbors(int x, int y){
int neighbors = 0;
//iteration starts with -1 in order to 'wrap' the grid around
for (int a = -1; a < 2; a++){
for (int b = -1; b < 2; b++){
int nx = x + a;
int ny = y + b;
if (nx < 0){
nx = COLUMNS - 1;
}
if (ny < 0){
ny = ROWS - 1;
}
if (nx > COLUMNS - 1){
nx = 0;
}
if (ny > ROWS - 1){
ny = 0;
}
if(generation[nx][ny].isAlive()){
neighbors += 1;
}
}
}
if(generation[x][y].isAlive())
neighbors--;
return neighbors;
}
public void renew(){
Cell[][] nextGeneration = new Cell[COLUMNS][ROWS];
for(int x = 0; x < COLUMNS; x++){
for(int y = 0; y < ROWS; y++){
nextGeneration[x][y] = new Cell();
nextGeneration[x][y].setAlive(generation[x][y].isAlive());
}
}
int neighborsCount = 0;
for(int x = 0; x < COLUMNS; x++){
for(int y = 0; y < ROWS; y++){
neighborsCount = countNeighbors(x, y);
if(generation[x][y].isAlive()){
if(neighborsCount < 2 || neighborsCount > 3)
nextGeneration[x][y].setAlive(false);
}
else{
if(neighborsCount == 3)
nextGeneration[x][y].setAlive(true);
}
}
}
for(int x = 0; x < COLUMNS; x++){
for(int y = 0; y < ROWS; y++){
generation[x][y].setAlive(nextGeneration[x][y].isAlive());
}
}
}
如何编写一个读取rle格式文件的方法并在我的电路板上添加一个模式?