以下是一个简单的用C语言编写的穿越迷宫的代码,仅供参考。
#include <graphics.h>
#include <conio.h>
#include <time.h>
#define WIDTH 20 // 迷宫宽度
#define HEIGHT 10 // 迷宫高度
#define WALL_SIZE 30 // 墙的尺寸
#define PATH_COLOR RGB(216, 216, 216)
#define WALL_COLOR RGB(80, 80, 80)
#define PLAYER_COLOR RGB(0, 255, 0)
#define EXIT_COLOR RGB(255, 0, 0)
int maze[HEIGHT][WIDTH]; // 存储迷宫的二维数组
int player_x, player_y; // 玩家所在位置的坐标
int exit_x, exit_y; // 出口所在位置的坐标
// 绘制单元格
void draw_cell(int x, int y, int type) {
switch (type) {
case 0:
setfillcolor(PATH_COLOR); // 空路
break;
case 1:
setfillcolor(WALL_COLOR); // 墙
break;
case 2:
setfillcolor(PLAYER_COLOR); // 玩家
break;
case 3:
setfillcolor(EXIT_COLOR); // 出口
break;
default:
break;
}
solidrectangle(x * WALL_SIZE, y * WALL_SIZE, (x + 1) * WALL_SIZE, (y + 1) * WALL_SIZE);
}
// 绘制迷宫
void draw_maze() {
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
draw_cell(j, i, maze[i][j]);
}
}
}
// 生成迷宫
void generate_maze() {
// 初始化迷宫
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if (i == 0 || i == HEIGHT - 1 || j == 0 || j == WIDTH - 1) {
maze[i][j] = 1; // 迷宫边缘固定为墙
}
else {
maze[i][j] = 0; // 其余位置初始化为空路
}
}
}
// 随机生成迷宫的内部结构
srand((unsigned int)time(NULL));
for (int i = 1; i < HEIGHT - 1; i++) {
for (int j = 1; j < WIDTH - 1; j++) {
if (rand() % 100 < 30) {
maze[i][j] = 1;
}
}
}
// 随机生成入口和出口
player_y = rand() % (HEIGHT - 2) + 1;
maze[player_y][0] = 2;
exit_y = rand() % (HEIGHT - 2) + 1;
maze[exit_y][WIDTH - 1] = 3;
// 防止入口和出口重叠
while (exit_y == player_y) {
exit_y = rand() % (HEIGHT - 2) + 1;
}
}
// 移动玩家
void move_player(int x, int y) {
if (maze[y][x] != 1) {
maze[player_y][player_x] = 0;
player_x = x;
player_y = y;
maze[player_y][player_x] = 2;
}
}
// 检查是否到达出口
bool check_exit(int x, int y) {
if (x == WIDTH - 1 && y == exit_y) {
return true;
}
else {
return false;
}
}
int main() {
initgraph(WIDTH * WALL_SIZE, HEIGHT * WALL_SIZE);
generate_maze();
draw_maze();
while (1) {
if (_kbhit()) { // 判断是否有键盘输入
char input = _getch();
switch (input) {
case 'w':
move_player(player_x, player_y - 1);
break;
case 's':
move_player(player_x, player_y + 1);
break;
case 'a':
move_player(player_x - 1, player_y);
break;
case 'd':
move_player(player_x + 1, player_y);
break;
default:
break;
}
if (check_exit(player_x, player_y)) {
break;
}
draw_maze();
}
Sleep(5); // 延时
}
closegraph();
return 0;
}