diff --git a/src/main/java/uta/cse3310/GridField.java b/src/main/java/uta/cse3310/GridField.java index c9187f4..0bcb65e 100644 --- a/src/main/java/uta/cse3310/GridField.java +++ b/src/main/java/uta/cse3310/GridField.java @@ -91,11 +91,42 @@ public void displayGrid() { public void placeRandomWords() { Random random = new Random(); for (String word : wordList) { - int len = word.length(); - int row = random.nextInt(grid.length); - int col = random.nextInt(grid[0].length); - Direction.Directions direction = Direction.Directions.values()[random.nextInt(Direction.Directions.values().length)]; - addWord(word, row, col, direction); + boolean wordPlaced = false; + while (!wordPlaced) { + int len = word.length(); + int row = random.nextInt(grid.length); + int col = random.nextInt(grid[0].length); + Direction.Directions direction = Direction.Directions.values()[random.nextInt(Direction.Directions.values().length)]; + if (canPlaceWord(word, row, col, direction)) { + addWord(word, row, col, direction); + wordPlaced = true; + } + } + } + } + + private boolean canPlaceWord(String word, int row, int column, Direction.Directions direction) { + int len = word.length(); + int dr = 0, dc = 0; + switch (direction) { + case HORIZONTAL: + dc = 1; + break; + case VERTICAL: + dr = 1; + break; + case DIAGONAL: + dr = 1; + dc = 1; + break; + } + for (int i = 0; i < len; i++) { + if (row < 0 || row >= grid.length || column < 0 || column >= grid[0].length || grid[row][column] != 0) { + return false; // Check if the word goes out of bounds or overlaps with existing letters + } + row += dr; + column += dc; } + return true; } }