首页 > 解决方案 > 试图限制基于图块的游戏中的移动

问题描述

NOOBIE问题...请帮忙!我正在构建一个基于图块的游戏,我正在左右上下移动一个图标。游戏的尺寸是 15 块 x 15 块。当我接近边界时,如何防止图标从“地图”上移开。我使用 W(上)A(左)S(下)和 D(右)进行定向输入。

一旦该图标达到 X 或 Y 轴上的最大点,有什么好方法可以防止该图标从地图上消失?我将 PlayerY 和 PlayerX 定义为玩家在地图上存在的点,但这是我目前用于移动的代码。

    if (choice.equals("w")){
        playerY--;
    }
    else if (choice.equals("s")){
        playerY++;
    }
    else if (choice.equals("d")){
        playerX++;
    }
    else if (choice.equals("a")){
        playerX--;
    }

你会放一些东西在这里你说像玩家处于最大值并且输入了d,什么都不做吗?但我不知道你会怎么说“什么都不做”......

if (player Y == 15 && choice.equals("d")){
   ________;
}

再次抱歉这个愚蠢的问题......我对Java比较陌生,但仍在努力了解自己的方向

标签: java

解决方案


在进行移动之前,您必须检查移动是否有效。如果移动有效,则移动它。如果没有,请不要移动,并可选择向玩家显示警告。

boolean isValidMove(choice){
    int nextX, nextY;
    if (choice.equals("w")){
        nextY = playerY-1;
    }
    else if (choice.equals("s")){
        nextY = playerY+1;
    }
    else if (choice.equals("d")){
        nextX = playerX+1;
    }
    else if (choice.equals("a")){
        nextX = playerX-1;
    }
    //immediately return false if X or Y out of board
    if(nextX<0||nextX>=15) return false;
    if(nextY<0||nextY>=15) return false;
    return true; //return true if nextX and nextY is in the board
}

在运行游戏的主要方法中:

choice = //user input
if(isValidMove(choice)){
   //do the move request and represent board game
} else{
   //optionally show a warning to players 
}

推荐阅读