269,337
社区成员
发帖
与我相关
我的任务
分享
游戏玩法:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <chrono>
#include <thread>
#include <cmath>
// 游戏设置
const int GRID_SIZE = 3; // 地鼠网格大小
const int MOLE_COUNT = 5; // 地鼠数量
const int GAME_DURATION = 30; // 游戏持续时间(秒)
const int DIFFICULTY = 1; // 难度级别,1-3
// 游戏状态
struct Mole {
int row;
int col;
bool isHit;
bool isMoving;
};
std::vector<Mole> moles;
std::vector<std::vector<bool>> grid(GRID_SIZE, std::vector<bool>(GRID_SIZE, false));
int score = 0;
int hitCount = 0;
int missCount = 0;
// 初始化地鼠位置
void initializeMoles() {
srand(static_cast<unsigned int>(std::time(nullptr)));
for (int i = 0; i < MOLE_COUNT; ++i) {
int row, col;
do {
row = rand() % GRID_SIZE;
col = rand() % GRID_SIZE;
} while (grid[row][col]);
moles.push_back({row, col, false, false});
grid[row][col] = true;
}
}
// 打印游戏网格
void printGrid() {
for (int i = 0; i < GRID_SIZE; ++i) {
for (int j = 0; j < GRID_SIZE; ++j) {
if (grid[i][j]) {
std::cout << "M ";
} else {
std::cout << ". ";
}
}
std::cout << std::endl;
}
}
// 地鼠行为
void moleBehavior() {
for (auto& mole : moles) {
if (!mole.isHit && !mole.isMoving) {
mole.isMoving = true;
// 模拟地鼠移动,这里简化处理
std::this_thread::sleep_for(std::chrono::milliseconds(500 / pow(2, DIFFICULTY - 1)));
mole.row = rand() % GRID_SIZE;
mole.col = rand() % GRID_SIZE;
mole.isMoving = false;
}
}
}
// 检查是否击中地鼠
bool checkHit(int row, int col) {
for (auto& mole : moles) {
if (mole.row == row && mole.col == col && !mole.isHit) {
mole.isHit = true;
hitCount++;
return true;
}
}
missCount++;
return false;
}
int main() {
initializeMoles();
auto startTime = std::chrono::high_resolution_clock::now();
while (true) {
printGrid();
moleBehavior(); // 更新地鼠行为
std::cout << "Enter row and column to hit (0-" << GRID_SIZE - 1 << "): ";
int row, col;
std::cin >> row >> col;
if (row < 0 || row >= GRID_SIZE || col < 0 || col >= GRID_SIZE) {
std::cout << "Invalid input. Try again." << std::endl;
continue;
}
if (checkHit(row, col)) {
score += 10; // 基础得分
// 检查是否有连击,这里简化处理
if (!moles.empty()) {
score += 5; // 连击得分
}
std::cout << "Hit! Score: " << score << " Hits: " << hitCount << " Misses: " << missCount << std::endl;
moles.erase(std::remove_if(moles.begin(), moles.end(), [](const Mole& m) { return m.isHit; }), moles.end());
if (moles.empty()) {
std::cout << "All moles hit!" << std::endl;
}
} else {
std::cout << "Miss! Try again. Score: " << score << " Hits: " << hitCount << " Misses: " << missCount << stdfty::endl;
}
auto currentTime = std::chrono::high_resolution_clock::now();
if (std::chrono::duration_cast<std::chrono::seconds>(currentTime - startTime).count() >= GAME_DURATION) {
std::cout << "Game over! Your final score is: " << score << std::endl;
std::cout << "Hits: " << hitCount << " Misses: " << missCount << std::endl;
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 控制游戏节奏
}
return 0;
}