package com.hotusm.datastructure.list;
import com.hotusm.datastructure.Log;/**
* @author luqibao
* @date 2017/3/17*/
public classChess {public static final int WHITE = 1; //白棋
public static final int BLACK = 2; //黑棋
private int[][] chessboard;private intxSize;private intySize;public Chess(intsize) {
chessboard= new int[size][size];
xSize=size;
ySize=size;
}publicChess() {
chessboard= new int[16][16];
xSize= 16;
ySize= 16;
}public void play(int x, int y, intwho) {if (x > xSize || y >ySize) {
Log.warn("超出范围!");return;
}if (chessboard[x][y] != 0) {
Log.warn("该位置不能下");return;
}
chessboard[x][y]=who;if(isSuccess()) {
Log.info("who:" + who + "已经获胜");
}
}publicboolean isSuccess() {//x轴
for (int i = 0; i < ySize; i++) {for (int j = 0; j < xSize; j++) {if (xSize - j < 5) {break;
}if (arriSSame(chessboard[i], j, j + 5)) {return true;
}
}
}//y轴
for (int i = 0; i < xSize; i++) {for (int j = 0; j < ySize; j++) {if (ySize - j < 5) {break;
}if (arriSSame(copyY2X(chessboard, i), j, j + 5)) {return true;
}
}
}//交叉
if(isCrossSame()) {return true;
}return false;
}/**
* 将数组的Y列数据拷贝到一维数组中去
*
* @param arr
* @param y
* @return*/
private int[] copyY2X(int[][] arr, inty) {int[] nArr = new int[ySize];for (int i = 0; i < ySize; i++) {
nArr[i]=arr[i][y];
}returnnArr;
}/**
* 是否有5个相同
*
* @param arr
* @param x1
* @param x2
* @return*/
private boolean arriSSame(int[] arr, int x1, intx2) {int sameNum = 1;for (int i = x1; i < x2 - 1; i++) {if (arr[i] == arr[i + 1] && arr[i] != 0) {
sameNum++;if (sameNum == 5) {return true;
}
}else{
sameNum= 1;
}
}return false;
}/**
* 交叉情况下是否有5个相同
*
* @return*/
privateboolean isCrossSame() {if (cross(ySize, "Y")) {return true;
}if (cross(xSize, "X")) {return true;
}for (int x = 5; x < xSize; x++) {int sameNum = 1;for (int i = x - 1, j = 0; i > 0; i--, j++) {if (chessboard[j][i] == chessboard[j + 1][i - 1] && chessboard[j][i] != 0) {
sameNum++;if (sameNum == 5) {return true;
}
}else{
sameNum= 1;
}
}
}for (int y = ySize - 4; y > 0; y++) {int sameNum = 1;for (int i = y - 1, j = xSize - 1; i < ySize - 1; i++, j--) {if (chessboard[i][j] == chessboard[i + 1][j - 1] && chessboard[i][j] != 0) {
sameNum++;if (sameNum == 5) {return true;
}
}else{
sameNum= 1;
}
}
}return false;
}/**
* @param xSize
* @param flag X 或者Y 表示X轴或者是Y轴
* @return*/
private boolean cross(intxSize, String flag) {for (int y = xSize - 4; y > 0; y--) {int sameNum = 1;//y-1 为坐标
for (int i = y - 1, j = 0; i < xSize - 1; i++, j++) {if (flag.equals("X")) {if (chessboard[j][i] == chessboard[j + 1][i + 1] && chessboard[j][i] != 0) {
sameNum++;if (sameNum == 5) {return true;
}
}else{
sameNum= 1;
}
}else{if (chessboard[i][j] == chessboard[i + 1][j + 1] && chessboard[i][j] != 0) {
sameNum++;if (sameNum == 5) {return true;
}
}else{
sameNum= 1;
}
}
}
}return false;
}
}