遊走地圖
RPG遊戲在地圖上如何判斷什麼是障礙物以及什麼是道路,就是用二維陣列中的數字來決定。以下的小範例,可以使用方向鍵來移動角色@@,遇到牆壁則不會穿過。
#include <iostream>
#include <conio.h>
#include <windows.h>
using namespace std;
const int UP=72;
const int LEFT=75;
const int RIGHT=77;
const int DOWN=80;
//2*x是因為想要讓文字與文字間格是全型的字體
void gotoxy(int x, int y)
{
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),
(COORD) {2 * x, y });
}
int main(){
int key1,key2,x=1,y=1;
int map[8][8] = {
{ 1, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 0, 0, 0, 1, 0, 0, 1 },
{ 1, 0, 0, 0, 0, 0, 0, 1 },
{ 1, 0, 0, 0, 0, 1, 1, 1 },
{ 1, 1, 0, 1, 0, 0, 0, 1 },
{ 1, 0, 0, 1, 0, 0, 0, 1 },
{ 1, 0, 0, 1, 0, 0, 1, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1 }
};
for (int i= 0; i < 8;i++){
for (int j= 0; j < 8;j++){
if (map[i][j] == 0) {
cout << " ";
} else if (map[i][j] == 1) {
cout << "gg";
}
}
cout << endl;
}
gotoxy(x,y);
cout<<"@@";
while (1) {
if (kbhit()) {
int key1 = getch();
if(key1 == 224){
int key2=getch();
switch (key2) {
case UP:
if(map[y-1][x]==1)break;
gotoxy(x,y);
cout<<" ";
gotoxy(x,--y);
cout<<"@@";
break;
case DOWN:
if(map[y+1][x]==1)break;
gotoxy(x,y);
cout<<" ";
gotoxy(x,++y);
cout<<"@@";
break;
case LEFT:
if(map[y][x-1]==1)break;
gotoxy(x,y);
cout<<" ";
gotoxy(--x,y);
cout<<"@@";
break;
case RIGHT:
if(map[y][x+1]==1)break;
gotoxy(x,y);
cout<<" ";
gotoxy(++x,y);
cout<<"@@";
break;
}
}
}
}
}