Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Recursive Assistance with a Word Puzzle Game

  1. #1
    Junior Member
    Join Date
    Oct 2012
    Posts
    6
    Thanks
    3
    Thanked 1 Time in 1 Post

    Default Recursive Assistance with a Word Puzzle Game

    Hey gang:

    The goal of this assignment is too develop a recursive method with a helper method to loop through a word puzzle board of 20 x 20 with a given list of words and 'Search' the word. IF the word is found, THEN highlight the word red. This is done for all the words in the word list. The problem arises with the code I have written. When I compile it, the board appears. When I press the 'Search' button, all the letters 'A' highlight red and the console returns AB. Every time I press the 'Search' button, AB keeps appearing on the console and other words are never checked to see if they appear on the board.

    I am trying to write a recursive method and helper method that searches the word one by one in every direction possible (up, down, left, right, up left, down left, up right, down right) but only the first letter of the word ABSTRACTION is done. any way to improve my recursive and helper method?

    Just so you don't have to search the whole code, the recursive/helper function/method is found before line 142 in class WordSearchFrame

    I have included two java files. i also included two txt files. my professor wants me to use the command line arguments, so i saved them in my C drive and named them

    args[0] = "C:\\projects\\wordsearch.txt";
    args[1] = "C:\\projects\\wordlist.txt";

    You can save it and name the file whatever u want. i just choose projects for mine.

    i appreciate any advice. (whether its about code cleanliness or anything else to improve the code)

    public class WordSearchException extends RuntimeException {
     
    	private static final long serialVersionUID = 1L;
     
    	/**
    	 * Default constructor
    	 */
    	public WordSearchException() {
     
    	}
     
    	/**
    	 * Constructor with an error message
    	 * 
    	 * @param reason
    	 *            The error message for the exception
    	 */
    	public WordSearchException(String reason) {
    		super(reason);
    	}
    }

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.Set;
    import java.util.StringTokenizer;
     
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingConstants;
    import javax.swing.border.EtchedBorder;
    import javax.swing.border.TitledBorder;
     
    public class WordSearchFrame extends JFrame {
     
    	private static final long serialVersionUID = 1L;
     
    	// The number of columns in the word list
    	private static final int COLS_IN_WORDLIST = 1;
     
    	// The width of the frame
    	private static final int FRAME_WIDTH = 640;
     
    	// The height of the frame
    	private static final int FRAME_HEIGHT = 480;
     
    	// The grid used in the word search
    	private JLabel[][] wordSearch;
     
    	// The labels used to display the words in the word list
    	private JLabel[] wordListLabels;
     
    	// The panel that the word list is inside
    	private JPanel wordListPanel;
     
    	// The panel that the word search is inside
    	private JPanel wordsearchPanel;
     
    	// The panel on the right hand side
    	private JPanel rightSidePanel;
     
    	// The panel on the left hand side
    	private JPanel leftSidePanel;
     
    	// The panel that the search button is inside
    	private JPanel searchButtonPanel;
     
    	// The search button
    	private JButton searchButton;
     
    	// The number of rows in the word search
    	private int numRows;
     
    	// The number of columns in the word search
    	private int numCols;
     
    	// The listener for the search button
    	private ActionListener searchButtonListener;
     
    	// The list of words to be found in the word search
    	// If this line won't compile in Java 1.4.2, change it to
    	// private ArrayList wordList;
    	private ArrayList<String> wordList;
     
    	private Set foundWords = new HashSet();
     
    	// boolean isOnBoard = searchBegin(word, 0, 0);
     
    	/**
    	 * The listener for the search button
    	 */
    	class SearchListener implements ActionListener {
    		/**
    		 * This event handler causes the current word in the word list to be
    		 * colored in red and finds the word in the word search
    		 * 
    		 * @param event
    		 *            The event corresponding to the search button being clicked
    		 */
    		public void actionPerformed(ActionEvent event) {
     
    			wordListLabels[0].setForeground(Color.RED);
    		        System.out.println(wordListLabels[0].getText().charAt(0));
    			System.out.println(wordSearch[0][0].getText());
     
    			wordListLabels[0].setForeground(Color.RED);
    			locateWord(wordListLabels[0]);
    	}
    		public void locateWord(JLabel currentWord)
    		{
    			for (int i = 0; i < numRows; i++)
    				for (int j = 0; j < numCols; j++)
    				{
    					if (wordSearch[i][j].getText().charAt(0) == currentWord.getText().charAt(0))
    					{
    						//WordSearchFrame.this.locateWord(currentWord, i, j, new boolean[numRows][numCols]);
    						wordSearch[i][j].setForeground(Color.RED);
    					}
    				}				
    		}
     
    	}		
    		public void locateWord(JLabel currentWord, int currentRow, int currentCol) //, boolean[][] visited
    		{
    			boolean found = false;
     
    			if (currentWord.getText().contains(wordSearch[currentRow][currentCol].getText())) {
    				if (foundWords.add(currentWord)) {
    					found = true;
    				}
    				else
    				{
    					//visited[currentRow][currentCol] = true;
     
    					locateWord(currentWord, currentRow+1, currentCol);
    					locateWord(currentWord, currentRow-1, currentCol); 
    					locateWord(currentWord, currentRow, currentCol+1); 
    					locateWord(currentWord, currentRow, currentCol-1);
    					locateWord(currentWord, currentRow+1, currentCol+1);
    					locateWord(currentWord, currentRow-1, currentCol+1); 
    					locateWord(currentWord, currentRow+1, currentCol-1);
    					locateWord(currentWord, currentRow-1, currentCol-1);
     
    				}
     
    				if (found)
    					wordSearch[currentRow][currentCol].setForeground(Color.RED);
     
     
    				if (currentRow < 0 || currentRow >= numRows || currentCol < 0 || currentCol >= numCols)
    					return;
    			}
     
    }
     
    	/**
    	 * Builds the panel on the left hand side, which consists of the word search
    	 * 
    	 * @throws WordSearchException
    	 *             Throws a WordSearchException if the word search file isn't in
    	 *             the proper format
    	 * @throws IOException
    	 *             Throws an IOException if loading the word search file has
    	 *             problems
    	 */
    	private void buildLeftSidePanel() throws WordSearchException, IOException {
    		// Create leftSidePanel
    		leftSidePanel = new JPanel();
    		leftSidePanel.setLayout(new BorderLayout());
    		leftSidePanel.setBorder(new TitledBorder(new EtchedBorder(),
    				"Word Search"));
     
    		// Build wordsearch panel
    		wordsearchPanel = new JPanel();
    		wordsearchPanel.setLayout(new GridLayout(numRows, numCols));
    		leftSidePanel.add(wordsearchPanel, BorderLayout.CENTER);
     
    		// Add leftSidePanel panel to main frame
    		this.getContentPane().add(leftSidePanel, BorderLayout.CENTER);
    	}
     
    	/**
    	 * Determines the number of columns and rows in the word search file.
    	 * 
    	 * @param wordSearchFilename
    	 *            The file name of the word search file
    	 * @throws WordSearchException
    	 *             Throws a WordSearchException if the word search file isn't in
    	 *             the proper format
    	 * @throws IOException
    	 *             Throws an IOException if loading the word search file has
    	 *             problems
    	 */
    	private void initGridFromFile(String wordSearchFilename)
    			throws WordSearchException, IOException {
    		this.numRows = 0;
    		this.numCols = 0;
    		BufferedReader reader = new BufferedReader(new FileReader(
    				wordSearchFilename));
    		String line = reader.readLine();
    		while (line != null) {
    			StringTokenizer tokenizer = new StringTokenizer(line, " ");
    			if (this.numCols == 0) {
    				this.numCols = tokenizer.countTokens();
    			} else {
    				if (tokenizer.countTokens() != this.numCols) {
    					throw new WordSearchException(
    							"Invalid number of columns in word search");
    				}
    			}
    			line = reader.readLine();
    			this.numRows++;
    		}
    		reader.close();
    		this.wordSearch = new JLabel[numRows][numCols];
    	}
     
    	/**
    	 * Loads the contents of the word search into the JLabels of the word search
    	 * grid in the GUI
    	 * 
    	 * @param wordSearchfilename
    	 *            The name of the word search file
    	 * @throws IOException
    	 *             Throws an IOException if loading the word search file has
    	 *             problems
    	 */
    	protected void loadGridFromFile(String wordSearchFilename)
    			throws IOException {
    		int row = 0;
    		BufferedReader reader = new BufferedReader(new FileReader(
    				wordSearchFilename));
    		String line = reader.readLine();
    		while (line != null) {
    			StringTokenizer tokenizer = new StringTokenizer(line, " ");
    			int col = 0;
    			while (tokenizer.hasMoreTokens()) {
    				String tok = tokenizer.nextToken();
    				wordSearch[row][col] = new JLabel(tok);
    				wordSearch[row][col].setForeground(Color.BLACK);
    				wordSearch[row][col]
    						.setHorizontalAlignment(SwingConstants.CENTER);
    				wordsearchPanel.add(wordSearch[row][col]);
    				col++;
    			}
    			line = reader.readLine();
    			row++;
    		}
    		reader.close();
    	}
     
    	/**
    	 * Builds the right hand side panel which contains the list of words in the
    	 * word search and the search button
    	 */
    	private void buildRightSidePanel() {
    		// Build the panel on the right side
    		rightSidePanel = new JPanel();
    		rightSidePanel.setBorder(new TitledBorder(new EtchedBorder(),
    				"Word List"));
    		rightSidePanel.setLayout(new BorderLayout());
     
    		// Build the word list
    		wordListLabels = new JLabel[wordList.size()];
    		wordListPanel = new JPanel();
    		wordListPanel.setLayout(new GridLayout(wordList.size(), 1));
    		for (int i = 0; i < this.wordList.size(); i++) {
    			// If the line below won't compile in Java 1.4.2, make it
    			// String word = (String)this.wordList.get(i);
    			String word = this.wordList.get(i);
    			wordListLabels[i] = new JLabel(word);
    			wordListLabels[i].setForeground(Color.BLUE);
    			wordListLabels[i].setHorizontalAlignment(SwingConstants.CENTER);
    			wordListPanel.add(wordListLabels[i]);
    		}
    		rightSidePanel.add(wordListPanel, BorderLayout.CENTER);
     
    		// Add search button
    		searchButton = new JButton("Search");
    		searchButtonListener = new SearchListener();
    		searchButton.addActionListener(searchButtonListener);
    		searchButtonPanel = new JPanel();
    		searchButtonPanel.add(searchButton);
    		rightSidePanel.add(searchButtonPanel, BorderLayout.SOUTH);
     
    		// Add rightSidePanel to main panel
    		this.getContentPane().add(rightSidePanel, BorderLayout.EAST);
    	}
     
    	/**
    	 * Loads the list of words to find in the word search
    	 * 
    	 * @param wordListFilename
    	 *            The file name of the file containing the list of words
    	 * @throws WordSearchException
    	 *             Throws a WordSearchException if the word search file isn't in
    	 *             the proper format
    	 * @throws IOException
    	 *             Throws an IOException if loading the word search file has
    	 *             problems
    	 */
    	private void loadWordList(String wordListFilename)
    			throws WordSearchException, IOException {
    		int row = 0;
     
    		// If this line won't compile under Java 1.4.2 change it to
    		// this.wordList = new ArrayList();
    		wordList = new ArrayList<String>();
    		BufferedReader reader = new BufferedReader(new FileReader(
    				wordListFilename));
    		String line = reader.readLine();
    		while (line != null) {
    			StringTokenizer tokenizer = new StringTokenizer(line, " ");
    			if (tokenizer.countTokens() != COLS_IN_WORDLIST) {
    				throw new WordSearchException(
    						"Error: only one word per line allowed in the word list");
    			}
    			String tok = tokenizer.nextToken();
    			// If this line won't compile, change it to
    			// wordList.add((Object)tok)
    			wordList.add(tok);
    			line = reader.readLine();
    			row++;
    		}
    		reader.close();
    	}
     
    	/**
    	 * Constructor for the WordSearchFrame
    	 * 
    	 * @param wordSearchFilename
    	 *            The name of the word search file
    	 * @param wordListFilename
    	 *            The name of the word list file
    	 * @throws IOException
    	 *             Throws an IOException if loading the word search file has
    	 *             problems
    	 * @throws WordSearchException
    	 *             Throws a WordSearchException if the word search file isn't in
    	 *             the proper format
    	 */
    	public WordSearchFrame(String wordSearchFilename, String wordListFilename)
    			throws IOException, WordSearchException {
    		this.setSize(FRAME_WIDTH, FRAME_HEIGHT);
    		this.getContentPane().setLayout(new BorderLayout());
    		this.initGridFromFile(wordSearchFilename);
    		buildLeftSidePanel();
    		this.loadGridFromFile(wordSearchFilename);
    		loadWordList(wordListFilename);
    		buildRightSidePanel();
    	}
     
    	/**
    	 * Constructor which takes a wordSearch 2D String array and a wordList String array
    	 * @param wordSearch The word search represented as a 2D String array
    	 * @param wordList The list of words to search for
    	 * @throws IOException Throws an IOException if loading the word search file has
    	 *             problems
    	 * @throws WordSearchException  Throws a WordSearchException if the word search file isn't in
    	 *             the proper format
    	 */
    	public WordSearchFrame(String[][] wordSearch, String[] wordList)
    			throws IOException, WordSearchException {
    		this.setSize(FRAME_WIDTH, FRAME_HEIGHT);
    		this.getContentPane().setLayout(new BorderLayout());
    		this.numRows = wordSearch.length;
    		this.numCols = wordSearch[0].length;
    		this.wordSearch = new JLabel[this.numRows][this.numCols];
    		buildLeftSidePanel();
    		for( int row = 0; row < this.numRows; row++ ) {
    			for( int col = 0; col < this.numCols; col++ ) {
    				this.wordSearch[row][col] = new JLabel(wordSearch[row][col]);
    				this.wordSearch[row][col].setForeground(Color.BLACK);
    				this.wordSearch[row][col]
    						.setHorizontalAlignment(SwingConstants.CENTER);
    				this.wordsearchPanel.add(this.wordSearch[row][col]);
    			}
    		}
     
     
    		// If this line won't compile under Java 1.4.2 change it to
    		// this.wordList = new ArrayList();
    		this.wordList = new ArrayList<String>();
    		for( int i = 0; i < wordList.length; i++ ) {
    			// If this line won't compile, change it to
    			// this.wordList.add((Object)wordList[i])
    			this.wordList.add(wordList[i]);
    		}
    		buildRightSidePanel();
    	}
     
    	/**
    	 * @param args
    	 *            The first argument is the word search file, the second
    	 *            argument is the word list.
    	 */
    	public static void main(String[] args) {
    		args[0] = "C:\\projects\\wordsearch.txt";
    		args[1] = "C:\\projects\\wordlist.txt";
     
    		try {
    			if (args.length != 2) {
    				System.out.println("Command line arguments: <word search file> <word list>");
    			} else {
    				WordSearchFrame frame = new WordSearchFrame(args[0], args[1]);
    				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    				frame.setVisible(true);
    			}
    		} catch (Exception e) {
    			System.out.println(e.getMessage());
    			e.printStackTrace();
    		}
    	}
    }

    this are the two txt files, not java files. this first one is called wordlist.txt

    ABSTRACTION
    DEBUGGER
    ECLIPSE
    ENCAPSULATION
    EXCEPTION
    INHERITANCE
    INTERFACE
    ITERATION
    JAVA
    METHOD
    POLYMORPHISM
    RECURSION
    STATIC
    SUPERCLASS

    this second txt file is called wordsearch.txt

    B H B U N Z A X O H I F P P O S S W O O 
    C V Z A O Y S B W M G G P X N V U Q N V 
    W D S M I N K I S L K T H I O C P P G N 
    A P Q O T E X V Z T M P N S Y D E Y R I 
    N N K M A Q C S V E R T Q E I N R G J Q 
    X O F O L J J L T I E A M J K D C V C D 
    M I I X U T W H I R A S C V M M L U L U 
    D T L G S S O S F P I V W T N M A A Y P 
    L P Y C P D O A S H S Y Y S I N S D T O 
    H E A V A J C D P N B E W W Q O S R C P 
    P C U U C E S R C I O Q E S O S N U S H 
    S X U U N Y O A N I P I D E B U G G E R 
    T E Q E E M I N H E R I T A N C E F S T 
    A I E Z Y E V Q G W O C Z A H N U O C C 
    T A L L C X W N W D Z J G Q R T E A R D 
    I B O Y L Y W J S J T I J D R E R L S H 
    C P Z F P E S C B Z C X S W I T T U R K 
    N W V D B O D F A D G T B F S L Y I J Y 
    T U V A N O I S R U C E R B J S T E H Z 
    L B C Q J W H K G V O I A V P J H U A K


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Recursive Assistance with a Word Puzzle Game

    Do you have any specific problems or questions about your program?

    public static void main(String[] args) {
    		args[0] = "C:\\projects\\wordsearch.txt";
    		args[1] = "C:\\projects\\wordlist.txt";

    This code will fail if there are not at least 2 args passed to the program. The length of the args array needs to be tested before trying to use 2 of its elements.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Recursive Wood Puzzle Assistance
    By inflames098 in forum Algorithms & Recursion
    Replies: 1
    Last Post: November 23rd, 2012, 05:56 PM
  2. Puzzle Game. Need some help
    By clydefrog in forum Java Theory & Questions
    Replies: 10
    Last Post: March 12th, 2012, 03:14 PM
  3. Sliding puzzle Restart button(same exact game)
    By carterb32 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 21st, 2011, 04:29 AM
  4. Search Word puzzle game
    By lew1s in forum What's Wrong With My Code?
    Replies: 6
    Last Post: April 9th, 2011, 04:23 AM