2 Star 1 Fork 27

hugefiver/finalab-19

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
ex1.cpp 2.13 KB
一键复制 编辑 原始数据 按行查看 历史
ZerAx 提交于 2019-10-02 23:27 +08:00 . 10.2
// TicTacToe.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
using namespace std;
bool checkMajorDiagonal(int board[3][3], int state) {
//主对角线
for (int i = 0; i < 3; ++i) {
if (board[i][i] != state) {
return false;
}
}
return true;
}
bool checkMinorDiagonal(int board[3][3], int state) {
//次对角线
for (int i = 0; i < 3; ++i) {
int j = 2 - i;
if (board[i][j] != state) {
return false;
}
}
return true;
}
bool checkHorizontal(int board[3][3], int state, int y) {
//横
for (int i = 0; i < 3; ++i) {
if (board[y][i] != state) {
return false;
}
}
return true;
}
bool checkVertical(int board[3][3], int state, int x) {
//竖
for (int i = 0; i < 3; ++i) {
if (board[i][x] != state) {
return false;
}
}
return true;
}
void printBoard(int board[3][3]) {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
cout << board[i][j] << " ";
}
cout << endl;
}
}
int main()
{
int board[3][3];
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
board[i][j] = 0;
bool win = false;
//标记是谁在下棋,默认1号先下
short state = 1;
while (!win) {
//获取一个坐标表示下在(x,y)上
cout << "现在是" << state << "号棋手在下棋(请按\"x y\"的格式下,从(0,0)开始):" << endl;
int x, y;
cin >> x >> y;
if (x < 0 || x > 2 || y < 0 || y > 2) {
cout << "下棋盘外面了...重来!" << endl;
continue;
}
if (board[y][x] != 0) {
cout << "这里已经下过了,重来!" << endl;
continue;
}
board[y][x] = state;
//如果在对角线
if (!((x == 1 && y != 1) || (y == 1 && x != 1))) {
if (checkMajorDiagonal(board, state) || checkMinorDiagonal(board, state)) {
cout << state << "号胜!" << endl;
break;
}
}
if (checkHorizontal(board, state, y) || checkVertical(board, state, x)) {
cout << state << "号胜!" << endl;
break;
}
cout << "当前棋盘状态:" << endl;
printBoard(board);
if (state == 1)
state = 2;
else
state = 1;
}
cout << endl;
cout << "最终棋盘状态:" << endl;
printBoard(board);
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/hugefiver/finalab.git
git@gitee.com:hugefiver/finalab.git
hugefiver
finalab
finalab-19
master

搜索帮助