这是一个不完整的TILEWORLD游戏,我通过处理编写,其中包含20个障碍物,10个洞,10个贴图和一个代理。代理随机移动,其他对象不移动。在代理移动功能中,代理进入障碍,停止,但我希望代理避免进入障碍物,那么如何跟踪代理以前的位置,如果代理的下一步移动是障碍物的位置在,它避免它?你可以去这个问题,假设你的代理只能移动1个格2D处理阵列位置轨迹
int min_x = 0;
int min_y = 0;
int max_x = 400;
int max_y = 600;
int grid_size = 10;
int Hoo[][] = new int[60][40];
int numhole=10;
int numtile =10;
int numobs=20;
PVector agent=getRandomLoc();
PVector hole1;
PVector tile;
PVector obstacle;
int x,y;
int i,j;
int a,b;
final int hole=1;
final int til=2;
final int obs=3;
final int STOPPED = 0;
final int RUNNING = 1;
int agentState = STOPPED;
void settings()
{
size(max_x, max_y);
}
void setup() {
ellipseMode(CORNER);
agentState = RUNNING;
for(x=0; x<60; x++){
for(y=0;y<40;y++){
Hoo[x][y]=0;
}}
while(numhole>0)
{
hole1=getRandomLoc();
i=(int)hole1.x/grid_size;
j=(int)hole1.y/grid_size;
if(Hoo[j][i]==0){
Hoo[j][i]=hole;
numhole--;
}
}
while(numobs>0)
{
obstacle=getRandomLoc();
i=(int)obstacle.x/grid_size;
j=(int)obstacle.y/grid_size;
if(Hoo[j][i]==0){
Hoo[j][i]=obs;
numobs--;
}
}
while(numtile>0)
{
tile=getRandomLoc();
i=(int)tile.x/grid_size;
j=(int)tile.y/grid_size;
if(Hoo[j][i]==0){
Hoo[j][i]=til;
numtile--;
}
}
}
void draw() {
background(#ffffff);
stroke(#cccccc);
for (int x=min_x; x<=max_x; x+=grid_size) {
line(x,min_y,x,max_y);
}
for (int y=min_y; y<=max_y; y+=grid_size) {
line(min_x,y,max_x,y);
}
for(int x=0; x< 60; x++){
for(int y=0; y<40; y++){
if(Hoo[x][y]==obs){
stroke(#cccccc);
fill(#cccccc);
rect(y*grid_size,x*grid_size, grid_size, grid_size);
}}}
for(int x=0; x< 60; x++){
for(int y=0; y<40; y++){
if(Hoo[x][y]==hole){
stroke(#cccccc);
fill(#000000);
rect(y*grid_size,x*grid_size, grid_size, grid_size);
}}}
for(int x=0; x< 60; x++){
for(int y=0; y<40; y++){
if(Hoo[x][y]==til){
stroke(#cccccc);
fill(#cc00cc);
rect(y*grid_size,x*grid_size, grid_size, grid_size);
noFill();
}}}
if (agentState == RUNNING) {
makeRandomMove();
agentmove();
delay(100);
}
stroke(#0000ff);
fill(#0000ff);
ellipse(agent.x, agent.y, grid_size, grid_size);
}
void agentmove()
{
int a=(int)agent.x/grid_size;
int b=(int)agent.y/grid_size;
if(Hoo[a][b]==obs)
noLoop();
if(Hoo[a][b]==hole)
{
noStroke();
fill(#ffffff);
ellipse(agent.x, agent.y, grid_size, grid_size);
background(#000000);
}
}
void mouseClicked() {
if (agentState == STOPPED) {
agentState = RUNNING;
}
else {
agentState = STOPPED;
}
}
PVector getRandomLoc() {
return(new PVector(
((int)random(min_x,max_x+1)/grid_size)*grid_size,
((int)random(min_y,max_y+1)/grid_size)*grid_size));
}
void makeRandomMove() {
int direction = (int)random(0,4);
switch(direction) {
case 0: // north
agent.y -= grid_size;
if (agent.y < min_y) {
agent.y = max_y - grid_size;
}
break;
case 1: // west
agent.x -= grid_size;
if (agent.x < min_x) {
agent.x = max_x - grid_size;
}
break;
case 2: // south
agent.y += grid_size;
if (agent.y > max_y) {
agent.y = min_y;
}
break;
case 3: // east
agent.x += grid_size;
if (agent.x > max_x) {
agent.x = min_x;
}
break;
}
}