From bacd12fdba2c2b381c3f4ea6dd239c210e8596cb Mon Sep 17 00:00:00 2001 From: 2onefan2 <159247397+2onefan2@users.noreply.github.com> Date: Sat, 27 Apr 2024 21:39:06 -0500 Subject: [PATCH] Added functionality to randomly place words from the word list on the grid while ensuring they remain intact --- src/main/java/uta/cse3310/GridField.java | 41 +++++++++++++++++++++--- 1 file changed, 36 insertions(+), 5 deletions(-) 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; } }