练习002 五子棋
自己练
package cat3;
import java.util.Scanner;
public class Demo08 {
public static void main(String[] args) {
int[][] chess = new int[10][10];
Scanner scanner = new Scanner(System.in);
int row = 0;
int col = 0;
boolean flag = false;
int player = 1;
boolean winner = false;
for (int i = 0; i < 100; i++) {
// 定位落子:
System.out.println("请输入一个0~99的正整数:");
if (scanner.hasNextInt()) {
int a = scanner.nextInt();
if (a < 0 || a >= 100) {
System.out.println("数据超出范围!");
i--;
flag = true;
} else {
col = a % 10;
row = (a - col) / 10;
}
} else {
System.out.println("输入的不是整数!");
break;
}
if (!flag) {
// 落子:
if (chess[row][col] != 0) {
System.out.println("无法重复落子!");
i--;
player = 3 - player;
} else {
chess[row][col] = player;
}
// 输出落子后结果:
for (int[] ints : chess) {
for (int anInt : ints) {
System.out.print(anInt + "\t");
}
System.out.println();
}
}
// 判断获胜条件:
for (int k = 0; k < 10; k++) {
for (int j = 0; j <= 5; j++) {
if(chess[k][j] == player
&& chess[k][j+1] == player
&& chess[k][j+2] == player
&& chess[k][j+3] == player
&& chess[k][j+4] == player){
System.out.println("player"+player+" win!");
winner = true;
}
if(chess[j][k] == player
&& chess[j+1][k] == player
&& chess[j+2][k] == player
&& chess[j+3][k] == player
&& chess[j+4][k] == player){
System.out.println("player"+player+" win!");
winner = true;
}
}
}
for (int n = 0; n < 6; n++) {
for (int m = 0; m < 6; m++) {
if(chess[n][m] == player
&& chess[n+1][m+1] == player
&& chess[n+2][m+2] == player
&& chess[n+3][m+3] == player
&& chess[n+4][m+4] == player){
System.out.println("player"+player+" win!");
winner = true;
}
}
}
if(winner){
break;
}
flag = false; // 重置。
player = 3 - player; // 切换玩家。
}
}
}
较好方法
暂无。