简体   繁体   English

Java中的简单迷宫游戏

[英]simple maze game in java

I am creating a simple maze game in java. 我正在用Java创建一个简单的迷宫游戏。 The code reads a data file and assigns it to a String array . 该代码读取一个数据文件,并将其分配给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) . 玩家输入他或她想去的方向,并且每个位置包含对应于obstacleNumber (0, 1, or 2) points (0, 1, or 2)一定数量的points (0, 1, or 2) 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新手!

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? 您如何正确计算用户键入“ up, down, right, or left ”的次数以及用户到目前为止获得了多少分? Thank you in advance for your help I sincerely appreciate your time. 预先感谢您的帮助,我衷心感谢您的宝贵时间。

The moves arent count right, because countMoves doesnt increment the Variable moves from the main function. 移动计数正确,因为countMoves不会从主函数中增加Variable移动。 If you do : 如果您这样做:

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;

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);

I might be wrong here (early in the morning...) but I'm guessing you always get the same moves and points value? 我在这里可能是错的(清晨……),但我猜您总是得到相同的动作积分值吗? This is because you are not increasing the values of the actual moves and 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. 当您将Int作为参数发送给方法时,您不是在发送指向Int的指针,而是发送给它的一个副本,该副本将由该方法使用,然后在离开时删除。 You need to either return moves and points after increasing the values or put them as static attributes. 您需要在增加值后返回移动 ,或者将它们作为静态属性。 Try doing it this way instead: 尝试以这种方式进行操作:

...
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;
    }

In Java, arguments to methods are always passed by value . 在Java中,方法的参数始终 按value传递 It can get confusing with objects though. 它可能会与对象混淆 But with primitive types like int it's very simple. 但是,像int这样的原始类型非常简单。 To the functions countMoves and countPoints you are only giving the value of the moves and points , respectively, but not their reference. 该功能countMovescountPoints你只给价值movespoints分别,但不是他们的参考。 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: 例如,您可以这样做:

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. set变量是您在main中定义的变量。 Analogously for countPoints . 类似于countPoints Another possibility would be to define moves and points in the class Program12 and make the methods count methods modify these variables directly without passing them, like: 另一种可能性是在Program12类中定义movespoints ,并使方法count方法直接修改这些变量而不传递它们,例如:

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

In this case the moves moves defined in Program12 is visible to the countMoves and so you are changing directly the variable you want; 在这种情况下, countMoves可以看到Program12定义的移动moves ,因此您可以直接更改所需的变量。 there is no need to reset it. 无需重置。

-- -

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 GameState that keeps the variables moves and points or anything else shall you need it, and define there the count methods or other methods to modify the statistics of the game. 例如,您可以定义一个名为GameState的类,该类可保持变量的movespoints或您需要的其他任何东西,并在那里定义count方法或其他方法来修改游戏的统计信息。 Don't make the main method define the logic of the program. 不要让main方法定义程序的逻辑。 It should merely be used to read the input to initialize some sort of class Game and write to output the results of the Game . 它仅应用于读取输入以初始化某种类型的Game并写入以输出Game的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM