• Advertisement
Sign in to follow this  

Help with some problems with word search game

This topic is 1518 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I am having some trouble with a word search game I am making in Java. For starters, when I click on new game in the menu bar, it draws the puzzle just fine. However, if you click it again, it doesn't draw the new puzzle. I know it is drawing the puzzle because I have it displaying in the output window, it's just not drawing on screen.
 
My other problem really isn't a problem, more of a question. How would I go about highlighting the user's selection? I know I should be using the MouseListener, however, how would I snap that to the 2D array that has the puzzle?
 

WordSearchDriver.java:
[spoiler]

package com.camsoftware.wordsearch;

import java.awt.*;
import javax.swing.*;

public class WordSearchDriver {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		/*
		JFrame frame = new JFrame("Project Search and Destroy");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		frame.setPreferredSize(new Dimension(325,350));
		
		TextFileReader txtFileReader = new TextFileReader();
		frame.setJMenuBar(new Frame());
		frame.getContentPane().add(new SearchBoardPanel());
		
		frame.pack();
		frame.setVisible(true);
		*/
		
		Frame mp = new Frame();
		mp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		mp.setVisible(true);

	}
}

[/spoiler]

 

TextFileReader.java

[spoiler]

package com.camsoftware.wordsearch;

import java.io.*;
import java.util.*;

public class TextFileReader {
	
	private static ArrayList<String> wordBank;
	private String line;
	private String txtFile;
	
	public TextFileReader(){
		wordBank = new ArrayList<String>();
		line = null;
		txtFile = "wordList.txt";
		
		readTextFile();
	}
	
	public static ArrayList<String> getWordBank(){
		return wordBank;
	}
	
	private void readTextFile(){
		
		try{
			FileReader fileReader = new FileReader(txtFile);
			BufferedReader bufferedReader = new BufferedReader(fileReader);
			
			while((line = bufferedReader.readLine()) != null){
				wordBank.add(line);
			}
			
			bufferedReader.close();
			
			System.out.println("Reading wordList File: ");
			for(int i = 0; i < wordBank.size(); i++)
				System.out.println(wordBank.get(i));
			
		}
		catch(IOException ex){
			System.out.println(ex);
		}
	}

}

[/spoiler]

 

WordsToFindPanel.java:

[spoiler]

package com.camsoftware.wordsearch;

import java.awt.*;
import javax.swing.*;

public class WordsToFindPanel extends JPanel {
	
	private JLabel[] labels;
	
	public WordsToFindPanel(){
		
		labels = new JLabel[SearchBoard.getWordsToFind().length];
		
		setLayout(new GridLayout(5, 3));
		//setPreferredSize(new Dimension(100, 100));
		
		addWordsToLabels();
		
		for(int x = 0; x < SearchBoard.getWordsToFind().length; x++)
			add(labels[x]);
	}
	
	private void addWordsToLabels(){
		for(int x = 0; x < labels.length; x++){
			labels[x] = new JLabel(SearchBoard.getWordsToFind()[x]);
		}
	}

}

[/spoiler]

 

SearchBoardPanel.java

[spoiler]

package com.camsoftware.wordsearch;

import java.awt.*;
import javax.swing.*;

public class SearchBoardPanel extends JPanel {
	
	private SearchBoard searchBoard;
	
	public SearchBoardPanel(){
		searchBoard = new SearchBoard();
		
		//setPreferredSize(new Dimension(400,350));
		
	}
	
	public void paintComponent(Graphics page){
		super.paintComponent(page);
		searchBoard.Draw(page);
	}

}

[/spoiler]

 

Frame.java:

[spoiler]

package com.camsoftware.wordsearch;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class Frame extends JFrame{
	
	private JMenuBar menuBar;
	private JMenu fileMenu;
	private JMenu helpMenu;
	private JMenuItem newGame, exit, help, about;
	private MainPanel mp;
	
	public Frame(){
		
		MenuBar();
	}
	
	private void MenuBar(){
		
		menuBar = new JMenuBar();
		
		setSize(1000,700);
		setTitle("Project Search");
		
		fileMenu = new JMenu("File");
		helpMenu = new JMenu("Help");
		
		newGame = new JMenuItem("New Game");
		exit = new JMenuItem("Exit");
		help = new JMenuItem("Help");
		about = new JMenuItem("About");
		
		menuBar.add(fileMenu);
		menuBar.add(helpMenu);
		
		fileMenu.add(newGame);
		fileMenu.add(exit);
		
		helpMenu.add(help);
		helpMenu.add(about);
		add(menuBar);
		
		setJMenuBar(menuBar);
		
		newGame.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0) {
				System.out.println("Clicked on New Game");
				
				mp = new MainPanel();
				add(mp);
				revalidate();
				repaint();
			}
		});
		
		exit.addActionListener(new ExitAction());
		
		help.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0){
				System.out.println("Clicked on Help");
			}
		});
		
		about.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent arg0){
				System.out.println("Clicked on About");
			}
		});
	}	
}

[/spoiler]

 

MainPanel.java:

[spoiler]

package com.camsoftware.wordsearch;

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EtchedBorder;

public class MainPanel extends JPanel {
	
	private SearchBoardPanel sbp;
	private WordsToFindPanel wtfp;
	
	public MainPanel(){
		
		sbp = new SearchBoardPanel();
		wtfp = new WordsToFindPanel();
		
		setLayout(new BorderLayout());
		
		setSize(new Dimension(1000,700));
		sbp.setPreferredSize(new Dimension(475,450));
		sbp.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
		wtfp.setSize(new Dimension(400,200));
		wtfp.setBorder(BorderFactory.createTitledBorder("Words To Find:"));
		
		add(sbp, BorderLayout.LINE_END);
		add(wtfp, BorderLayout.PAGE_END);
	}

}

[/spoiler]

 

SearchBoard.java:

[spoiler]

package com.camsoftware.wordsearch;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.Random;

public class SearchBoard{
	
	// Random number generators
	private Random randGen;
	
	private boolean across;
	private boolean down;
	private boolean diagonal;
	private int randNumber;
	
	private int xLocation, yLocation;
	
	// String array of words selected from the word bank
	private static String[] wordsToFind;
	private String[] shuffledWordBank;
	
	private int randIndex;
	private String randValue;
	
	private int xOffset, yOffset;
	
	// 2D Array for the search board
	private String[][] searchBoard;
	private final int searchBoardSize = 15;
	private int addForLoop;
	
	public SearchBoard(){
		randGen = new Random();
		
		across = false;
		down = false;
		diagonal = false;
		
		wordsToFind = new String[15];
		shuffledWordBank = new String[TextFileReader.getWordBank().size()];
		searchBoard = new String[searchBoardSize][searchBoardSize];
		addForLoop = 0;
		
		xOffset = 10;
		yOffset = 20;
		
		// Initialize the shuffledWordBank array to the words in the wordBank
		for (int i = 0; i < TextFileReader.getWordBank().size(); i++){
			shuffledWordBank[i] = TextFileReader.getWordBank().get(i);
		}
		randomizeWords();
		
		// Initialize the searchBoard
		for (int y = 0; y < searchBoard.length; y++)
			for(int x = 0; x < searchBoard[y].length; x++)
				searchBoard[y][x] = null;
		
		addWordsToBoard();
		
	}
	
	// Shuffle words from wordBank
	private void randomizeWords(){
		
		for (int i = 0; i < shuffledWordBank.length; i++){
			
			randIndex = randGen.nextInt(shuffledWordBank.length);
			
			randValue = shuffledWordBank[randIndex];
			shuffledWordBank[randIndex] = shuffledWordBank[i];
			shuffledWordBank[i] = randValue;
		}
		
		System.out.println("Printing words in wordsToFind:");
		
		// Assign the first 9 elements of the shuffledWordBank to wordsToFind
		for (int i = 0; i < wordsToFind.length; i++){
			
			wordsToFind[i] = shuffledWordBank[i];
			
			// Debug
			System.out.print(wordsToFind[i] + " ");
		}
		System.out.println();
	}
	
