2016-10-18 3 views
1

현재 "Game of Life"버전을 만드는 과제를 수행 중입니다. 그러나 내 세포는 나타나지 않을 것입니다.Game of Life - 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

아무것도 나타나지 않습니다 또한 주요 프로그램이 클릭 됐어요 여부를 결정하기 위해의 MouseListener에서 사용할 수있는 public boolean contains(Point p) 방법이있다? –

+0

컴파일되지 않습니다 :'super.paintComponent (g)' – AJNeufeld

+0

당신은'SwingUtilities.invokeLater (Runnable)'로 이벤트 디스패치 스레드를 시작하지 않았습니다. –

답변

5

왜 그려야하는지 알 수 없습니다. 예, paintComponent 메소드를 가지고있는 Cell 클래스가 있습니다 만,이 메소드는 Swing 컴포넌트의 일부가 아니기 때문에 무의미합니다. 그리기를 수행해야하는 JPanel은 아무 작업도 수행하지 않습니다. Cell 클래스의 다른 문제도 있습니다. 단 하나의 셀이 아니라 전체 그리드를 그리는 것처럼 보입니다.

  • 그것을 그 자체를 그릴 수있는 public void draw(Graphics g) 방법을 제공
  • 대신 셀의 paintComponent에 방법 제거하십시오.
  • 셀 격자를 보유하는 JPanel을 만듭니다.
  • 이 JPanel은 paintComponent 재정의로 도면을 처리하게하십시오. for 루프 내에서 보유하는 모든 셀에 대해 draw(g) 메서드를 호출합니다.
  • 항상 오버라이드 된 메소드 위에 @Override 주석을 추가하십시오. 이 작업을 paintComponent보다 위에 수행했다면 컴파일러는 잘못된 것을 경고했을 것입니다. 예를 들어

: 여기에 생명의 게임을하지 않는 작은 프로그램입니다,하지만 JPanel에 들고, 비 구성 요소 세포의 격자를 표시하는 예를 보여줍니다. "비 구성 요소"는 SimpleCell 클래스가 Swing 구성 요소에서 확장되지 않으며 Swing 메서드가 없지만 위에 제안 된대로 draw(...) 메서드를 가지고 있으며이 메서드를 사용하여 자체를 그릴 수 있습니다.

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 
       + "]"; 
    } 

} 
관련 문제