井字棋遊戲

2021-09-21 07:25:54 字數 2458 閱讀 9563

三連棋遊戲(兩人輪流在印有九格方盤上劃「+」或「o」字, 誰先把三個同一記號排成橫線、直線、斜線, 即是勝者)。

程式提供隨機演算法和智慧型演算法兩種ai,隨機演算法使用隨機數隨意選擇棋盤上的位置,智慧型演算法通過對每隔落子位置權重的計算,選取最優的落子點。

#include #include #include #include using namespace std;

//human takes x, competitor takes o,

enum checker;

//base class of randomai, intermediateai, human

class competitor

virtual ~competitor(){}

//competitor algorithms : random and intermediateai

virtual void desiredmove(vector> &checkboard, checker type) = 0;

//checker type

checker checkertype;

string name;

};//move checker by random seed

class randomai:public competitor

void desiredmove(vector> &checkboard, checker type)override}}

if(emptycheckernum == 0)

return;

//get random index

int randomindex = rand()%(emptycheckernum) + 1;

emptycheckernum = 0;

for(auto &row: checkboard)}}

}cout<<"randomai move failed!"<> &checkboard, checker type) override

//count weights of same column

res = countweight(checkboard[0][j],checkboard[1][j],checkboard[2][j]);

if(res != -1)

//in the maindiagonal

if((i == 0 && j == 0) || (i == 1 && j == 1) || (i == 2 && j == 2))

}//in the subdiagonal

if((i == 0 && j == 2)||(i == 2 && j == 0)||(i == 1 && j == 1))}}

}}

//get max weight pos, which is the best hand

int maxi = 0, maxj = 0, maxweight = 0;

for(int i = 0; i < levelboard.size();i++)}}

//set the checker

if(checkboard[maxi][maxj] == empty)

checkboard[maxi][maxj] = checkertype;

else

cout<<"err:intermediateai can't get pos"<> &checkboard, checker type) override

}checkboard[i][j] = checkertype;

}//private:

bool checkexception(vector> &checkboard, int i, int j)

//printcheckerboard

void printcheckboard() else if(checker == o) else

}cout<> checkerboard;

};

程式解析

#include "tictactoe.cpp"

#include "catch.hpp"

test_case("testcheckerboard")

test_case("testwinnercheck")

test_case("testintermediateai")

test_case("testhuman")

#include "tictactoe.cpp"

int main() else if(res == 1) else

}cout<<"intermediateai wins:"

delete competitor2;

return 0;

}

井字棋遊戲

井字棋,英文名叫tic tac toe,是一種在3 3格仔上進行的連珠遊戲,和五子棋類似,由於棋盤一般不畫邊框,格線排成井字故得名。遊戲需要的工具僅為紙和筆,然後由分別代表o和x的兩個遊戲者輪流在格仔裡留下標記 一般來說先手者為x 任意三個標記形成一條直線,則為獲勝。py100天day7 井字棋這個...

井字棋小遊戲

include include define row 3 define col 3 define player piece x define computer piece o 開始選單 void menu 函式宣告 void game void rule void board char board ...

python 井字棋遊戲,Leetcode

今天刷到一道python的題目,對比了他人的做法,覺得自己簡直弱爆了,把這道題記錄一下,也供大家學習,真的很棒!設計乙個演算法,判斷玩家是否贏了井字遊戲。輸入是乙個 n x n 的陣列棋盤,由字元 x 和 o 組成,其中字元 代表乙個空位。規則玩家輪流將字元放入空位 中。第乙個玩家總是放字元 o 且...