graphics.h)實現2=牆壁,1=可通行,0=豆子,3=玩家,4=敵人
#define LEFT 0x4b00
#define RIGHT 0x4d00
#define DOWN 0x5000
#define UP 0x4800
#define ESC 0x011b
int map[15][20] = { /* 地圖數據 */ };
struct Player { int x, y; };
Player you, them[5];
int xx[5][2]; // 敵人上一步/本步方向,防止來回震盪
int sum = 0; // 吃豆計數
bool gameOver = false;
begain()movethem()
void movethem(Player* them) {
for (int i = 0; i < 5; ++i) {
// 1. 若玩家在相鄰四格,直接移向玩家
if (you.x == them[i].x && them[i].y + 1 == you.y) them[i].y++;
else if (you.x == them[i].x && them[i].y - 1 == you.y) them[i].y--;
else if (you.y == them[i].y && them[i].x + 1 == you.x) them[i].x++;
else if (you.y == them[i].y && them[i].x - 1 == you.x) them[i].x--;
// 2. 否則隨機選方向,但不能與上一步方向相反
else {
do {
xx[i][0] = rand() % 4 + 1; // 1=左,2=右,3=下,4=上
} while ((xx[i][0]==1 && xx[i][1]==2) ||
(xx[i][0]==2 && xx[i][1]==1) ||
(xx[i][0]==3 && xx[i][1]==4) ||
(xx[i][0]==4 && xx[i][1]==3));
xx[i][1] = xx[i][0];
// 嘗試移動,撞牆則回退並重新隨機
switch (xx[i][0]) {
case 1: them[i].x--; if (map[them[i].x][them[i].y]==2) { them[i].x++; continue; } break;
case 2: them[i].x++; if (map[them[i].x][them[i].y]==2) { them[i].x--; continue; } break;
case 3: them[i].y++; if (map[them[i].x][them[i].y]==2) { them[i].y--; continue; } break;
case 4: them[i].y--; if (map[them[i].x][them[i].y]==2) { them[i].y++; continue; } break;
}
}
}
}
kbhit() + bioskey(0)TimeDelay(280000) 控制幀率| 亮點 | 不足 |
|---|---|
| 敵人「視野追蹤 + 隨機游走」行為自然 | 大量 goto 降低可讀性,建議改用循環/函數 |
| 方向防反邏輯避免震盪 | 地圖硬編碼,無關卡編輯/加載機制 |
| 碰撞檢測分離(敵人移動後、玩家移動後各檢測一次) | 延時函數依賴 BIOS 中斷 int 0x15,移植性極差 |
| 勝利/失敗畫面有簡單動畫 | 無分數系統、無多關卡、無音效 |
while (running) { processInput(); update(dt); render(); }文末附完整單文件源碼,可在 Turbo C / BC++ / VC6(含 graphics.h)下直接編譯運行。