迷宫
2025-08-07 20:58:25
发布于:浙江
迷宫
- 效果:无需多言
- 使用:WASD 以移动,代码里的 N 可以自行调整,但必须是奇数(建议)
- 说明:好玩,参与其他制作
#include <bits/stdc++.h>
#include <windows.h>
#include <conio.h>
using namespace std;
const int maze_n = 31;
int maze_dx[4] = {0,0,1,-1};
int maze_dy[4] = {1,-1,0,0};
bool maze_mp[1005][1005];
bool maze_in(int x,int y) {
return x >= 1 && x <= maze_n && y >= 1 & y <= maze_n;
}
void maze_dfs(int x,int y) {
if(x == maze_n - 1 && y == maze_n - 1) return;
int dir[4] = {0,1,2,3};
for(int i = 0;i < 4;i++) {
int j = rand() % 4;
swap(dir[i],dir[j]);
}
for(int d : dir) {
int nx = x + 2 * maze_dx[d];
int ny = y + 2 * maze_dy[d];
if(maze_in(nx,ny) && maze_mp[nx][ny] == 1) {
maze_mp[nx][ny] = maze_mp[x + maze_dx[d]][y + maze_dy[d]] = 0;
maze_dfs(nx,ny);
}
}
}
void maze_init() {
for(int i = 1;i <= maze_n;i++) {
for(int j = 1;j <= maze_n;j++) {
maze_mp[i][j] = 1;
}
}
maze_mp[2][2] = 0;
maze_dfs(2,2);
}
void maze_print() {
system("cls");
for(int i = 1;i <= maze_n;i++) {
for(int j = 1;j <= maze_n;j++) {
if(maze_mp[i][j]) cout << "■";
else cout << "□";
}
cout << '\n';
}
}
void maze_color(string s) {
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
if(s == "white") SetConsoleTextAttribute(h,FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
else if(s == "red") SetConsoleTextAttribute(h,FOREGROUND_INTENSITY | FOREGROUND_RED);
else if(s == "green") SetConsoleTextAttribute(h,FOREGROUND_INTENSITY | FOREGROUND_GREEN);
else if(s == "blue") SetConsoleTextAttribute(h,FOREGROUND_INTENSITY | FOREGROUND_BLUE);
}
void maze_go(int x,int y) {
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
COORD coord;
coord.X = x,coord.Y = y;
SetConsoleCursorPosition(h,coord);
}
void maze_play() {
maze_go(2 * maze_n - 4,maze_n - 2);
maze_color("green");
cout << "■";
int px = 2,py = 2;
while(px != maze_n - 1 || py != maze_n - 1) {
maze_go(2 * py - 2,px - 1);
maze_color("red");
cout << "■";
maze_go(0,maze_n);
char op = getch();
maze_go(2 * py - 2,px - 1);
maze_color("blue");
cout << "□";
if(op == 'w' || op == 'W') {
if(maze_mp[px - 1][py]) continue;
px--;
}
else if(op == 's' || op == 'S') {
if(maze_mp[px + 1][py]) continue;
px++;
}
else if(op == 'a' || op == 'A') {
if(maze_mp[px][py - 1]) continue;
py--;
}
else if(op == 'd' || op == 'D') {
if(maze_mp[px][py + 1]) continue;
py++;
}
}
maze_go(2 * maze_n - 4,maze_n - 2);
maze_color("red");
cout << "■";
maze_go(0,maze_n);
maze_color("white");
cout << "You Win!\n";
Sleep(3000);
}
void maze() {
srand(time(NULL));
maze_init();
maze_print();
maze_play();
}
int main() {
system("pause");
maze();
return 0;
}
全部评论 1
ddd
2025-08-09 来自 浙江
0
有帮助,赞一个