1. 贪吃蛇
贪吃蛇是一款经典的小游戏,玩家通过控制蛇的方向来吃食物并增长长度。以下是实现的关键点:
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
void locate(int x, int y) {
COORD coord = { (SHORT)y, (SHORT)x };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
int main() {
int x = 10, y = 10; // 初始位置
char direction = 'd'; // 初始方向
while (true) {
if (_kbhit()) {
direction = _getch(); // 获取用户输入
}
switch (direction) {
case 'w': x--; break;
case 's': x++; break;
case 'a': y--; break;
case 'd': y++; break;
}
system("cls");
locate(x, y);
cout << "O"; // 显示蛇头
Sleep(200); // 控制速度
}
return 0;
}
2. 飞机大战
飞机大战是一款射击类游戏,玩家控制飞机躲避敌人并击落目标。以下是实现的核心逻辑:
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
void drawPlane(int x, int y) {
COORD coord = { (SHORT)x, (SHORT)y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
cout << "▲"; // 飞机符号
}
int main() {
int x = 10, y = 20; // 飞机初始位置
char input;
while (true) {
if (_kbhit()) {
input = _getch();
switch (input) {
case 'w': y--; break;
case 's': y++; break;
case 'a': x--; break;
case 'd': x++; break;
}
}
system("cls");
drawPlane(x, y);
Sleep(100);
}
return 0;
}
3. 2048
2048 是一款数字合并游戏,玩家通过滑动方向键将相同数字合并。以下是实现的关键逻辑:
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
void printBoard(vector<vector<int>>& board) {
for (auto& row : board) {
for (auto& cell : row) {
cout << (cell ? to_string(cell) : ".") << "\t";
}
cout << endl;
}
}
void addRandomTile(vector<vector<int>>& board) {
int x, y;
do {
x = rand() % 4;
y = rand() % 4;
} while (board[x][y] != 0);
board[x][y] = (rand() % 2 + 1) * 2;
}
int main() {
srand(time(0));
vector<vector<int>> board(4, vector<int>(4, 0));
addRandomTile(board);
addRandomTile(board);
printBoard(board);
return 0;
}
4. 扫雷
扫雷是一款经典的逻辑游戏,玩家需要标记地雷并清空安全区域。以下是实现的关键逻辑
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
void generateMines(vector<vector<int>>& board, int mines) {
int rows = board.size(), cols = board[0].size();
while (mines--) {
int x = rand() % rows, y = rand() % cols;
if (board[x][y] == -1) mines++;
else board[x][y] = -1;
}
}
void printBoard(vector<vector<int>>& board) {
for (auto& row : board) {
for (auto& cell : row) {
cout << (cell == -1 ? "*" : ".") << " ";
}
cout << endl;
}
}
int main() {
srand(time(0));
vector<vector<int>> board(10, vector<int>(10, 0));
generateMines(board, 10);
printBoard(board);
return 0