vc++6.0推箱子代码
时间: 2023-07-31 10:05:49 浏览: 80
以下是一个简单的 VC++6.0 推箱子代码示例:
```c++
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
const int MAXN = 20;
const int MAXM = 20;
const int WALL = -1;
const int BLANK = 0;
const int BOX = 1;
const int TARGET = 2;
const int PLAYER = 3;
const int MOVEX[4] = {-1, 0, 1, 0};
const int MOVEY[4] = {0, 1, 0, -1};
int map[MAXN][MAXM];
int n, m;
int px, py;
void init()
{
memset(map, WALL, sizeof(map));
cout << "Please input the size of the map (n m): ";
cin >> n >> m;
cout << "Please input the map (use # to represent wall, . to represent blank, * to represent target, and @ to represent player):" << endl;
char ch;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
{
cin >> ch;
if (ch == '#') map[i][j] = WALL;
else if (ch == '.') map[i][j] = BLANK;
else if (ch == '*') map[i][j] = TARGET;
else if (ch == '@') map[i][j] = PLAYER, px = i, py = j;
}
}
void print_map()
{
system("cls");
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
if (map[i][j] == WALL) cout << '#';
else if (map[i][j] == BLANK) cout << ' ';
else if (map[i][j] == TARGET) cout << '*';
else if (map[i][j] == BOX) cout << '$';
else if (map[i][j] == PLAYER) cout << '@';
cout << endl;
}
}
bool push_box(int x, int y, int dir)
{
int nx = x + MOVEX[dir], ny = y + MOVEY[dir];
if (map[nx][ny] == WALL || map[nx][ny] == BOX) return false;
map[nx][ny] = BOX;
map[x][y] = (map[x][y] == TARGET ? TARGET : BLANK);
return true;
}
bool move(int dir)
{
int nx = px + MOVEX[dir], ny = py + MOVEY[dir];
if (map[nx][ny] == WALL) return false;
if (map[nx][ny] == BLANK)
{
map[px][py] = BLANK;
map[nx][ny] = PLAYER;
px = nx, py = ny;
return true;
}
if (map[nx][ny] == TARGET)
{
map[px][py] = BLANK;
map[nx][ny] = PLAYER;
px = nx, py = ny;
return true;
}
if (map[nx][ny] == BOX)
{
bool success = push_box(nx, ny, dir);
if (success)
{
map[px][py] = BLANK;
map[nx][ny] = PLAYER;
px = nx, py = ny;
}
return success;
}
}
int main()
{
init();
print_map();
while (true)
{
int ch = getch();
if (ch == 27) break;
bool success = false;
if (ch == 'w' || ch == 'W') success = move(0);
if (ch == 'd' || ch == 'D') success = move(1);
if (ch == 's' || ch == 'S') success = move(2);
if (ch == 'a' || ch == 'A') success = move(3);
if (success) print_map();
}
return 0;
}
```
该代码可以让用户自定义地图,并使用 WASD 键来控制人物移动,将箱子推到目标点即可胜利。
阅读全文