Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- /**
- * @author kevin.liu
- */
- public class Reversi {
- private static int[] dx = new int[]{1, 1, 1, 0, 0, -1, -1, -1};
- private static int[] dy = new int[]{-1, 0, 1, 1, -1, -1, 0, 1};
- private int[][] board;
- private int currentPlayer;
- public Reversi() {
- this.board = new int[8][8];
- board[3][4] = 1;
- board[4][3] = 1;
- board[3][3] = 2;
- board[4][4] = 2;
- this.currentPlayer = 2;
- }
- public void printBoard() {
- int[][] copy = new int[8][8];
- for (int i = 0; i < copy.length; i++) {
- copy[i] = board[i].clone();
- for (int j = 0; j < copy[0].length; j++) {
- if (isValid(i, j, currentPlayer)) {
- copy[i][j] = 8;
- }
- }
- }
- for (int i = 0; i < copy.length; i++) {
- System.out.println(Arrays.toString(copy[i]));
- }
- }
- public boolean isValid(int r, int c, int player) {
- if (this.currentPlayer != player) {
- return false;
- }
- if (board[r][c] != 0) {
- return false;
- }
- // iterates over dx, dy
- for (int i = 0; i < 8; i++) {
- int x = r;
- int y = c;
- boolean foundOther = false;
- while (inBounds(x += dx[i], y += dy[i])) {
- if (board[x][y] == 0) {
- break;
- }
- if (board[x][y] == player) {
- if (foundOther) {
- return true;
- } else {
- break;
- }
- }
- if (board[x][y] == getOpponentOf(player)) {
- foundOther = true;
- }
- }
- }
- return false;
- }
- public void move(int r, int c, int player) {
- // iterates over dx, dy
- board[r][c] = player;
- for (int i = 0; i < 8; i++) {
- int x = r;
- int y = c;
- boolean foundSelf = false;
- while (inBounds(x += dx[i], y += dy[i])) {
- if (board[x][y] == 0) {
- break;
- }
- if (board[x][y] == player) {
- foundSelf = true;
- break;
- }
- }
- if (foundSelf) {
- x -= dx[i];
- y -= dy[i];
- while (x != r && y != c) {
- board[x][y] = player;
- x -= dx[i];
- y -= dy[i];
- }
- }
- }
- this.currentPlayer = getOpponentOf(player);
- }
- private int getOpponentOf(int player) {
- return player == 1 ? 2 : 1;
- }
- private boolean inBounds(int r, int c) {
- return (r >= 0 && c >= 0 && r < 8 && c < 8);
- }
- public static void main(String[] args) {
- Reversi game = new Reversi();
- // boolean isValid = game.isValid(3, 5, 2);
- // System.out.println(isValid);
- game.move(3, 5, 2);
- game.printBoard();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement