Jestem w trakcie pisania gry Snake. Utworzyłem sobie w klasie GameBoard tablice dwuwymiarową typu enum: CellData, która przechowywuje dane co się znajduje na danej pozycji(wąż, jabłko, ściana, pusta). Problem z tym że nie mogę sobie poradzić z wyświetleniem tego w oknie.
Plansza ma być czarna, a wąż,jabłko i ściany białe. Skrawek kodu, który podałem jest błędny i tu jest moje pytanie. Jak go poprawić, żeby działał prawidłowo.
public class GameBoard {
private int boardWidth = 990;
private int boardHeight = 690;
private int xCells = boardWidth / 10 + 2;
private int yCells = boardHeight / 10 + 2;
private CellData board[][];
public GameBoard() {
board = new CellData[xCells][yCells];
for (int i = 0; i < xCells; i++) {
board[i][0] = CellData.WALL;
}
for (int i = 0; i < xCells; i++) {
board[i][yCells-1] = CellData.WALL;
}
for (int j = 0; j < yCells; j++) {
board[0][j] = CellData.WALL;
}
for (int j = 0; j < yCells; j++) {
board[xCells-1][j] = CellData.WALL;
}
}
public void cleanBoard() {
for (int i = 1; i < xCells-1; i++) {
for (int j = 1; j < yCells-1; j++) {
board[i][j] = CellData.EMPTY;
}
}
}
.............
}
public class GameInstant extends JFrame {
private JPanel scorePanel;
public JLabel scoreLabel;
private CellData[][] board;
private int score = 0;
SnakeGame snakeRules = new SnakeGame();
GameBoard gameBoard = new GameBoard();
public GameInstant() {
addKeyListener(new KeyListener() {
............});
DrawingTheBoard gamePanel = new DrawingTheBoard(board);
this.add(gamePanel, BorderLayout.CENTER);
scorePanel = new JPanel();
scoreLabel = new JLabel();
scoreLabel.setText("Score: " + Integer.toString(score));
scoreLabel.setFont(new Font("Serif", Font.PLAIN, 40));
scorePanel.add(scoreLabel, BorderLayout.CENTER);
this.add(scorePanel, BorderLayout.PAGE_END);
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(5);
executor.scheduleAtFixedRate(new RepaintTheBoard(this), 0, snakeRules.getGameSpeed(), TimeUnit.MILLISECONDS);
this.setVisible(true);
}
}
class DrawingTheBoard extends JComponent {
CellData[][] board;
GameBoard gameBoard = new GameBoard();
SnakeGame sGame = new SnakeGame();
public DrawingTheBoard(CellData[][] board) {
this.board = board;
this.setSize(1000, 800);
}
public void paint(Graphics g) {
Graphics2D g2D = (Graphics2D) g;
g2D.setBackground(Color.BLACK);
g2D.fillRect(0, 0, gameBoard.getxCells() * 10, gameBoard.getyCells() * 10);
g2D.setPaint(Color.WHITE);
sGame.update();
for (int i = 0; i < gameBoard.getxCells(); i++) {
for (int j = 0; j < gameBoard.getyCells(); j++) {
if (board[i][j] == CellData.WALL || board[i][j] == CellData.SNAKE || board[i][j] == CellData.APPLE)
g2D.fillRect(i*10,j*10,10,10);
}
}
}
}