import java.util.Scanner;
public class FiveChess {
char[][] chess = new char[16][16];
boolean isBlack = true;
public FiveChess() {
for (int i = 0; i < chess.length; i++) {
for (int j = 0; j < chess[i].length; j++) {
chess[i][j] = '*';
}
}
Scanner s = new Scanner(System.in);
printChess();
while (true) {
System.out.println("请" + (isBlack ? "黑" : "白") + "方落子:");
String str = s.next();
int r = fromCharToInt(str.charAt(0));
int c = fromCharToInt(str.charAt(1));
if (chess[r][c] != '*') {
System.out.println("该位置已经有棋子,请重新输入!");
continue;
} else {
chess[r][c] = isBlack ? '@' : 'O';
printChess();
if (wasWin(r, c)) {
System.out.println((isBlack ? "黑" : "白") + "方获胜!");
break;
}
}
isBlack = !isBlack;
}
}
private char alph(int i) {
return (char) ('a' + i - 10);
}
public void printChess() {
for (int i = 0; i < chess.length; i++) {
System.out.print(i < 10 ? " " + i : " " + alph(i));
}
System.out.println();
for (int i = 0; i < chess.length; i++) {
System.out.print(i < 10 ? i + " " : alph(i) + " ");
for (int j = 0; j < chess[i].length; j++) {
System.out.print(chess[i][j] + " ");
}
System.out.println();
}
}
public int fromCharToInt(char c) {
return c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10;
}
public boolean wasWin(int r, int c) {
return wasWinAtV(r, c) || wasWinAtH(r, c) || wasWinAtLD(r, c)
|| wasWinAtRD(r, c);
}
public boolean wasWinAtV(int r, int c) {
char ch = isBlack ? '@' : 'O';
int i = c;
while (i >= 0 && chess[r][i] == ch) {// 向左找到第一个不是ch的字符
i--;
}
int num = 0;
i++;
while (i < chess.length && chess[r][i] == ch) {
num++;
i++;
}
return num >= 5;
}
public boolean wasWinAtH(int r, int c) {
char ch = isBlack ? '@' : 'O';
int i = r;
while (i >= 0 && chess[i][c] == ch) {// 向左找到第一个不是ch的字符
i--;
}
int num = 0;
i++;
while (i < chess.length && chess[i][c] == ch) {
num++;
i++;
}
return num >= 5;
}
public boolean wasWinAtLD(int r, int c) {
char ch = isBlack ? '@' : 'O';
int i = r;
int j = c;
while (i >= 0 && j < chess.length && chess[i][j] == ch) {// 向左找到第一个不是ch的字符
i--;
j++;
}
int num = 0;
i++;
j--;
while (i < chess.length && j >= 0 && chess[i][j] == ch) {
num++;
i++;
j--;
}
return num >= 5;
}
public boolean wasWinAtRD(int r, int c) {
char ch = isBlack ? '@' : 'O';
int i = r;
int j = c;
while (i >= 0 && j >= 0 && chess[i][j] == ch) {// 向左找到第一个不是ch的字符
i--;
j--;
}
int num = 0;
i++;
j++;
while (i < chess.length && j < chess.length && chess[i][j] == ch) {
num++;
i++;
j++;
}
return num >= 5;
}
public static void main(String[] args) {
new FiveChess();
}
}
控制台的五子棋
最新推荐文章于 2022-01-20 23:52:00 发布