C++实现——三子棋游戏

来源:互联网 发布:苹果mac宽屏电脑壁纸 编辑:程序博客网 时间:2024/06/09 16:02

这里写图片描述
/*
题目描述:
两个人玩三子棋游戏,即在3*3的矩阵上下棋,一个人画叉一个人画圈,谁先出现成行或成列或成对角线三个相同的棋子就算谁赢。编写算法实现,判断给定棋局的状态,用1代表先手,2代表后手。出现的六种状态为 1won 2won x(代表棋局错误) draw(代表平局) 1(下一步先手走) 2(下一步后手走)

*/

输入 :(共含有三种字符 x . 0)
含有测试,每组测试用例需要输入三行
样例:
x.x
x0x
0x.
输出:
2

#include "stdafx.h"#include <iostream>#include <vector>#include <cstdio>#include<algorithm>#include <map>#include <string>using namespace std;int main(){    //代表行矩阵    vector<vector<char>> board1(3, vector<char>(3));    //代表列矩阵    vector<vector<char>> board2(3, vector<char>(3));    //记录主/副对角线    vector<char> a, b;    while (1){        int onum = 0;        int xnum = 0;        for (int i = 0; i < 3; i++){            for (int j = 0; j < 3; j++){                char c;                cin >> c;                //填充行矩阵                board1[i][j] = c;                //填充列矩阵                board2[j][i] = c;                //统计先手和后手放棋子的个数                if (board1[i][j] == '0')++onum;                if (board1[i][j] == 'x')++xnum;                //记录正对角线                if (i == j)a.push_back(c);                //记录斜对角线                if ((i == 1 && j == 1) || (i == 0 && j == 2) || (i == 2 && j == 0))                    b.push_back(c);            }        }        vector<char> t1 = { '0', '0', '0' }, t2 = {'x','x','x'};        int count = 0;        for (int i = 0; i < 3; i++){            if (board1[i] == t1 || board1[i] == t2) ++count;            if (board2[i] == t1 || board2[i] == t2) ++count;        }        if (t1 == a || t2==a)++count;        if (t1 == b || t2 == b)++count;        //不合理的棋局        if (count >= 2){            cout << "x" << endl;        }        //由一方剩        else if(count==1){            if (onum == xnum)cout << "2 won" << endl;            else cout << "1 won" << endl;        }        //平局或者继续走        else {            //棋盘已满,不分胜负            if (onum + xnum == 9)cout << "draw" << endl;            else{                 //恰为偶数,轮着1走                if (onum == xnum)cout << "1" << endl;                //为奇数,轮着2走                else cout << "2" << endl;            }        }    }    return 0;}
0 0