c++编写一个打地鼠游戏
时间: 2023-07-19 17:31:21 浏览: 51
好的,以下是一个简单的打地鼠游戏的 C++ 代码:
```c++
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <conio.h>
#include <windows.h>
using namespace std;
const int boardWidth = 20;
const int boardHeight = 10;
const int maxMoles = 10;
int score = 0;
int molesLeft = maxMoles;
bool gameBoard[boardHeight][boardWidth] = { false };
void clearScreen()
{
COORD cursorPosition;
cursorPosition.X = 0;
cursorPosition.Y = 0;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cursorPosition);
}
void displayBoard()
{
clearScreen();
cout << "Score: " << score << endl;
cout << "Moles Left: " << molesLeft << endl;
for (int y = 0; y < boardHeight; y++) {
for (int x = 0; x < boardWidth; x++) {
if (gameBoard[y][x]) {
cout << "M";
} else {
cout << ".";
}
}
cout << endl;
}
}
void placeMole()
{
int x, y;
do {
x = rand() % boardWidth;
y = rand() % boardHeight;
} while (gameBoard[y][x]);
gameBoard[y][x] = true;
}
void whack(int x, int y)
{
if (gameBoard[y][x]) {
gameBoard[y][x] = false;
score++;
molesLeft--;
}
}
int main()
{
srand(time(NULL));
char input;
int x, y;
while (molesLeft > 0) {
displayBoard();
cout << "Enter x and y coordinates to whack mole: ";
cin >> x >> y;
whack(x, y);
placeMole();
}
cout << "You win!" << endl;
return 0;
}
```
该代码使用了 Windows API 的一些功能,可以在 Windows 上编译和运行。游戏板的大小为 20x10,最多存在 10 只地鼠。每次游戏会提示输入 x 和 y 坐标来敲打地鼠,直到所有地鼠都被敲打完毕,游戏结束并输出胜利信息。