1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- public class PlayField {
- private int width;
- private int height;
- private final char[][] fields;
- public PlayField(int width, int height) {
- this.width = width;
- this.height = height;
- fields = new char[width][height];
- reset();
- }
- public final void setPos(int x, int y, Player player) {
- fields[x][y] = player.getToken();
- }
- public int getWidth() {
- return width;
- }
- public int getHeight() {
- return height;
- }
- public void print() {
- for(int i = 1; i <= width; i++) {
- System.out.print("[" + i + "]");
- }
- System.out.println();
- for(int y = 0; y < height; y++) {
- for(int x = 0; x < width; x++) {
- System.out.print("[" + fields[x][y] + "]");
- }
- System.out.println();
- }
- }
- public void reset() {
- for(int x = 0; x < width; x++) {
- for(int y = 0; y < height; y++) {
- fields[x][y] = ' ';
- }
- }
- }
- public int getFreeY(int x) {
- for(int y = height - 1; y >= 0; y--) {
- if(fields[x][y] == ' ') {
- return y;
- }
- }
- return -1;
- }
- public boolean isDraw() {
- for(int x = 0; x < width; x++) {
- if(getFreeY(x) != 1) {
- return false;
- }
- }
- return true;
- }
- public boolean hasWon(Player player, int y, int x) {
- for(int dir_x = -1; dir_x <= 1; dir_x++) {
- for(int dir_y = -1; dir_y <= 1; dir_y++) {
- if(dir_x == 0 && dir_y == 0) {
- continue;
- }
- if(checkDirection(player, y, x, dir_y, dir_x)) {
- return true;
- }
- }
- }
- return false;
- }
- private boolean checkDirection(Player player, int x, int y, int dir_x, int dir_y) {
- char t = player.getToken();
- for(int i = 1; i < 4; i++) {
- int new_x = x + i * dir_y;
- int new_y = y + i * dir_x;
- if(new_x < 0 || new_x >= width || new_y < 0 || new_y >= height
- || fields[new_x][new_y] != t) {
- return false;
- }
- }
- return true;
- }
- }
|