1. 程式人生 > >C++實現——三子棋遊戲

C++實現——三子棋遊戲

這裡寫圖片描述
/*
題目描述:
兩個人玩三子棋遊戲,即在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; }