java - 试图限制基于图块的游戏中的移动
问题描述
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比较陌生,但仍在努力了解自己的方向
解决方案
在进行移动之前,您必须检查移动是否有效。如果移动有效,则移动它。如果没有,请不要移动,并可选择向玩家显示警告。
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
}
推荐阅读
- flutter - pub 获取失败(1;可运行的程序或批处理文件。)
- amazon-web-services - 计算优化实例和加速计算实例的区别
- gstreamer - GStreamer 的 rtspsrc 元素可以通过 DESCRIBE 请求的身份验证标头吗?
- reactjs - 带有打字稿的formik在withFormik HOC中设置了初始值
- javascript - npm install 后,依赖项被忽略并从 package-lock.json 中删除
- python - 熊猫应用有条件的功能
- reactjs - 从 Firebase 实时数据库中获取当前值的键
- python - 如何将嵌入广播到不同的服务器不和谐 python
- java - Error while adding ImageView[] array to BorderPane in JavaFX
- java - 构建二叉树并将其转换为可以在 Java 中保存空值的数组