Java
javaTutorial
Java implementation of random word generation and placement guide for game word search board
Java implementation of random word generation and placement guide for game word search board

This tutorial details how to generate a specified number of unique random words for a game board in Java. The content covers initialization of the word pool, user input validation, unique word selection mechanism based on `java.util.Random`, and a general method to integrate these words into the `WordSearch` game board. With this guide, developers will master the core randomization logic of building dynamic word games.
When developing applications such as word searches, crossword puzzles, or any application that requires dynamic word content, randomly picking and placing words from a preset word list is a common requirement. This tutorial will walk you through this process, focusing on how to ensure that the words you pick are unique, and provide a common way to integrate these words into the game board (such as the WordSearch class).
1. Build a word pool
First, we need a collection of words as our randomly selected source. This is usually defined by an array of strings, which is then converted into a List
1.1 Define the original word array
You can define an array of strings containing all possible words. For example:
String[] wordsArray = {
"play", "dream", "personal", "advice", "steal",
"suspicious", "borrow", "image", "repeat", "enemy",
"break", "selfish", "protester", "charity", "encounter",
"discreetly", "effectively", "react", "respect", "depression",
"couch", "counsellor", "snatch", "judge", "appearance",
"quiet", "ridiculous", "overjoyed", "antidote", "parademic",
"employment", "balance", "overwhelm", "relax", "flextime",
"task", "daily", "realistic", "essential", "stressful",
"fixed", "key", "reward", "salary", "loan", "promotion",
"value", "database", "schedule", "priority"
};
1.2 Encapsulated as a Word object list
In order to better manage words, especially when each word may need to store additional information (such as position on the game board, orientation, etc.), it is recommended to create a Word class to encapsulate this information. Then, each word in the string array is converted to a Word object and stored in an ArrayList.
Word class example:
// Assume the Word class is as follows, you can add more attributes as needed class Word {
private String value;
// More properties can be added here, for example:
// private int startRow;
// private int startCol;
// private Direction direction; // An enumeration type representing the direction of the word public Word(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return value;
}
}
Initialize the word pool:
List<word> poolWords = new ArrayList();
for (String wordStr : wordsArray) {
poolWords.add(new Word(wordStr));
}</word>
2. User input and validity verification
Before the game starts, the user is usually allowed to specify some parameters, such as how many words they wish to place on the game board. For the robustness of the program, we need to obtain the user's input and verify its validity to ensure that it is within a reasonable range.
import java.util.Scanner;
// ... (inside the readWords method or where appropriate)
Scanner input = new Scanner(System.in);
int maxWords;
do {
System.out.print("How many words should be generated? (Maximum 12): ");
maxWords = input.nextInt();
if (maxWords 12) {
System.out.println("Invalid input, please choose between 1 and 12.");
}
} while (maxWords 12);
// input.close(); // In practical applications, Scanner is usually closed when no longer needed
The above code uses a do-while loop to ensure that the number of words entered by the user is between 1 and 12. If the input is invalid, it prompts the user to re-enter it until a valid value is obtained.
3. Implement unique random word selection
This is the core logic. We need to randomly select a specified number of words from the word pool, and make sure that each word is only selected once. The key to achieving this is to remove the word from the word pool after each selection.
import java.util.Random;
// ... (inside the readWords method or where appropriate)
Random rand = new Random();
List<word> selectedWords = new ArrayList(); // Store the final selected words for (int i = 0; i <p> This code loops maxWords times, each time randomly selecting a word from poolWords and then immediately removing it from poolWords. This ensures that the words selected each time are unique.</p>
<h3> 4. Integrate words into the game board (WordSearch class)</h3>
<p> Once we have a unique set of randomly chosen words, the next step is to place them on the game board. This usually involves the design of a WordSearch class (or other game board class). Since the actual word placement logic (such as selecting starting position, direction, collision detection, etc.) can be very complex, this tutorial will focus on how to pass the selected word to the WordSearch instance.</p>
<p> <strong>WordSearch class concept example:</strong></p>
<pre class="brush:php;toolbar:false"> // Assume that the WordSearch class is as follows class WordSearch {
private char[][] board;
private int rows;
private int cols;
public WordSearch(int rows, int cols) {
this.rows = rows;
this.cols = cols;
this.board = new char[rows][cols];
// Initialize the game board, e.g. fill it with empty characters or specific placeholders for (int i = 0; i <p> <strong>Example of readWords method integrating all code:</strong></p><pre class="brush:php;toolbar:false"> import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class WordGeneratorAndPlacer {
// Assume that the Word class and WordSearch class have been defined as above public static void readWords() {
// Initialize the WordSearch game board (for example, a 10x10 board)
WordSearch search = new WordSearch(10, 10);
List<word> poolWords = new ArrayList();
String[] wordsArray = {
"play", "dream", "personal", "advice", "steal",
"suspicious", "borrow", "image", "repeat", "enemy",
"break", "selfish", "protester", "charity", "encounter",
"discreetly", "effectively", "react", "respect", "depression",
"couch", "counsellor", "snatch", "judge", "appearance",
"quiet", "ridiculous", "overjoyed", "antidote", "parademic",
"employment", "balance", "overwhelm", "relax", "flextime",
"task", "daily", "realistic", "essential", "stressful",
"fixed", "key", "reward", "salary", "loan", "promotion",
"value", "database", "schedule", "priority"
};
// Convert the string array to a list of Word objects for (String wordStr : wordsArray) {
poolWords.add(new Word(wordStr));
}
Random rand = new Random();
Scanner input = new Scanner(System.in);
// Get the number of words entered by the user and verify them int maxWords;
do {
System.out.print("How many words should be generated? (Maximum 12): ");
maxWords = input.nextInt();
if (maxWords 12) {
System.out.println("Invalid input, please choose between 1 and 12.");
}
} while (maxWords 12);
// Randomly select a unique word and try to place it on the game board System.out.println("\nStart selecting and placing words:");
for (int i = 0; i <h3> 5. Precautions and best practices</h3>
<ul>
<li> <strong>Design of Word class:</strong> According to your game needs, Word class can contain more attributes, such as the starting coordinates of the word, direction, whether it has been found, etc.</li>
<li> <strong>Complexity of WordSearch:</strong> The actual word placement logic of the word search board is far more complex than the tryAddWord method in this tutorial demonstrates. It requires considering algorithms to find suitable gaps, handle collisions, ensure word readability, and support multiple orientations (horizontal, vertical, diagonal).</li>
<li> <strong>Error handling:</strong> Consider the case where the word pool is empty. Before trying poolWords.get(randomIndex), it's better to check poolWords.isEmpty() to avoid IndexOutOfBoundsException.</li>
<li> <strong>Resource management:</strong> Make sure to call the close() method after using the Scanner object to release system resources.</li>
<li> <strong>Performance:</strong> For very large word pools and large word selections, the performance of the ArrayList.remove() operation decreases linearly with list size (because it may need to move subsequent elements). If performance becomes a bottleneck, consider using a HashSet for initial deduplication, or a more complex random sampling algorithm. However, for the selection of up to 12 words in this example, this method is completely sufficient.</li>
</ul>
<h3> Summarize</h3>
<p> This tutorial details the complete process of generating a specified number of unique random words for a game board in Java. We start by building a word pool and manage word data through ArrayList and custom Word classes. Next, we implemented user input validation to ensure that a valid number of words was obtained. The core part is to use the java.util.Random and ArrayList.remove() methods to efficiently select unique words. Finally, we discuss how to integrate these words into the WordSearch game board and provide a conceptual WordSearch class example that highlights the complexity of actual placement logic. Mastering these techniques will help you build dynamic and engaging content for all types of word games.</p></word>The above is the detailed content of Java implementation of random word generation and placement guide for game word search board. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20518
7
13631
4
How to configure Spark distributed computing environment in Java_Java big data processing
Mar 09, 2026 pm 08:45 PM
Spark cannot run in local mode, ClassNotFoundException: org.apache.spark.sql.SparkSession. This is the most common first step of getting stuck: even the dependencies are not correct. Only spark-core_2.12 is written in Maven, but spark-sql_2.12 is not added. SparkSession crashes as soon as it is built. The Scala version must strictly match the official Spark compiled version - Spark3.4.x uses Scala2.12 by default. If you use spark-sqljar of 2.13, the class loader cannot directly find the main class. Practical advice: Go to mvnre
How to safely map user-entered weekday string to integer value and implement date offset operation in Java
Mar 09, 2026 pm 09:43 PM
This article introduces a concise and maintainable way to map the weekday string (such as "Monday") to the corresponding serial number (1-7), and use the modulo operation to realize the forward and backward offset of any number of days (such as Monday plus 4 days to get Friday), avoiding lengthy if chains and hard-coded logic.
How to generate a list of duplicate elements using Java's Collections.nCopies_Initialization tips
Mar 06, 2026 am 06:24 AM
Collections.nCopies returns an immutable view. Calling add/remove will throw UnsupportedOperationException; it needs to be wrapped with newArrayList() to modify it, and it is disabled for mutable objects.
What is exception masking (Suppressed Exceptions) in Java_Multiple resource shutdown exception handling
Mar 10, 2026 pm 06:57 PM
What is SuppressedException: It is not "swallowed", but actively archived by the JVM. SuppressedException is not an exception loss, but the JVM quietly attaches the secondary exception to the main exception under the premise that "only one exception must be thrown" for you to verify afterwards. It is automatically triggered by the JVM in only two scenarios: one is that the resource closure in try-with-resources fails, and the other is that you manually call addSuppressed() in finally. The key difference is: the former is fully automatic and safe; the latter requires you to keep it to yourself, and it can be written as shadowing if you are not careful. try-
How to use Homebrew to install Java on Mac_A must-have Java tool chain for developers
Mar 09, 2026 pm 09:48 PM
Homebrew installs the latest stable version of openjdk (such as JDK22) by default, not the LTS version; you need to explicitly execute brewinstallopenjdk@17 or brewinstallopenjdk@21 to install the LTS version, and manually configure PATH and JAVA_HOME to be correctly recognized by the system and IDE.
How to correctly implement runtime file writing in Java applications (avoiding JAR internal write failures)
Mar 09, 2026 pm 07:57 PM
After a Java application is packaged as a JAR, data cannot be written directly to the resources in the JAR package (such as test.txt) because the JAR is essentially a read-only ZIP archive; the correct approach is to write variable data to an external path (such as a user directory, a temporary directory, or a configuration-specified path).
What is the underlying principle of array expansion in Java_Java memory dynamic adjustment analysis
Mar 09, 2026 pm 09:45 PM
ArrayList.add() triggers expansion because grow() is called when size is equal to elementData.length. The first add allocates 10 capacity, and subsequent expansion is 1.5 times and not less than the minimum requirement, relying on delayed initialization and System.arraycopy optimization.
How to safely read a line of integer input in Java and avoid Scanner blocking
Mar 06, 2026 am 06:21 AM
This article introduces typical blocking problems when using Scanner to read multiple integers in a single line. It points out that hasNextInt() will wait indefinitely when there is no subsequent input, and recommends a safe alternative with nextLine() string splitting as the core.





