判断井字棋是否结束和谁赢

1 代表 X 0 代表 O 用到了遍历

import java.util.Scanner;

// look at # game who win

public class Hello {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		final int SIZE = 3;
		int[][] board = new int[SIZE][SIZE];
		boolean gotResult = false;	// first, result = false
		int numfX = 0;	// X -- 1
		int numfO = 0;	// O -- 0
		
		// read Matrix
		for(int i = 0; i<board.length; i++)
		{
			for(int j = 0; j<board[i].length; j++)
			{
				board[i][j] = in.nextInt();
			}
		}
		
		// traverse row axis
		for(int i = 0; i < board.length; i++)
		{
			numfX = 0;
			numfO = 0;
			for(int j = 0; j < board[i].length; j++)
			{
				if(board[i][j] == 1)
				{
					numfX++;
				}
				else
				{
					numfO++;
				}
			}
			if(numfX == SIZE || numfO == SIZE)
			{
				gotResult = true;
				if (numfX == SIZE)
				{
					System.out.println("X WIN");
				}
				else
				{
					System.out.println("O WIN");
				}
				break;
			}
		}
		// traverse column axis
		for(int j = 0; j < SIZE; j++)
		{
			numfX = 0;
			numfO = 0;
			for(int i = 0;i < SIZE; i++)
			{
				if(board[i][j] == 1)
				{
					numfX++;
				}
				else
				{
					numfO++;
				}
			}
			if(numfX == SIZE || numfO == SIZE)
			{
				gotResult = true;
				if (numfX == SIZE)
				{
					System.out.println("X WIN");
				}
				else
				{
					System.out.println("O WIN");
				}
				break;
			}
		}
		// traverse main diagonal
		numfX = 0;
		numfO = 0;
		for(int i = 0; i < SIZE; i++)
		{
			if(board[i][i] == 1)
			{
				numfX++;
			}
			else
			{
				numfO++;
			}
			if(numfX == SIZE || numfO == SIZE)
			{
				gotResult = true;
				if (numfX == SIZE)
				{
					System.out.println("X WIN");
				}
				else
				{
					System.out.println("O WIN");
				}
			}
		}
		
		// traverse back-diagonal
		numfX = 0;
		numfO = 0;
		for(int i = 0; i < SIZE; i++)
		{
			if(board[i][2-i] == 1)
			{
				numfX++;
			}
			else
			{
				numfO++;
			}
			if(numfX == SIZE || numfO == SIZE)
			{
				gotResult = true;
				if (numfX == SIZE)
				{
					System.out.println("X WIN");
				}
				else
				{
					System.out.println("O WIN");
				}
			}
		}
		
		if(gotResult)
		{
			System.out.println("GOT RESULT!");
		}
		else
		{
			System.out.println("CONTINUE!");
		}
	}
}

 

上一篇:设置ubuntu、deppin(等linux系统)和window双系统启动引导顺序


下一篇:自动化kolla-ansible部署openstack+GPU透传方法