📄 grid.java
字号:
import java.awt.*;import java.awt.event.*;/** * Creates a representation of the board for the games and keeps track * of the neighbouring fields and if any token occupy them, it tells * the field View and Field Controller where the tokens are on the * board, so they can depict it */class Grid{ GridCell _border; GridCell _cell[][]; private int _width; private int _height; /** * Constructor that sets a tokens neighbours and sets up the empty board * representation */ public Grid(int width, int height, GridCellFactory factory) { _width = width; _height = height; createGridCells(factory); setNeighbours(); clear(); } /** * This creates the board representation with the correct number of fields * for the game and starts a new field view and a field controller */ public void createGridCells(GridCellFactory factory) { _cell = new GridCell[_width][_height]; for(int v = 0; v < _height; v++) for(int h = 0; h < _width; h++) _cell[h][v] = factory.create(); _border = factory.create(); _border.setBorder(); } public GridCell getCell(int h, int v) { if (0 <= h && h <= _width && 0 <= v && v <= _height) return _cell[h][v]; else return null; } /** * Finds the neighbouring fields of a field */ public void setNeighbours() { for(int h = 0; h < _width; h++) for(int v = 0; v < _height; v++) for(int d = 0; d < 8; d++) _cell[h][v].setNeighbour(d, getNeighbour(h,v,d)); } /** * Gets the neighbouring field in a particular direction taken in as the last * parameter. The two first parameters are the position of the field in the * array that symolizes the board */ public GridCell getNeighbour(int h, int v, int direction) { if(direction == Direction.NORTH) v--; else if(direction == Direction.SOUTH) v++; else if(direction == Direction.NORTHWEST) {v--; h--; } else if(direction == Direction.SOUTHEAST) {v++; h++; } else if(direction == Direction.NORTHEAST) {v--; h++; } else if(direction == Direction.SOUTHWEST) {v++; h--; } else if(direction == Direction.WEST) h--; else if(direction == Direction.EAST) h++; else System.out.println("getNeighbour: wrong direction\n"); if(h < 0 || h >= _width || v < 0 || v >= _height) return _border; else return _cell[h][v]; } /** * Clears all the fields */ public void clear() { for(int v = 0; v < _height; v++) for(int h = 0; h < _width; h++) _cell[h][v].clear(); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -