五子棋小游戏c++简单代码,具有屏幕更新功能
时间: 2023-08-16 08:07:04 浏览: 85
小游戏五子棋c++代码
4星 · 用户满意度95%
好的,下面是一个简单的 C++ 五子棋小游戏代码,具有屏幕更新功能:
```c++
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
const int ROWS = 15;
const int COLS = 15;
const int CELL_SIZE = 3;
int board[ROWS][COLS] = {0};
int player = 1;
bool gameOver = false;
void drawBoard() {
system("cls");
cout << "Player " << player << "'s turn" << endl;
cout << " ";
for (int i = 0; i < COLS; i++) {
cout << " " << i + 1;
}
cout << endl;
for (int i = 0; i < ROWS; i++) {
cout << i + 1 << " ";
for (int j = 0; j < COLS; j++) {
switch (board[i][j]) {
case 0:
cout << ".";
break;
case 1:
cout << "X";
break;
case 2:
cout << "O";
break;
}
cout << " ";
}
cout << endl;
}
}
bool checkWin(int row, int col, int player) {
int count = 0;
for (int i = row - 4; i <= row; i++) {
if (i < 0 || i + 4 >= ROWS) {
continue;
}
count = 0;
for (int j = i; j <= i + 4; j++) {
if (board[j][col] == player) {
count++;
} else {
break;
}
}
if (count == 5) {
return true;
}
}
for (int i = col - 4; i <= col; i++) {
if (i < 0 || i + 4 >= COLS) {
continue;
}
count = 0;
for (int j = i; j <= i + 4; j++) {
if (board[row][j] == player) {
count++;
} else {
break;
}
}
if (count == 5) {
return true;
}
}
for (int i = row - 4, j = col - 4; i <= row && j <= col; i++, j++) {
if (i < 0 || i + 4 >= ROWS || j < 0 || j + 4 >= COLS) {
continue;
}
count = 0;
for (int k = 0; k < 5; k++) {
if (board[i + k][j + k] == player) {
count++;
} else {
break;
}
}
if (count == 5) {
return true;
}
}
for (int i = row + 4, j = col - 4; i >= row && j <= col; i--, j++) {
if (i >= ROWS || i - 4 < 0 || j < 0 || j + 4 >= COLS) {
continue;
}
count = 0;
for (int k = 0; k < 5; k++) {
if (board[i - k][j + k] == player) {
count++;
} else {
break;
}
}
if (count == 5) {
return true;
}
}
return false;
}
void processInput() {
if (_kbhit()) {
switch (_getch()) {
case 'a':
if (player == 1) {
player = 2;
} else {
player = 1;
}
break;
case 'w':
if (board[0][0] != 0) {
gameOver = true;
} else {
int row = 0;
int col = 0;
while (board[row][col] != 0) {
row++;
col++;
}
board[row][col] = player;
if (checkWin(row, col, player)) {
gameOver = true;
} else if (player == 1) {
player = 2;
} else {
player = 1;
}
}
break;
case 's':
if (board[ROWS - 1][COLS - 1] != 0) {
gameOver = true;
} else {
int row = ROWS - 1;
int col = COLS - 1;
while (board[row][col] != 0) {
row--;
col--;
}
board[row][col] = player;
if (checkWin(row, col, player)) {
gameOver = true;
} else if (player == 1) {
player = 2;
} else {
player = 1;
}
}
break;
case 'q':
gameOver = true;
break;
}
}
}
int main() {
drawBoard();
while (!gameOver) {
processInput();
drawBoard();
}
cout << "Game Over!" << endl;
if (player == 1) {
cout << "Player 2 wins!" << endl;
} else {
cout << "Player 1 wins!" << endl;
}
return 0;
}
```
这个游戏的原理是在控制台中打印出一个 15 行 15 列的棋盘,玩家可以通过按下 'w' 键放置棋子,按下 'a' 键切换玩家,按下 'q' 键结束游戏。当玩家放置一个棋子后,游戏会检查是否有五子连珠,如果有,游戏结束,显示获胜者。如果棋盘已经满了,游戏结束,平局。
阅读全文