井字游戏代码

我们两清 提交于 2020-02-17 15:05:44

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
int main()
{
unsigned int player = 0;
unsigned int xia = 0;
bool winner = 0;
unsigned int row = 0;
unsigned column = 0;
//定义棋子
char qizi[3][3] = { {‘1’,‘2’,‘3’},{‘4’,‘5’,‘6’},{‘7’,‘8’,‘9’} };

for (unsigned int i = 0; i < 9 && winner == 0; ++i)
{
	//1,设定选手号
	player = i % 2 + 1;
	//2,打印棋局,选手下棋,下的不对继续下,并检验赢家
	do {
		printf(" %c | %c | %c \n", qizi[0][0], qizi[0][1], qizi[0][2]);
		printf("---+---+---\n");
		printf(" %c | %c | %c \n", qizi[1][0], qizi[1][1], qizi[1][2]);
		printf("---+---+---\n");
		printf(" %c | %c | %c \n", qizi[2][0], qizi[2][1], qizi[2][2]);
		printf("请%d号选手下,注意你的标记是%c,选择1-9之间的数字即可", player, player == 1 ? 'X' : 'O');
		scanf("%d", &xia);
		row = --xia / 3;
		column = xia % 3;

	} while (xia < 0 && xia>8 && qizi[row][column] > '9');
	qizi[row][column] = (player == 1 ? 'X' : 'O');
	//3,计算赢家
	if (qizi[0][0] == qizi[1][1] && qizi[0][0] == qizi[2][2] || qizi[0][2] == qizi[1][1] && qizi[1][1] == qizi[2][0])
		winner = 1;
	else
		for (int j = 0; j < 3; ++j)
			if (qizi[j][0] == qizi[j][1] && qizi[j][0] == qizi[j][2])
				winner = 1;
			else
				if (qizi[0][j] == qizi[1][j] && qizi[0][j] == qizi[j][2])
					winner = 1;
		}			
if (winner == 0)
	printf("平局");
else
		printf("赢家是%d号选手\n",player);
//4,打印选手下完后的棋局
		printf(" %c | %c | %c \n", qizi[0][0], qizi[0][1], qizi[0][2]);
		printf("---+---+---\n");
		printf(" %c | %c | %c \n", qizi[1][0], qizi[1][1], qizi[1][2]);
		printf("---+---+---\n");
		printf(" %c | %c | %c \n", qizi[2][0], qizi[2][1], qizi[2][2]);
			
system("pause");
return 0;

}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!