以下是一個簡單的C++實現五子棋的代碼示例:
#include <iostream>
#include <vector>
const int BOARD_SIZE = 15;
char board[BOARD_SIZE][BOARD_SIZE];
void initBoard() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = '.';
}
}
}
void printBoard() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
std::cout << board[i][j] << " ";
}
std::cout << std::endl;
}
}
bool checkWin(int x, int y, char player) {
// 檢查橫向
int count = 1;
for (int i = 1; i < 5; i++) {
if (x+i >= BOARD_SIZE || board[x+i][y] != player) {
break;
}
count++;
}
for (int i = 1; i < 5; i++) {
if (x-i < 0 || board[x-i][y] != player) {
break;
}
count++;
}
if (count >= 5) {
return true;
}
// 檢查縱向
count = 1;
for (int i = 1; i < 5; i++) {
if (y+i >= BOARD_SIZE || board[x][y+i] != player) {
break;
}
count++;
}
for (int i = 1; i < 5; i++) {
if (y-i < 0 || board[x][y-i] != player) {
break;
}
count++;
}
if (count >= 5) {
return true;
}
// 檢查斜向
count = 1;
for (int i = 1; i < 5; i++) {
if (x+i >= BOARD_SIZE || y+i >= BOARD_SIZE || board[x+i][y+i] != player) {
break;
}
count++;
}
for (int i = 1; i < 5; i++) {
if (x-i < 0 || y-i < 0 || board[x-i][y-i] != player) {
break;
}
count++;
}
if (count >= 5) {
return true;
}
// 檢查反斜向
count = 1;
for (int i = 1; i < 5; i++) {
if (x+i >= BOARD_SIZE || y-i < 0 || board[x+i][y-i] != player) {
break;
}
count++;
}
for (int i = 1; i < 5; i++) {
if (x-i < 0 || y+i >= BOARD_SIZE || board[x-i][y+i] != player) {
break;
}
count++;
}
if (count >= 5) {
return true;
}
return false;
}
int main() {
initBoard();
char player = 'X';
int x, y;
while (true) {
printBoard();
std::cout << "Player " << player << ": ";
std::cin >> x >> y;
if (x < 0 || x >= BOARD_SIZE || y < 0 || y >= BOARD_SIZE || board[x][y] != '.') {
std::cout << "Invalid move, try again." << std::endl;
continue;
}
board[x][y] = player;
if (checkWin(x, y, player)) {
printBoard();
std::cout << "Player " << player << " wins!" << std::endl;
break;
}
player = (player == 'X') ? 'O' : 'X';
}
return 0;
}
這段代碼實現了一個簡單的五子棋游戲,玩家可以輪流下棋,當有玩家連成五子時游戲結束并宣布勝利。您可以在此基礎上進行更多的擴展和優化。