devc++制作五子棋
时间: 2024-01-14 10:21:32 浏览: 103
以下是使用Dev-C++制作五子棋的示例代码:
```cpp
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
const int BOARD_SIZE = 15;
const int CELL_SIZE = 40;
const int BOARD_OFFSET = 20;
const int WINDOW_WIDTH = BOARD_SIZE * CELL_SIZE + BOARD_OFFSET * 2;
const int WINDOW_HEIGHT = BOARD_SIZE * CELL_SIZE + BOARD_OFFSET * 2;
enum class Player { NONE, BLACK, WHITE };
Player board[BOARD_SIZE][BOARD_SIZE];
Player currentPlayer;
void initBoard() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
board[i][j] = Player::NONE;
}
}
}
void drawBoard() {
system("cls");
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
int x = BOARD_OFFSET + j * CELL_SIZE;
int y = BOARD_OFFSET + i * CELL_SIZE;
if (board[i][j] == Player::NONE) {
cout << ".";
} else if (board[i][j] == Player::BLACK) {
cout << "X";
} else if (board[i][j] == Player::WHITE) {
cout << "O";
}
cout << " ";
}
cout << endl;
}
}
bool isValidMove(int row, int col) {
return row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE && board[row][col] == Player::NONE;
}
bool isWinningMove(int row, int col) {
Player player = board[row][col];
int count = 1;
// Check horizontally
for (int i = col - 1; i >= 0 && board[row][i] == player; i--) {
count++;
}
for (int i = col + 1; i < BOARD_SIZE && board[row][i] == player; i++) {
count++;
}
if (count >= 5) {
return true;
}
// Check vertically
count = 1;
for (int i = row - 1; i >= 0 && board[i][col] == player; i--) {
count++;
}
for (int i = row + 1; i < BOARD_SIZE && board[i][col] == player; i++) {
count++;
}
if (count >= 5) {
return true;
}
// Check diagonally (top-left to bottom-right)
count = 1;
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0 && board[i][j] == player; i--, j--) {
count++;
}
for (int i = row + 1, j = col + 1; i < BOARD_SIZE && j < BOARD_SIZE && board[i][j] == player; i++, j++) {
count++;
}
if (count >= 5) {
return true;
}
// Check diagonally (top-right to bottom-left)
count = 1;
for (int i = row - 1, j = col + 1; i >= 0 && j < BOARD_SIZE && board[i][j] == player; i--, j++) {
count++;
}
for (int i = row + 1, j = col - 1; i < BOARD_SIZE && j >= 0 && board[i][j] == player; i++, j--) {
count++;
}
if (count >= 5) {
return true;
}
return false;
}
void makeMove(int row, int col) {
board[row][col] = currentPlayer;
currentPlayer = (currentPlayer == Player::BLACK) ? Player::WHITE : Player::BLACK;
}
int main() {
initBoard();
currentPlayer = Player::BLACK;
while (true) {
drawBoard();
cout << "Player " << ((currentPlayer == Player::BLACK) ? "X" : "O") << "'s turn. Enter row and column: ";
int row, col;
cin >> row >> col;
if (isValidMove(row, col)) {
makeMove(row, col);
if (isWinningMove(row, col)) {
drawBoard();
cout << "Player " << ((currentPlayer == Player::BLACK) ? "X" : "O") << " wins!" << endl;
break;
}
} else {
cout << "Invalid move. Try again." << endl;
}
}
return 0;
}
```
阅读全文