简单的Java 2D阵列迷宫游戏
问题描述:
我正在做一个2D数组项目的迷宫游戏。到目前为止,我已经设法制作了一个随机游戏板。每次程序运行时,游戏板都是随机的。目标是让'P'(玩家)从右上角到'E'(结束)左下角,同时避开'X'和'*'。我需要帮助制作一种允许玩家输入向上,向下,向右,向左移动的方法。这是我到目前为止有:简单的Java 2D阵列迷宫游戏
public class MazeGame {
//Declare scanner to allow user to input directional commands
Scanner move = new Scanner(System.in);
public static void main(String[] args) {
//Call methods
Game_Beginning();
Game_Board();
}
//Intro to the game
public static void Game_Beginning(){
System.out.println("This is your game board:");
System.out.println("-------------------------------");
}
//Game Board
public static void Game_Board(){
//Declare new array, maze 10x10
char maze[][] = new char[10][10];
//Randomly print the obstacles in the maze.
for (int i = 0; i < maze.length; i++){
for (int j = 0; j < maze.length; j++){
double random = Math.random();
if (random <= .05){
maze[i][j] = '*';
}
else if (random > .06 && random <= .15){
maze[i][j] = 'X';
}
else{
maze[i][j] = '.';
}
maze[0][0] = 'P';
maze[9][9] = 'E';
System.out.print(maze[i][j]);
}
System.out.println("");
}
}
/**
* Add a method called "makePMove." Define char right, char left and so on
*/
public static void makeMove(){
int row;
int col;
System.out.print("Enter your move (Up-Down-Left-Right): ");
}
}
答
首先,你需要创建一个循环,并识别用户的命令。
1.确定你的阵列/板目标位置:所以,你可以,一旦你知道什么是你需要的所需方向的Game_Board()方法
while (true) {
String playerInput = move.next();
switch (playerInput) {
case "u" :
System.out.println("User command is 'up'");
break;
case "d" :
System.out.println("User command is 'down'");
break;
case "l" :
System.out.println("User command is 'left'");
break;
case "r" :
System.out.println("User command is 'right'");
break;
case "e" :
System.out.println("User command is 'exit'");
break;
case "y" :
System.out.println("User command is 'yes'");
break;
case "n" :
System.out.println("User command is 'no'");
break;
default:
System.out.println("Unknown command '" + playerInput + "'!");
}
}
然后之后添加这样的事情。
2.验证您的规则是否允许移动到目标位置
3.如果允许移动:
3.1。将'P'放入目标位置
3.2。放''。插入'P'的前一个位置
另外请确保您已经实现了用户退出的预期行为。
你应该保存'P'的位置,然后有一个'move()'方法来测试它们输入的方向。请记住检查索引是否超出范围,并适当地返回。 –
[Java命名约定](http://www.oracle.com/technetwork/java/codeconventions-135099.html)声明方法不应以大写字母开头,并且应该是动词(或至少以动词开头) 。此外,下划线通常只用于命名常量 - 而不是方法名称。 –
由于您的棋盘是纯粹随机生成的,因此不能保证迷宫是可以解决的。您应该考虑编写一些逻辑来验证迷宫是否可以解决,如果无法解决,可以生成一个新的逻辑。 –