多维数组怎么学?看这一篇就够了,带你在游戏中学习。

tic-tac-toe 游戏 (井字棋游戏)

大家小时候应该都玩过井字棋吧,下课之余和同学来上一把,是多么开心。今天 Aaron 就带你来学会用程序来判断井字棋胜利的一方。

  • 读入一个 3X3 的矩阵,矩阵中的数字为 1 表示该位置上有一个 X,为 0 表示 O
  • 程序判断这个矩阵中是否有获胜的一方,输出表示获胜一方的字符 X

由Thomas Steiner - created with the GIMP, I stilll have the xcf-file, if anybody wants to chanage anything.,CC BY-SA 3.0,https://commons.wikimedia.org/w/index.php?curid=678973

大家可以直接看程序,我作了详细的注释。

// 二维数组
Scanner in = new Scanner(System.in);
final int SIZE = 3;
int[][] board = new int[SIZE][SIZE];
boolean gotResult = false;
int numOFX = 0;
int numOFO = 0;
//  输入矩阵
for(int i = 0; i< board.length; i ++)
{
	
	for(int j = 0; j < board[i].length; j++)
	{
		board[i][j] = in.nextInt();
	}
}
// 检查行
for(int i = 0; i< board.length; i++)
{
	numOFX = 0;
	numOFO = 0;
	for(int j = 0; j< board[i].length;j ++)
	{
		if (board[i][j] ==1)
		{
			numOFX ++;
		}
		else
		{
			numOFO ++;
		}
	}
	if(numOFX == SIZE || numOFO == SIZE)
	{
		gotResult = true;
		break;
		
	}
}
// 检查列
if ( !gotResult)
{
	numOFX = 0;
	numOFO = 0;
	for(int i = 0; i< board.length; i++)
	{
		for(int j = 0; j< board[i].length;j ++)
		{
			if (board[j][i] ==1)
			{
				numOFX  ++;
			}
			else
			{
				numOFO ++;
			}
		}
		if(numOFX == SIZE || numOFO == SIZE)
		{
			gotResult = true;
			break;
			
		}
	}
}
	// 判断反对角线
if ( !gotResult)
{
	numOFX = 0;
	numOFO = 0;
	for(int i1 = 0; i1< board.length; i1++)
	{
		
		if( board[i1][SIZE-i1-1] ==1)
		{
			numOFX  ++;
		}
		else
		{
			numOFO ++;
		}
		
		if(numOFX == SIZE || numOFO == SIZE)
		{
			gotResult = true;
			break;
			
		}
	}
}
	// 判断对角线
if ( !gotResult)
{
	numOFX = 0;
	numOFO = 0;
	for(int i1 = 0; i1< board.length; i1++)
	{
		
		if( board[i1][i1] ==1)
		{
			numOFX  ++;
		}
		else
		{
			numOFO ++;
		}
		
		if(numOFX == SIZE || numOFO == SIZE)
		{
			gotResult = true;
			break;
			
		}
	}
}
if(gotResult )
{

	if(numOFX == SIZE)
	{
		System.out.println("X 赢了");
	}
	else
	{
		System.out.println("O 赢了");
	}
	
	
}
if(!gotResult)
{
	System.out.println("没有结果");
}

代码总的来说就是是个四个循环,先判断行是否出现三个相同元素,在判断列,最后判断两个对角线。简单易懂,希望对你有帮助!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值