Skip to content

Commit

Permalink
Added functionality to randomly place words from the word list on the…
Browse files Browse the repository at this point in the history
… grid while ensuring they remain intact
  • Loading branch information
2onefan2 committed Apr 28, 2024
1 parent ff14eba commit bacd12f
Showing 1 changed file with 36 additions and 5 deletions.
41 changes: 36 additions & 5 deletions src/main/java/uta/cse3310/GridField.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}

0 comments on commit bacd12f

Please sign in to comment.