2016-10-18 42 views
1

目前我正在做一個關於創建「遊戲人生」版本的任務。但是我的細胞不會出現。生活的遊戲 - Java,不起作用(不顯示單元格)

這是我的手機類:

class Cell{ 
boolean alive; //true if cell is alive, false if cell is dead 
int numNeighbors; //number of alive neightboring cells 

//change alive/dead state of the cell 
void setAlive(boolean state){ 
    alive = state; 
} 

//return alive/dead state of the cell 
boolean isAlive(){ 
    return alive; 
} 

//set numNeightbors of the cell to n 
void setNumNeighbors(int n){ 
    numNeighbors = n; 
} 

//take the cell to the next generation 
void update(){ 
    if(numNeighbors <2 || numNeighbors >3){ 
     alive = false; 
    } else if((numNeighbors == 2 || numNeighbors == 3) && alive == true){ 
     alive = true; 
    } else if(numNeighbors == 3 && alive == false){ 
     alive = true; 
    } 
} 
public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    g.setColor(Color.blue); 
    g.setOpaque(true); 
    for(int i = 0; i < row; i++){ 
     for(int j = 0; j < col; j++){ 
      if(grid[i][j].isAlive()){ 
       g.setColor(Color.BLACK); 
      } else { 
       g.setColor (Color.WHITE); 
       g.fillRect(50, 50, 50*i, 50*j); 
      } 
     } 
    } 
} 

這是我GameOfLife類

<pre>import java.awt.*; 
import java.awt.event.*; 
import java.util.*; 
import javax.swing.*; 
import java.io.*; 


public class GameOfLife implements MouseListener{ 
Cell[][] grid; //contain grid of cells 
String birthFilename = "birth.txt"; //text file where initial generation is stored 
int row; //number of rows 
int col; //number of columns 


ActionListener actionListener = new ActionListener(){ 
    javax.swing.Timer timer = new javax.swing.Timer(500, this); //new timer 

    @Override 
    public void actionPerformed(ActionEvent event){ 
    } 
}; 

public void buildIt() { 
    int width = 600; 
    int height = 600; 
    JFrame frame = new JFrame("Game of Life"); 
    readInitial(); 

    //adds button interface 
    JPanel buttonbar = new JPanel(); 
    frame.add(buttonbar, BorderLayout.SOUTH); 
    JButton start = new JButton("Start"); 
    JButton stop = new JButton("Stop"); 
    JButton nextg = new JButton("Next Generation"); 
    buttonbar.add(nextg); 
    buttonbar.add(start); 
    buttonbar.add(stop); 

    JPanel panel = new JPanel(); 
    frame.add(panel); 
    panel.setPreferredSize(new Dimension(width, height)); 
    panel.setLayout(new GridLayout(row, col, 4, 4)); 
    frame.pack(); 
    frame.setBackground(Color.WHITE); 
    frame.setVisible(true); 


} 

public void mousePressed(MouseEvent e) { 
//add code to update x and y 
} 
public void mouseReleased(MouseEvent e) { } 
public void mouseClicked(MouseEvent e) { } 
public void mouseEntered(MouseEvent e) { } 
public void mouseExited(MouseEvent e) { } 


//calculate number of living neightbors of each cell and sets numNeighbors 
//Does not update dead/live state of cells 
void calculateNumNeighbors(){ 
    int numNeighbors = 0; 
    for(int i = 1; i < row + 1; i++){ 
     for(int j = 1; j < col + 1; j++){ 
      for(int k = -1; k < 2; k++){ 
       for(int m = -1; m < 2; m++){ 
        if(grid[i+k][j+m].isAlive() && !(k == 0 && m == 0)){ 
         numNeighbors++; 
        } 
       } 
      } 
      grid[i][j].setNumNeighbors(numNeighbors); 
     } 
    } 
} 

//create grid and read initial generation from file 
void readInitial(){ 
    try{ 
     grid = new Cell[row + 2][col + 2]; //empty neighbors at corners, so + 2 
     File file = new File(birthFilename); 
     Scanner scanner = new Scanner(file); 
     row = scanner.nextInt(); 
     col = scanner.nextInt(); 

     for(int i = 0; i < row + 2; i++){ 
      for (int j = 0; j < col + 2; j++){ 
       grid[i][j] = new Cell(); 
      } 
     } 

     for(int i = 1; i < row + 1; i++){ 
      for (int j = 1; j < col + 1; j++){ 
       if(scanner.next().equals(".")){ 
        grid[i][j].setAlive(false); 
       } else if(scanner.next().equals("*")){ 
        grid[i][j].setAlive(true); 
       } 
      } 
     } 

     for(int i = 0; i < row + 2; i++){ 
      grid[0][i].setAlive(false); 
      grid[row+2][i].setAlive(false); 
     } 
     for(int j = 0; j < col + 2; j++){ 
      grid[j][0].setAlive(false); 
      grid[j][col+2].setAlive(false); 
     } 

    } catch(FileNotFoundException e) { 
     grid = new Cell[12][12]; 
     row = 10; 
     col = 10; 
     for(int i = 0; i < 12; i++){ 
      for (int j = 0; j < 12; j++){ 
       grid[i][j] = new Cell(); 
       grid[i][j].setAlive(false); 
      } 
     } 
    } 
} 



//update grid to the next generation, using the values of numNeightbors in the cells 
void nextGeneration(){ 
    for(int i = 1; i < row + 1; i++){ 
     for (int j = 1; j < col + 1; j++){ 
      grid[i][j].update(); 
     } 
    } 
} 


public static void main(String[] arg) { 
    (new GameOfLife()).buildIt();  
} 

我希望有人能幫助我出去,使本工作方案。

+0

中會出現什麼? –

+0

不編譯:'super.paintComponent(g)' – AJNeufeld

+0

你從來沒有用'SwingUtilities.invokeLater(Runnable)啓動事件調度線程' –

回答

5

我不明白爲什麼要繪製。你有一個Cell類,它有一個paintComponent方法,但是這個方法沒有意義,因爲它不是Swing組件的一部分。你的JPanel,你應該畫圖的地方 - 什麼也不做。您還有其他Cell類的問題,因爲它似乎試圖繪製整個網格而不是單個單元格。