	private void addWordsToBoard(){
		
		char letterInWord = ' ';
		
		for(addForLoop = 0; addForLoop < wordsToFind.length; addForLoop++){
			
			getRandomSpotOnBoard();
			getDirection();
			
			while(searchBoardSize < (xLocation + wordsToFind[addForLoop].length()) || 
					searchBoardSize < (yLocation + wordsToFind[addForLoop].length()) || !isDirectionOpen()){
				getRandomSpotOnBoard();
				System.out.println("Word would not fit on board, selecting a new location");
			}
			
			if (across && isDirectionOpen()){
				int index = 0;
				for (int x = xLocation; x < (xLocation + wordsToFind[addForLoop].length()); x++){
					for (int i = index; i < wordsToFind[addForLoop].length();){
						letterInWord = wordsToFind[addForLoop].charAt(i);
						searchBoard[yLocation][x] = String.valueOf(letterInWord);
						index++;
						break;
					}
				}
				System.out.println("Setting across to false");
				across = false;
			}
			
			if (down && isDirectionOpen()){
				int index = 0;
				for (int y = yLocation; y < (yLocation + wordsToFind[addForLoop].length()); y++){
					for(int i = index; i < wordsToFind[addForLoop].length();){
						letterInWord = wordsToFind[addForLoop].charAt(i);
						searchBoard[y][xLocation] = String.valueOf(letterInWord);
						index++;
						break;
					}
				}
				System.out.println("Setting down to false");
				down = false;
			}
			
			if (diagonal && isDirectionOpen()){
				int index = 0;
				int xPos = xLocation;
				for (int y = yLocation; y < (yLocation + wordsToFind[addForLoop].length()); y++){
					for(int x = xPos; x < (xLocation + wordsToFind[addForLoop].length());){
						for(int i = index; i < wordsToFind[addForLoop].length();){
							letterInWord = wordsToFind[addForLoop].charAt(i);
							searchBoard[y][x] = String.valueOf(letterInWord);
							index++;
							xPos++;
							break;
						}
						break;
					}
				}
				System.out.println("Setting diagonal to false");
				diagonal = false;
			}
			
		}
		
		fillEmptySpaces();
		
		// Debug
		for (int y = 0; y < searchBoard.length; y++){
			for (int x = 0; x < searchBoard[y].length; x++){
				System.out.print(searchBoard[y][x] + " ");
			}
			System.out.println();
		}
	}
	
	// Generates a random number for the x and y coordinates on the board
	// in order to place a word on a board
	private void getRandomSpotOnBoard(){
		
		xLocation = randGen.nextInt(searchBoardSize);
		yLocation = randGen.nextInt(searchBoardSize);
		
		// Debug
		System.out.println("Getting a random location: " + xLocation + ", " + yLocation);
	}
	
	// Get a random direction to set the word
	private void getDirection(){
		
		randNumber = randGen.nextInt(3);
		
		switch(randNumber){
		
		case 0:
			System.out.println("Setting across to true");
			across = true;
			break;
			
		case 1:
			System.out.println("Setting down to true");
			down = true;
			break;
			
		case 2:
			System.out.println("Setting diag to true");
			diagonal = true;
			break;
		}
		
		// Debug
		System.out.println("Setting a direction: " + across + down + diagonal);
	}
	
	// Check to see if the direction is open to put a word,
	// or if the interceting word has the same letter in order
	// to continue
	private boolean isDirectionOpen(){
		
		boolean isOpen = false;
		boolean isInterceting = false;
		char interChar = ' ';
		String valueAtInter = " ";
		
		acrossIf:{
			if(across){
				int index = 0;
				
				for (int x = xLocation; x < (xLocation + wordsToFind[addForLoop].length()); x++){
					for (int i = index; i < wordsToFind[addForLoop].length();){
						
						if (searchBoard[yLocation][x] != null){
							valueAtInter = searchBoard[yLocation][x];
							interChar = valueAtInter.charAt(0);
							System.out.println("Value of char on searchBoard: " + valueAtInter + interChar + "Value of char in wordsToFind: " +
									wordsToFind[addForLoop].charAt(i));
							if(interChar == wordsToFind[addForLoop].charAt(i)){
								isInterceting = true;
							}
							else{
								isInterceting = false;
							}
						}
						
						if (searchBoard[yLocation][x] == null || isInterceting){
							isOpen = true;
							index++;
							break;
						}
						else{
							isOpen = false;
							break acrossIf;
						}
					}
				}
			}
		}
		
		downIf:{
			if (down){
				int index = 0;
				for (int y = yLocation; y < (yLocation + wordsToFind[addForLoop].length()); y++){
					for (int i = index; i < wordsToFind[addForLoop].length();){
						
						if (searchBoard[y][xLocation] != null){
							valueAtInter = searchBoard[y][xLocation];
							interChar = valueAtInter.charAt(0);
							System.out.println("Value of char on searchBoard: " + valueAtInter + interChar + "Value of char in wordsToFind: " +
									wordsToFind[addForLoop].charAt(i));
							if(interChar == wordsToFind[addForLoop].charAt(i)){
								isInterceting = true;
							}
							else{
								isInterceting = false;
							}
						}
						
						if (searchBoard[y][xLocation] == null || isInterceting){
							isOpen = true;
							index++;
							break;
						}
						else{
							isOpen = false;
							break downIf;
						}
					}
				}
			}
		}
		
		diagonalIf:{
			if (diagonal){
				int xPos = xLocation;
				int index = 0;
				for (int y = yLocation; y < (yLocation + wordsToFind[addForLoop].length()); y++){
					for (int x = xPos; x < (xLocation + wordsToFind[addForLoop].length());){
						for (int i = index; i < wordsToFind[addForLoop].length();){
							
							if (searchBoard[y][x] != null){
								valueAtInter = searchBoard[y][x];
								interChar = valueAtInter.charAt(0);
								System.out.println("Value of char on searchBoard: " + valueAtInter + interChar + "Value of char in wordsToFind: " +
										wordsToFind[addForLoop].charAt(i));
								if(interChar == wordsToFind[addForLoop].charAt(i)){
									isInterceting = true;
								}
								else{
									isInterceting = false;
								}
							}
							
							if (searchBoard[y][x] == null || isInterceting){
								isOpen = true;
								xPos++;
								index++;
								break;
							}
							else{
								isOpen = false;
								break diagonalIf;
							}
						}
						break;
					}
				}
			}
		}
				
		// Debug
		System.out.println("Checking to see if the spaces are open");
		
		return isOpen;
	}
	
