Java word search maze game

  • 2020-04-01 03:52:24
  • OfStack

This article is an example of a Java word search maze game. Share with you for your reference. Specific analysis is as follows:

In magazines, we often see little word finding games, in a two-dimensional table, there are various letters, we can find the word from eight directions. This is easy to do with a computer, but the quality of the algorithm matters, because it would take an unimaginable amount of time to do with a brute force algorithm.

This is the implementation idea given in the book description of data structure and problem solving Java language

The full code is as follows, and the comments are clear


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class WordSearch
{
 
  public WordSearch( ) throws IOException
  {
    puzzleStream = openFile( " Input form file path: " );
    wordStream  = openFile( " Input word file path: " );
    System.out.println( " File reading ..." );
    readPuzzle( );
    readWords( );
  }
  
  public int solvePuzzle( )
  {
    int matches = 0;
    for( int r = 0; r < rows; r++ )
      for( int c = 0; c < columns; c++ )
        for( int rd = -1; rd <= 1; rd++ )
          for( int cd = -1; cd <= 1; cd++ )
            if( rd != 0 || cd != 0 )
             matches += solveDirection( r, c, rd, cd );
    return matches;
  }
  
  private int solveDirection( int baseRow, int baseCol, int rowDelta, int colDelta )
  {
    String charSequence = "";
    int numMatches = 0;
    int searchResult;
    charSequence += theBoard[ baseRow ][ baseCol ];
    for( int i = baseRow + rowDelta, j = baseCol + colDelta;
         i >= 0 && j >= 0 && i < rows && j < columns;
         i += rowDelta, j += colDelta )
    {
      charSequence += theBoard[ i ][ j ];
      searchResult = prefixSearch( theWords, charSequence );
      
      if( searchResult == theWords.length )
        break;
      
      if( !theWords[ searchResult ].startsWith( charSequence ) )
        break;
      if( theWords[ searchResult ].equals( charSequence ) )
      {
        numMatches++;
        System.out.println( " found  " + charSequence + "  in  " +
                  baseRow+1 + " line   " + baseCol + "  column    " +
                  i + " " + j );
      }
    }
    return numMatches;
  }
  
  private static int prefixSearch( String [ ] a, String x )
  {
    int idx = Arrays.binarySearch( a, x );
    if( idx < 0 )
      return -idx - 1;
    else
      return idx;
  }
  
  private BufferedReader openFile( String message )
  {
    String fileName = "";
    FileReader theFile;
    BufferedReader fileIn = null;
    do
    {
      System.out.println( message + ": " );
      try
      {
        fileName = in.readLine( );
        if( fileName == null )
           System.exit( 0 );
        theFile = new FileReader( fileName );
        fileIn = new BufferedReader( theFile );
      }
      catch( IOException e )
       { System.err.println( "Cannot open " + fileName ); }
    } while( fileIn == null );
    System.out.println( "Opened " + fileName );
    return fileIn;
  }
  
  private void readPuzzle( ) throws IOException
  {
    String oneLine;
    List<String> puzzleLines = new ArrayList<String>( );
    if( ( oneLine = puzzleStream.readLine( ) ) == null )
      throw new IOException( "No lines in puzzle file" );
    columns = oneLine.length( );
    puzzleLines.add( oneLine );
    while( ( oneLine = puzzleStream.readLine( ) ) != null )
    {
      if( oneLine.length( ) != columns )
        System.err.println( "Puzzle is not rectangular; skipping row" );
      else
       puzzleLines.add( oneLine );
    }
    rows = puzzleLines.size( );
    theBoard = new char[ rows ][ columns ];
    int r = 0;
    for( String theLine : puzzleLines )
      theBoard[ r++ ] = theLine.toCharArray( );
  }
  
  private void readWords( ) throws IOException
  {
    List<String> words = new ArrayList<String>( );
    String lastWord = null;
    String thisWord;
    while( ( thisWord = wordStream.readLine( ) ) != null )
    {
      if( lastWord != null && thisWord.compareTo( lastWord ) < 0 )
      {
        System.err.println( " Not sorted in lexicographical order, skip this time " );
        continue;
      }
      words.add( thisWord.trim() );
      lastWord = thisWord;
    }
    theWords = new String[ words.size( ) ];
 theWords = words.toArray( theWords );
  }
   // Cheap main
  public static void main( String [ ] args )
  {
    WordSearch p = null;
    try
    {
      p = new WordSearch( );
    }
    catch( IOException e )
    {
      System.out.println( "IO Error: " );
      e.printStackTrace( );
      return;
    }
    System.out.println( " Are the search ..." );
    p.solvePuzzle( );
  }
  private int rows;
  private int columns;
  private char [ ][ ] theBoard;
  private String [ ] theWords;
  private BufferedReader puzzleStream;
  private BufferedReader wordStream;
  private BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
}

I hope this article has been helpful to your Java programming.


Related articles: