dimanche 27 mai 2018

How can I make an algorithm that will randomly put 1's in a 2d array while making sure there's a path from the bottom left to the top right space?

I am trying to make a simple java game where the player cannot see the world (a 2d array) and has to enter "right," "left," "up," or "down." The player has to get from the bottom left to the top right in a certain time. The array will be full of 0's and 1's will be assigned randomly, while making sure there's a path between the start and end. This is what I have so far:

public class PathMaker {

    private int [][]arr;

    public PathMaker(int Difficulty){
        if (Difficulty == 1)
            arr = new int[5][5];
        if (Difficulty == 2)
            arr = new int[5][5];
        if (Difficulty == 3)
            arr = new int[5][5];
        Pathset(arr);
    }

    private static void Pathset(int [][]arr){
        int length = arr.length;
        int trees = (length-1)*2;
        int a, b;
        int check = 0;
        arr[0][0] = 1;
        for (int i = 0; i < trees; i++){
            a = (int)((Math.random()*length)+1);
            b = (int)((Math.random()*length)+1);
            while(check == 0){
                if (((arr[a+1][b] == 0) && (arr[a][b+1] == 0)) || a == 1 || b == 1)
                    check = 1;
                a = (int)((Math.random()*length)+1);
                b = (int)((Math.random()*length)+1);
            }
            arr[a][b] = 1;
        }
    }
}




Aucun commentaire:

Enregistrer un commentaire