  • 擺脫細胞的方法的paintComponent的
  • 而是給它一個public void draw(Graphics g)方法,允許其自行繪製。
  • 創建一個包含單元網格的JPanel
  • 讓此JPanel在其paintComponent重寫中執行繪圖。它會調用它在for循環中保存的所有Cell的draw(g)方法。
  • 總是@Override註釋放在任何重寫的方法之上。如果你已經完成了這個工作,在你的paintComponent之上,編譯器會警告你有什麼錯誤。

例如:這裏有一個小程序,沒有做生活的遊戲,但顯示的一個JPanel保持和展示非組件單元網格的例子。通過「非組件」,SimpleCell類不會從Swing組件擴展,也不具有任何Swing方法,但是如上所述,確實有一個draw(...)方法,並且可以使用它來繪製它自己。它也有一個public boolean contains(Point p)方法主程序可以在它的MouseListener用它來決定,如果一直點擊它:

import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 
import javax.swing.*; 

@SuppressWarnings("serial") 
public class SimpleCellGrid extends JPanel { 
    private static final int ROWS = 40; 
    private static final int COLS = 40; 
    private static final int CELL_WIDTH = 10; 
    private static final int PREF_W = CELL_WIDTH * COLS; 
    private static final int PREF_H = CELL_WIDTH * ROWS; 
    private SimpleCell[][] cellGrid = new SimpleCell[ROWS][COLS]; 

    public SimpleCellGrid() { 
     MyMouse myMouse = new MyMouse(); 
     addMouseListener(myMouse); 
     for (int row = 0; row < cellGrid.length; row++) { 
      for (int col = 0; col < cellGrid[row].length; col++) { 
       int x = col * CELL_WIDTH; 
       int y = row * CELL_WIDTH; 
       cellGrid[row][col] = new SimpleCell(x, y, CELL_WIDTH); 
      } 
     } 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     Graphics2D g2 = (Graphics2D) g; 
     for (SimpleCell[] cellRow : cellGrid) { 
      for (SimpleCell simpleCell : cellRow) { 
       simpleCell.draw(g2); 
      } 
     } 
    } 

    @Override 
    public Dimension getPreferredSize() { 
     if (isPreferredSizeSet()) { 
      return super.getPreferredSize(); 
     } 
     return new Dimension(PREF_W, PREF_H); 
    } 

    private class MyMouse extends MouseAdapter { 
     @Override 
     public void mousePressed(MouseEvent e) { 
      for (SimpleCell[] cellRow : cellGrid) { 
       for (SimpleCell simpleCell : cellRow) { 
        if (simpleCell.contains(e.getPoint())) { 
         simpleCell.setAlive(!simpleCell.isAlive()); 
        } 
       } 
      } 
      repaint(); 
     } 
    } 

    private static void createAndShowGui() { 
     JFrame frame = new JFrame("SimpleCellGrid"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().add(new SimpleCellGrid()); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(() -> createAndShowGui()); 
    } 
} 

import java.awt.Color; 
import java.awt.Graphics2D; 
import java.awt.Point; 
import java.awt.Rectangle; 

public class SimpleCell { 
    private static final Color CELL_COLOR = Color.RED; 
    private boolean alive = false; 
    private int x; 
    private int y; 
    private int width; 
    private Rectangle rectangle; 

    public SimpleCell(int x, int y, int width) { 
     this.x = x; 
     this.y = y; 
     this.width = width; 
     rectangle = new Rectangle(x, y, width, width); 
    } 

    public boolean isAlive() { 
     return alive; 
    } 

    public void setAlive(boolean alive) { 
     this.alive = alive; 
    } 

    public void draw(Graphics2D g2) { 
     if (alive) { 
      g2.setColor(CELL_COLOR); 
      g2.fill(rectangle); 
     } 
    } 

    public boolean contains(Point p) { 
     return rectangle.contains(p); 
    } 

    @Override 
    public String toString() { 
     return "SimpleCell [alive=" + alive + ", x=" + x + ", y=" + y + ", width=" + width + ", rectangle=" + rectangle 
       + "]"; 
    } 

}