java java中的简单迷宫游戏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16030753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 21:40:47  来源:igfitidea点击:

simple maze game in java

javamaze

提问by maggie

I am creating a simple maze game in java. The code reads a data file and assigns it to a String array. The player inputs what direction he or she would like to go in and each position contains a certain number of points (0, 1, or 2)that corresponds to the obstacleNumber (0, 1, or 2). I want to keep track of the points as well as the number of times the player has moved but I cannot figure out where to call my methods to make sure that the counting is correct. I'm sorry if this is a really stupid question but I am new to java!

我正在用 Java 创建一个简单的迷宫游戏。该代码读取数据文件并将其分配给String array. 玩家输入他或她想要进入的方向,每个位置包含points (0, 1, or 2)obstacleNumber (0, 1, or 2). 我想跟踪点数以及玩家移动的次数,但我不知道在哪里调用我的方法以确保计数正确。如果这是一个非常愚蠢的问题,我很抱歉,但我是 Java 新手!

The array is being filled correctly but I cannot count the moves and points.

数组被正确填充,但我无法计算移动和点数。

    import java.util.*; 
    import java.io.File;

    public class Program12
     {

 static public void main( String [ ] args ) throws Exception
 {

     if(args.length != 1) {
         System.out.println("Error -- usage is: java Lab11 roomData.txt"); 
         System.exit(0); 
     }

    File newFile = new File(args[0]); 
    Scanner inputFile = new Scanner(newFile);       

    int numberOfRows = inputFile.nextInt();
    int numberOfColumns = inputFile.nextInt();  

    Room[][] game; 

    game = new Room[numberOfRows][numberOfColumns]; 
    int rowNumber = 0; 
    int columnNumber = 0; 

    int moves = 0;
    int points = 0;


    for(int i = 0; i < numberOfRows; i++) 
    {
        for (int j = 0; j < numberOfColumns; j++) 
        {
            String obstacle = inputFile.nextLine(); 
            int obstacleNumber = inputFile.nextInt(); 

            Room room = new Room(obstacle, obstacleNumber); 

            game[i][j] = room;

        }
        System.out.println(); 
        countPoints(obstacleNumber, points);

    }


    while(true) 
    {
        printPlayerLocation(numberOfRows, numberOfColumns, rowNumber, columnNumber);

        System.out.println();
        System.out.print("Enter up, down, left, or right to move:  ");
        Scanner userInput = new Scanner(System.in);
        String in = userInput.nextLine();
        if(in.equals("left") || in.equals("right") || in.equals("up") || in.equals("down"))
        {
            if (in.equalsIgnoreCase("up"))  
            { 
                rowNumber = rowNumber - 1; 
            } 

            if (in.equalsIgnoreCase("down")) 
            {           
                rowNumber = rowNumber + 1; 
            } 

            if (in.equalsIgnoreCase("left"))  
            {   
                columnNumber = columnNumber - 1;  
            } 

            if (in.equalsIgnoreCase("right"))  
            {   
                columnNumber = columnNumber + 1; 
            }
        }
        else
        {
            System.out.println("Input invalid! Please enter up, down, left, or right.");
        }

        try 
        {
            System.out.println(game[columnNumber][rowNumber].toString());
        }

        catch (ArrayIndexOutOfBoundsException e)
        {
            System.out.println("You cannot leave the boardwalk during the hunt! Please start over.");
            System.exit(0);     
        }

        countMoves(in, moves);
        //countPoints(obstacleNumber, points);
    }        
}

    public static void printPlayerLocation(int numberOfRows, int numberOfColumns, int rowNumber, int columnNumber)
    {
        System.out.println();
        System.out.print("***** PLAYER LOCATION *****");
        String[][] game = new String[numberOfRows][numberOfColumns];
        for (int i = 0; i < numberOfRows; i++)
        {
            for (int j = 0; j < numberOfColumns; j++)
            {
                game[i][j] = "*";
            }   
        }

        game[rowNumber][columnNumber] = "P";

        for (int i = 0; i < numberOfRows; i++)
        {
            System.out.println();
            for (int j = 0; j < numberOfColumns; j++)
            {
                System.out.printf("%-5s", game[i][j]);
            }   
        }
        System.out.println();
    }

    //doesn't correctly count the moves
    public static void countMoves(String in, int moves)
    {
        if(in.equals("left") || in.equals("right") || in.equals("up") || in.equals("down"))
        {
            moves++;
        }
        System.out.println("You have used " + moves + " moves.");
    }

    //doesn't correctly count the points
    public static void countPoints(int obstacleNumber, int points)
    {
        if(obstacleNumber == 0)
        {
            points = points;
        }
        if(obstacleNumber == 1)
        {
            points++;
        }
        if(obstacleNumber == 2)
        {
            points = points + 2;
        }
        System.out.println("You have obtained " + points + " points so far. Keep hunting!");
    }

The data file has the size of the array (4 4) and an obstacleNumber and obstacle

数据文件有数组的大小(4 4)和一个障碍编号和障碍

    0 this obstacleNumber would award 0 points
    1 this obstacleNumber would award 1 point
    2 this obstacleNumber would award 2 points

16 times to fill the array.

16 次填充数组。

I would like the sample output to print the player location (which it does correctly), ask the user to input a direction (which it does correctly), print the text in the data file (again already done) and then print the number of moves already used and the amount of points the player has gained so far.

我希望示例输出打印玩家位置(正确执行),要求用户输入方向(正确执行),打印数据文件中的文本(再次完成),然后打印已经使用的动作以及玩家到目前为止获得的点数。

How do you correctly calculate the number of times the user typed "up, down, right, or left" and how many points does the user have so far? Thank you in advance for your help I sincerely appreciate your time.

你如何正确计算用户输入“ up, down, right, or left”的次数以及用户目前有多少分?预先感谢您的帮助,我真诚地感谢您的时间。

回答by Lazy Senior

The moves arent count right, because countMoves doesnt increment the Variable moves from the main function. If you do :

移动算不上正确,因为 countMoves 不会从主函数增加变量移动。如果你这样做:

System.out.println(moves);
countMoves(in, moves);
System.out.println(moves);

You will see that the value didnt changed. So you could add a return value to countMoves and assingn moves with it :

你会看到值没有改变。所以你可以向 countMoves 添加一个返回值,并用它来分配移动:

moves = countMoves(in,moves);

Or you could increment the moves here :

或者你可以在这里增加移动:

if(in.equals("left") || in.equals("right") || in.equals("up") || in.equals("down"))
    {
        moves++;
        if (in.equalsIgnoreCase("up"))  
        {

            rowNumber = rowNumber - 1; 
        } 

        if (in.equalsIgnoreCase("down")) 
        {           
            rowNumber = rowNumber + 1; 
        } 

        if (in.equalsIgnoreCase("left"))  
        {   columnNumber = columnNumber - 1;  
        } 

        if (in.equalsIgnoreCase("right"))  
        {   columnNumber = columnNumber + 1; 
        }
    }

The same with Points i think. The line

我认为 Points 也是如此。线

points = points;

Would only make sense if you have a classvariable that would get the point value but assign a variable with its own value doenst make sense .

只有当您有一个类变量可以获取点值但分配一个具有自己的值的变量才有意义时才有意义。

So maybe add a return to the countPoints and assign points with it :

因此,也许可以为 countPoints 添加一个返回值并用它分配点数:

points = countPoints(obstacleNumber, points);

回答by juanmirocks

In Java, arguments to methods are alwayspassed by value. It can get confusing with objectsthough. But with primitive types like intit's very simple. To the functions countMovesand countPointsyou are only giving the value of the movesand points, respectively, but not their reference. That is, the methods are working in fact with another variable. This variable is initialized to the value you give in and you can change it as you want, but the changes made to this variable are only visible to the method. Therefore in order to make the changes visibile to the outer variables you must reset their values. For instance you could do this:

在 Java 中,方法的参数总是按值传递。但是,它可能会与对象混淆。但是对于像int它这样的原始类型非常简单。为了功能countMovescountPoints你只给的值moves,并points分别,但不是他们的参考。也就是说,这些方法实际上与另一个变量一起工作。此变量被初始化为您提供的值,您可以根据需要对其进行更改但对此变量所做的更改仅对方法可见。因此,为了使更改对外部变量可见,您必须重置它们的值。例如你可以这样做:

public static int countMoves(String in, int moves) {
       //... change the value of moves as you want
       return moves; //return the new value
}

And then use the method like:

然后使用如下方法:

moves = countMoves(in, moves);

Where the set variable is the one you define in main. Analogously for countPoints. Another possibility would be to define movesand pointsin the class Program12and make the methods countmethods modify these variables directly without passing them, like:

其中 set 变量是您在 main 中定义的变量。类似地对于countPoints。另一种可能性是在类中定义moves和并使方法方法直接修改这些变量而不传递它们,例如:pointsProgram12count

public static void countMoves(String in) {
    moves = ...
}

In this case the moves movesdefined in Program12is visible to the countMovesand so you are changing directly the variable you want; there is no need to reset it.

在这种情况下,moves定义的移动对Program12可见countMoves,因此您可以直接更改所需的变量;无需重置它。

--

——

But big but. The code you have is rather spaghetti. You should think how to better structure and compartmentalize the code into closely-related logical units. In object-oriented programming you do it with classes. For example, you could define a class called GameStatethat keeps the variables movesand pointsor anything else shall you need it, and define there the countmethods or other methods to modify the statistics of the game. Don't make the mainmethod define the logic of the program. It should merely be used to read the input to initialize some sort of class Gameand write to output the results of the Game.

不过大不过。您拥有的代码很像意大利面条。您应该考虑如何更好地组织代码并将其划分为密切相关的逻辑单元。在面向对象的编程中,您可以使用类来完成。例如,您可以定义一个名为的类GameState来保存变量moves和/points或其他任何您需要的东西,并在那里定义count方法或其他方法来修改游戏的统计数据。不要让main方法定义程序的逻辑。它应该仅用于读取输入以初始化某种类Game并写入以输出Game.

回答by patrick.elmquist

I might be wrong here (early in the morning...) but I'm guessing you always get the same movesand pointsvalue? This is because you are not increasing the values of the actual movesand points. When you send an Int as a parameter to a method you are not sending a pointer to the Int but a copy of it which will be used by the method and then removed when leaving it. You need to either return movesand pointsafter increasing the values or put them as static attributes. Try doing it this way instead:

我在这里可能是错的(清晨......)但我猜你总是得到相同的动作值?这是因为您没有增加实际移动的值。当您将 Int 作为参数发送给方法时,您发送的不是指向 Int 的指针,而是它的副本,该副本将被该方法使用,然后在离开时将其删除。您需要在增加值后返回移动,或者将它们作为静态属性。尝试这样做:

...
moves = countMoves(String in, int moves);
...

public static int countMoves(String in, int moves) {
    if(in.equals("left") || in.equals("right") || in.equals("up") || in.equals("down")) {
        moves++;
    }
    System.out.println("You have used " + moves + " moves.");
    return moves;
}

Or you could increase them when identifying the moving direction (which is more efficient since you don't have to redo the check if the move was valid):

或者您可以在确定移动方向时增加它们(这样效率更高,因为您不必重新检查移动是否有效):

if (in.equalsIgnoreCase("up")) { 
    rowNumber = rowNumber - 1; 
    moves++;
}
...

EDIT
Points Problem:
Since you didn't post how Room is implemented I just improvise, but I figure it should look something like this:

编辑
点问题:
由于您没有发布 Room 是如何实现的,我只是即兴创作,但我认为它应该是这样的:

...  
points = countPoints(game[rowNumber][columnNumber].getObstacleNumber(), points);
...

and change countPoints() to:

并将 countPoints() 更改为:

public static int countPoints(int obstacleNumber, int points) {
        if(obstacleNumber == 0) points = points;
        if(obstacleNumber == 1) points++;
        if(obstacleNumber == 2) points += 2;

        System.out.println("You have obtained " + points + " points so far. Keep hunting!");
        return points;
    }

or just (provided you know that the input is correct):

或者只是(前提是您知道输入是正确的):

public static int countPoints(int obstacleNumber, int points) {
        points += obstableNumber;
        System.out.println("You have obtained " + points + " points so far. Keep hunting!");
        return points;
    }