import java.util.Scanner;
public class Qipan {
static char[][] chessBoard = new char[16][16];
//當isBlack爲true時,黑方下子
//O表示黑方,#表示白方
static boolean isBlack =true;
public static void main(String[] args){
start();
print();
Scanner c = new Scanner(System.in);
while(true){
if(isBlack){
System.out.println("請黑方下子");
}else{
System.out.println("請白方下子");
}
//獲取輸入的橫縱座標
int i = c.nextInt();
int j = c.nextInt();
if(chessBoard[i][j] !='*'){
System.out.println("該位置已經有棋子,請重新輸入");
}else{
if(isBlack){
chessBoard[i][j] = 'O';
//判斷輸贏的方法
if(isWin(i,j)){
System.out.println("黑方勝利!");
break;
}
}else{
chessBoard[i][j] = '#';
if(isWin(i,j)){
System.out.println("白方勝利!");
break;
}
}
isBlack = !isBlack;
print();
}
}
}
public static void start(){
for(int i=0;i<chessBoard.length;i++){
for(int j=0;j<chessBoard[i].length;j++){
chessBoard[i][j]='*';
}
}
}
public static void print(){
char[] c = {'0','1','2','3','4','5','6','7','8','9'};
System.out.print(" ");
for(int i=0;i<c.length;i++){
System.out.print(c[i]);
}
System.out.println();
for(int i =0;i<10;i++){
System.out.print(c[i]);
for(int j =0;j<10;j++){
System.out.print(chessBoard[i][j]);
}
//換行
System.out.println();
}
}
//判斷輸贏的總方法
public static boolean isWin(int i,int j){
return isLeftAndRught(i,j) ||
isUpAndDown(i,j) ||
isLeftUpAndRightDown(i,j)||
isRightUpAndLeftDown(i,j);
}
//判斷左右方向的輸贏
public static boolean isLeftAndRught(int i ,int j){
int j1 = j-1;
while(true){
if(j1<0||chessBoard[i][j1] != chessBoard[i][j]){
break;
}else{
j1--;
}
}
j1++;
int count = 0;
while(true){
if(j1>=16||chessBoard[i][j1] != chessBoard[i][j]){
break;
}else{
count++;
j1++;
}
}
return count >= 5;
}
//判斷上下方向
public static boolean isUpAndDown(int i,int j){
int i1 = i-1;
while(true){
if(i1<0||chessBoard[i1][j] != chessBoard[i][j]){
break;
}else{
i1--;
}
}
i1++;
int count = 0;
while(true){
if(i1>=16||chessBoard[i1][j] != chessBoard[i][j]){
break;
}else{
count++;
i1++;
}
}
return count >= 5;
}
//判斷左上右下
public static boolean isLeftUpAndRightDown(int i,int j){
int j1 = j-1;
int i1 = i-1;
while(true){
if(j1<0||i1<0||chessBoard[i1][j1] != chessBoard[i][j]){
break;
}else{
j1--;
i1--;
}
}
j1++;
i1++;
int count = 0;
while(true){
if(j1>=16||i1>=16||chessBoard[i1][j1] != chessBoard[i][j]){
break;
}else{
count++;
j1++;
i1++;
}
}
return count >= 5;
}
//判斷右上左下
public static boolean isRightUpAndLeftDown(int i,int j){
int j1 = j-1;
int i1 = i+1;
while(true){
if(j1<0||i1>=16||chessBoard[i1][j1] != chessBoard[i][j]){
break;
}else{
j1--;
i1++;
}
}
j1++;
i1--;
int count = 0;
while(true){
if(j1>=16||i1<0||chessBoard[i1][j1] != chessBoard[i][j]){
break;
}else{
count++;
j1++;
i1--;
}
}
return count >= 5;
}
}
打印結果:
0123456789
0**********
1**********
2**********
3**********
4**********
5**********
6**********
7**********
8**********
9**********
請黑方下子