五子棋小游戏
五子棋小游戏
好久没有碰C++了,最近写个五子棋的小游戏玩玩。
代码如下:
#include<iostream>
#include<vector>
using namespace std;// 棋盘的大小
const int SIZE = 15;
// 棋子的类型(空格、黑棋、白棋)
const char EMPTY = ' ';
const char BLACK = 'X';
const char WHITE = 'O';// 初始化棋盘
void init_board(vector<vector<char>>& board) {for (int i = 0; i < SIZE; ++i) {board[i].assign(SIZE, EMPTY);}
}// 打印棋盘
void print_board(vector<vector<char>>& board) {cout << " ";//空两格// 打印列号for (int i = 0; i < SIZE; ++i) {printf("%2d", i + 1);}cout << endl;// 打印棋盘内容for (int i = 0; i < SIZE; ++i) {printf("%2d", i + 1);for (int j = 0; j < SIZE; ++j) {cout << "|" << board[i][j];}cout << "|" << endl;// 打印分隔线if (i != SIZE - 1) {cout << " ";for (int j = 0; j < SIZE; ++j) {cout << "+-";}cout << "+" << endl;}}cout << endl;
}// 胜负判断
bool check_win(vector<vector<char>>& board, int x, int y, char player) {// 用于遍历方向(水平、垂直、左斜、右斜)int dirs[4][2] = { {0, 1}, {1, 0}, {1, 1}, {1, -1} };for (auto dir : dirs) {int dx = dir[0];int dy = dir[1];int count = 0; // 统计该方向上的连续棋子数(不含当前位置)for (int i = -4; i <= 4; ++i) {if (i == 0) continue; // 跳过当前位置int nx = x + dx * i;int ny = y + dy * i;if (nx >= 0 && nx < SIZE && ny >= 0 && ny < SIZE && board[nx][ny] == player) {count++;}else {break; // 遇到边界或不同棋子,停止该方向检查}}if (count + 1 >= 5) return true; // 加上当前位置,共5个则获胜}return false;
}int main() {cout << "五子棋游戏" << endl;cout << "输入格式:行号 列号。例如输入:1 2(表示在第1行第2列落子)" << endl;vector<vector<char>> board(SIZE, vector<char>(SIZE));init_board(board); // 先初始化print_board(board); // 再打印初始棋盘char cur_player = BLACK; // 黑棋先行bool game_over = false;int x, y;while (!game_over) {cout << ((cur_player == BLACK) ? "黑棋(X)落子: " : "白棋(O)落子: ");cin >> x >> y;x--; // 转换为0-based索引(用户输入1~15 → 0~14)y--;// 检查输入合法性if (x < 0 || x >= SIZE || y < 0 || y >= SIZE) {cout << "输入无效,请输入1-" << SIZE << "之间的数字" << endl;continue;}if (board[x][y] != EMPTY) {cout << "该位置已经有棋子!请重新落子" << endl;continue;}// 落子board[x][y] = cur_player;print_board(board);// 检测是否获胜if (check_win(board, x, y, cur_player)) {cout << (cur_player == BLACK ? "黑棋(X)获胜!" : "白棋(O)获胜!") << endl;game_over = true;}// 检测是否平局else {bool is_full = true;for (int i = 0; i < SIZE; ++i) {for (int j = 0; j < SIZE; ++j) {if (board[i][j] == EMPTY) {is_full = false;break;}}if (!is_full) break;}if (is_full) {cout << "平局!" << endl;game_over = true;}}// 仅在游戏未结束时切换玩家if (!game_over) {cur_player = (cur_player == BLACK) ? WHITE : BLACK;}}cout << "游戏结束!" << endl;return 0;
}