c++井字棋(●'◡'●)
2025-01-19 09:51:19
发布于:广东
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
const int SIZE = 3;
char board[SIZE][SIZE] = { {' ', ' ', ' '},
{' ', ' ', ' '},
{' ', ' ', ' '} };
char currentPlayer = 'X';
void printBoard() {
for (int i = 0; i < SIZE; ++i) {
for (int j = 0; j < SIZE; ++j) {
stdcout << board[i][j] << " ";
}
stdcout << std::endl;
}
}
bool checkWin(char player) {
// 检查行
for (int i = 0; i < SIZE; ++i) {
if (board[i][0] == player && board[i][1] == player && board[i][2] == player) {
return true;
}
}
// 检查列
for (int j = 0; j < SIZE; ++j) {
if (board[0][j] == player && board[1][j] == player && board[2][j] == player) {
return true;
}
}
// 检查对角线
if (board[0][0] == player && board[1][1] == player && board[2][2] == player) {
return true;
}
if (board[0][2] == player && board[1][1] == player && board[2][0] == player) {
return true;
}
return false;
}
bool isBoardFull() {
for (int i = 0; i < SIZE; ++i) {
for (int j = 0; j < SIZE; ++j) {
if (board[i][j] == ' ') {
return false;
}
}
}
return true;
}
void playGame() {
while (true) {
printBoard();
int row, col;
stdcout << "玩家 " << currentPlayer << ",请输入行和列(0-2): ";
stdcin >> row >> col;
if (row < 0 || row >= SIZE || col < 0 || col >= SIZE || board[row][col] != ' ') {
std::cout << "无效的移动!请重试。" << std::endl;
continue;
}
board[row][col] = currentPlayer;
if (checkWin(currentPlayer)) {
printBoard();
std::cout << "玩家 " << currentPlayer << " 获胜!" << std::endl;
break;
}
if (isBoardFull()) {
printBoard();
std::cout << "平局!" << std::endl;
break;
}
currentPlayer = (currentPlayer == 'X') ? 'O' : 'X';
}
}
int main() {
stdsrand(static_cast<unsigned int>(stdtime(0)));
playGame();
return 0;
}
这里空空如也
有帮助,赞一个