	// After all words are on the board, fill the empty spaces
	// with random letters
	private void fillEmptySpaces(){
		
		String alphabet = "abcdefghijklmnopqrstuvwxyz";
		int numOfCharInAlphabet = alphabet.length();
		char randChar = ' ';
		
		for (int y = 0; y < searchBoard.length; y++){
			for(int x = 0; x < searchBoard[y].length; x++){
				if (searchBoard[y][x] == null){
					int randNum = randGen.nextInt(numOfCharInAlphabet);
					randChar = alphabet.charAt(randNum);
					searchBoard[y][x] = String.valueOf(randChar);
				}
				else
					continue;
			}
		}
		
		// Debug
		System.out.println("Filling empty spaces");
	}
	
	public static String[] getWordsToFind(){
		return wordsToFind;
	}
	
	public String[][] getSearchBoard(){
		return searchBoard;
	}
	
	// Draw the searchBoard
	public void Draw(Graphics page){
		
		page.setColor(Color.black);
		Font font = new Font("Arial", Font.BOLD, 24);
		page.setFont(font);
		
		for (int y = 0; y < searchBoard.length; y++){
			for (int x = 0; x < searchBoard[y].length; x++){
				page.drawString(searchBoard[y][x], xOffset + 30 * x, yOffset + 30 * y);
			}
		}
	}
}

[/spoiler]

 

Listeners.java:

[spoiler]

package com.camsoftware.wordsearch;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Listeners {

}

class NewGameAction implements ActionListener{
	public void actionPerformed(ActionEvent arg0) {
		
		
	}
}

class ExitAction implements ActionListener{
	public void actionPerformed(ActionEvent arg0){
		
		System.exit(0);
	}
}

class HelpAction implements ActionListener{
	public void actionPerformed(ActionEvent arg0){
		
	}
}

class AboutAction implements ActionListener{
	public void actionPerformed(ActionEvent arg0){
		
	}
}

[/spoiler]

 

 

Share this post


Link to post
Share on other sites
Advertisement

You should consider that when you add new things to a container, the old things that are already in there do not go away. The new game button just creates a new MainPanel and adds it, but if there is one already in there, it might be added somewhere where you can't see it. Try removing mp first and the adding it again. Consider that you might run into a problem of adding items out of order. If there are components added after the MainPanel, they will be relocated because the MainPanel is now going to be the last component to be added.

 

Also don't abbreviate complicated names like SearchBoardPanel to sbp. It makes it harder to figure out what the code means.

Edited by boogyman19946

Share this post


Link to post
Share on other sites


Try removing mp first and the adding it again.

 

Thanks, that worked. Now I just need help getting pointed in the right direction for the highlighting / circling the words the user finds

Share this post


Link to post
Share on other sites


Also don't abbreviate complicated names like SearchBoardPanel to sbp. It makes it harder to figure out what the code means.

 

Good naming is a small cost, high gain thing you can do to become a much better programmer. It makes your programs so much easier to understand which has all kinds of benefits. When I was in school, I dismissed my professors' wisdom. "I can keep this straight, it's no problem for me." But later on in the real world, I'd be cussing my predecessors who wrote the garbage code I had to debug. :)

 


Thanks, that worked. Now I just need help getting pointed in the right direction for the highlighting / circling the words the user finds

 

You'll need to define how you'd like the user to "circle a word".

[spoiler]How about they click one letter to "start circling" and click another letter to finish circling. While in the circling state, you could listen to Mouse Moves to dynamically show the user what he's circling, or change the color of the letter he started with.[/spoiler]

 

Your search board will need to be able to identify what's been found. Currently the board is just a 2d array of strings. You need to start tracking the state for "circling" and "circled" words.

[spoiler]Instead of a 2d array of strings, you could have a 2d array of WordSearchLetter which could hold the char, and a state enumeration (normal, circling, circled). In your draw function for now, you can just draw the letters as a different color depending on state.[/spoiler]

 

- Eck

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement