如果有更好的算法,请在下方评论学习
输入1表示 X 下的棋,输入0表示 Y 下的棋
package game; import java.util.Scanner; public class Game_new { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int SIZE ;// 单元格 int numOfX=0; int numOfY=0; System.out.println("Plase enter the game'sizes: "); SIZE=in.nextInt();//get int [][]game = new int [SIZE][SIZE]; boolean getResult = false; System.out.println("Please enter your X or Y"); for(int i=0;i<game.length;i++) { for(int k=0;k<game[i].length;k++) { game[i][k]=in.nextInt(); } } for(int i=0;i<game.length;i++) {//判断主对角线 if(game[i][i]==1) { numOfX++; } else { numOfY++; } if(numOfX==SIZE || numOfY==SIZE) { getResult=true; } } if(!getResult) {//判断副对角线 numOfX=0; numOfY=0; for(int i=0;i<game.length;i++) { if(game[i][SIZE-1-i]==1) { numOfX++; } else { numOfY++; } if(numOfX==SIZE || numOfY==SIZE) { getResult=true; } } } if(!getResult) {//判断行 for(int i=0;i<game.length;i++) { numOfX=0; numOfY=0; for(int k=0;k<game[i].length;k++) { if(game[i][k]==1) numOfX++; else numOfY++; } if(numOfX==SIZE || numOfY==SIZE) { getResult=true; break; } } } if(!getResult) {//判断列 for(int i=0;i<SIZE;i++) { numOfX=0; numOfY=0; for(int k=0;k<SIZE;k++) { if(game[k][i]==1) numOfX++; else numOfY++; } if(numOfX==SIZE || numOfY==SIZE) { getResult=true; break; } } } if(getResult) { if(numOfX==SIZE) { System.out.println("X win this game!"); } else { System.out.println("Y win this game!"); } } else { System.out.println("draw!"); } } }