0

I have this game where the user picks the position of the character and then the character starts moving randomly. I'm trying do make it that the character doesn't go out of bound, and if it does the system randomly picks a new position and the character moves 60 times then stops. Can someone please help

import java.util.*;

public class a1 {

public static String map[][] = new String[21][21];
public static int x;
public static int y;

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

    fillGrid();

    System.out.println("Enter starting (x,y) cooridinates for the player (0-20)");

    try (Scanner sc = new Scanner(System.in)) {
        System.out.print("Enter X position: ");
        x = sc.nextInt();

        System.out.print("Enter Y position: ");
        y = sc.nextInt();
    }
    map[x][y] = " ## "; // Letter to represent the location of the player
    movement();

}

public static void fillGrid() {
    // place a square in each space of the array(grid)
    for (int i = 0; i < map.length; i++) {
        for (int j = 0; j < map[i].length; j++) {
            map[i][j] = " |_| ";
        }
    }
}

public static void showMap() {
    // display the map
    for (int i = 0; i < map.length; i++) {
        for (int j = 0; j < map[i].length; j++) {
            System.out.print(map[i][j]);
        }
        System.out.print("\n");
    }

    System.out.print("\n");
    System.out.print("\n");
}

private static void movement() throws InterruptedException {

    Random rand = new Random();

    for (int i = 0; i < 10; i++) {

        i = rand.nextInt(4);
        map[x][y] = " |_| ";

        if (i == 0) {
            y = y + 1;
        } else if (i == 1) {
            y = y - 1;
        } else if (i == 2) {
            x = x + 1;
        } else if (i == 3) {
            x = x - 1;
        }

        map[x][y] = "  X  ";
        showMap();
        Thread.sleep(300);
    }

}

}

anan
  • 1
  • 1
    A) please see https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it ... and B) when asking about not working code, always provide a real [mcve]. – GhostCat Mar 19 '22 at 20:17

1 Answers1

0

You could clamp the players position to the bounds of your grid

x = clamp(sc.nextInt(), 0, 21);
y = clamp(sc.nextInt(), 0, 21);


int clamp(int val, int min, int max){
    return Math.max(min, Math.min(max, val));
}
Valerij Dobler
  • 1,848
  • 15
  • 25