我正在为2D阵列项目制作迷宫游戏。到目前为止,我已经成功制作了一个随机游戏板。每次运行程序时,游戏板都是随机的。目标是让'P'(玩家)从右上角到'E'(结束)左下角,同时避免'X'和'*'。我需要帮助制作一种方法,允许玩家输入Up,Down,Right,Left并使P移动。这就是我到目前为止所做的:
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): ");
}
}
答案 0 :(得分:0)
首先,您需要创建一个循环并识别用户命令。所以你可以在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 + "'!");
}
}
然后,一旦你知道你需要的方向是什么:
1.确定阵列/电路板中的目标位置
2.验证您的规则是否允许移动到目标位置
3.如果允许移动:
3.1。把P&#39; P&#39;进入目标位置
3.2。放&#39;。&#39;进入以前的位置&#39; P&#39;
还要确保已实现用户退出的预期行为。