迷宫游戏代码(完整版)
#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;
}