Exemplo n.º 1
0
        public static Boolean TryParse(String path, Configuration aConfiguration, out WordList aWordList)
        {
            StreamReader fileIn = new StreamReader(path);

            Errors    = new List <String>();
            aWordList = new WordList(path, aConfiguration);

            // Split the original wordlist from the file.
            aWordList.OriginalList = fileIn.ReadLine().Split(WordSeparators);

            // Check each field in the wordlist.
            int fieldNumber = 0;

            foreach (String potentialWord in aWordList.OriginalList)
            {
                // Check that the field is not empty.
                if (potentialWord.Length > 0)
                {
                    // Check that the field is alphabetic.
                    if (Regex.IsMatch(potentialWord, Configuration.allowedCharacters))
                    {
                        aWordList.Add(potentialWord);
                    }
                    else
                    {
                        Errors.Add(String.Format(WordListErrors.AlphabeticError, potentialWord, fieldNumber));
                    }
                }
                else
                {
                    Errors.Add(String.Format(WordListErrors.MissingWordError, fieldNumber));
                }

                fieldNumber++;
            }

            // Check the minimmum word limit.
            if (aWordList.Count < aConfiguration.MinimumNumberOfUniqueWords)
            {
                Errors.Add(String.Format(WordListErrors.MinimumSizeError, aWordList.Count, aConfiguration.MinimumNumberOfUniqueWords));
            }

            // Check the maximum word limit.
            if (aWordList.Count > aConfiguration.MaximumNumberOfUniqueWords)
            {
                Errors.Add(String.Format(WordListErrors.MaximumSizeError, aWordList.Count, aConfiguration.MaximumNumberOfUniqueWords));
            }

            aWordList.Valid = Errors.Count == 0;
            return(aWordList.Valid);
        }
Exemplo n.º 2
0
        private int CrozzleScore()
        {
            int score = 0;

            // Get the point per word from wordlist
            Configuration.PointsPerWord = WordList.getPointsPerWord();
            // Increase the score for each word.
            score += CrozzleSequences.Count * Configuration.PointsPerWord;

            // Increase the score for intersecting letters.
            List <Char> intersectingLetters = CrozzleSequences.GetIntersectingLetters();

            foreach (Char letter in intersectingLetters)
            {
                score += Configuration.IntersectingPointsPerLetter[(int)letter - (int)'A'];
            }

            // Get all letters.
            List <Char> allLetters = new List <Char>();

            foreach (String[] letters in CrozzleRows)
            {
                foreach (String letter in letters)
                {
                    if (letter[0] != ' ')
                    {
                        allLetters.Add(letter[0]);
                    }
                }
            }

            // Remove each intersecting letter from allLetters.
            List <Char> nonIntersectingLetters = allLetters;

            foreach (Char letter in intersectingLetters)
            {
                nonIntersectingLetters.Remove(letter);
            }

            // Increase the score for non-intersecting letters.
            foreach (Char letter in nonIntersectingLetters)
            {
                score += Configuration.NonIntersectingPointsPerLetter[(int)letter - (int)'A'];
            }

            return(score);
        }
Exemplo n.º 3
0
        private int CrozzleScore()
        {
            int score = 0;

            // Increase the score for each word.
            CrozzleSequences.UsedSequences().ForEach(used => score += WordList.FirstResult(used.Letters).Score);

            // Increase the score for intersecting letters.
            List <Char> intersectingLetters = CrozzleSequences.GetIntersectingLetters();

            foreach (Char letter in intersectingLetters)
            {
                score += Configuration.IntersectingPointsPerLetter[(int)letter - (int)'A'];
            }

            // Get all letters.
            List <Char> allLetters = new List <Char>();

            foreach (String[] letters in CrozzleRows)
            {
                foreach (String letter in letters)
                {
                    if (letter[0] != ' ')
                    {
                        allLetters.Add(letter[0]);
                    }
                }
            }

            // Remove each intersecting letter from allLetters.
            List <Char> nonIntersectingLetters = allLetters;

            foreach (Char letter in intersectingLetters)
            {
                nonIntersectingLetters.Remove(letter);
            }

            // Increase the score for non-intersecting letters.
            foreach (Char letter in nonIntersectingLetters)
            {
                score += Configuration.NonIntersectingPointsPerLetter[(int)letter - (int)'A'];
            }

            return(score);
        }
Exemplo n.º 4
0
        public static Boolean TryParse(String path, Configuration aConfiguration, WordList wordList, out Crozzle aCrozzle)
        {
            Errors   = new List <String>();
            aCrozzle = new Crozzle(path, aConfiguration, wordList);

            // Open file.
            StreamReader  fileIn   = new StreamReader(path);
            List <String> wordData = new List <string>();

            // Validate file.
            while (!fileIn.EndOfStream)
            {
                // Read a line.
                String line = fileIn.ReadLine();

                // Parse a crozzle file item.
                CrozzleFileItem aCrozzleFileItem;
                if (CrozzleFileItem.TryParse(line, out aCrozzleFileItem))
                {
                    if (aCrozzleFileItem.IsConfigurationFile)
                    {
                        // Get the configuration file name.
                        String configurationPath = aCrozzleFileItem.KeyValue.Value;
                        if (configurationPath == null)
                        {
                            Errors.Add(CrozzleFileErrors.ConfigurationFilenameMissing);
                        }
                        else
                        {
                            configurationPath = configurationPath.Trim();
                            if (Validator.IsDelimited(configurationPath, StringDelimiters))
                            {
                                configurationPath = configurationPath.Trim(StringDelimiters);
                            }

                            if (!Path.IsPathRooted(configurationPath))
                            {
                                String directoryName = Path.GetDirectoryName(path);
                                configurationPath = directoryName + @"\" + configurationPath;
                            }

                            aCrozzle.ConfigurationPath = configurationPath;
                        }
                    }
                    else if (aCrozzleFileItem.IsWordListFile)
                    {
                        // Get the word list file name.
                        String wordListPath = aCrozzleFileItem.KeyValue.Value;
                        if (wordListPath == null)
                        {
                            Errors.Add(CrozzleFileErrors.WordlistFilenameMissing);
                        }
                        else
                        {
                            wordListPath = wordListPath.Trim();
                            if (Validator.IsDelimited(wordListPath, StringDelimiters))
                            {
                                wordListPath = wordListPath.Trim(StringDelimiters);
                            }

                            if (!Path.IsPathRooted(wordListPath))
                            {
                                String directoryName = Path.GetDirectoryName(path);
                                wordListPath = directoryName + @"\" + wordListPath;
                            }

                            aCrozzle.WordListPath = wordListPath;
                        }
                    }
                    else if (aCrozzleFileItem.IsRows)
                    {
                        // Get the number of rows.
                        int rows;
                        if (Validator.IsInt32(aCrozzleFileItem.KeyValue.Value.Trim(), out rows))
                        {
                            aCrozzle.Rows = rows;
                        }
                        else
                        {
                            Errors.Add(String.Format(CrozzleFileErrors.RowError, aCrozzleFileItem.KeyValue.OriginalKeyValue, Validator.Errors[0]));
                        }
                    }
                    else if (aCrozzleFileItem.IsColumns)
                    {
                        // Get the number of columns.
                        int columns;
                        if (Validator.IsInt32(aCrozzleFileItem.KeyValue.Value.Trim(), out columns))
                        {
                            aCrozzle.Columns = columns;
                        }
                        else
                        {
                            Errors.Add(String.Format(CrozzleFileErrors.ColumnError, aCrozzleFileItem.KeyValue.OriginalKeyValue, Validator.Errors[0]));
                        }
                    }
                    else if (aCrozzleFileItem.IsRow)
                    {
                        // Collect potential word data for a horizontal word.
                        wordData.Add(aCrozzleFileItem.KeyValue.OriginalKeyValue);
                    }
                    else if (aCrozzleFileItem.IsColumn)
                    {
                        // Collect potential word data for a vertical word.
                        wordData.Add(aCrozzleFileItem.KeyValue.OriginalKeyValue);
                    }
                }
                else
                {
                    Errors.AddRange(CrozzleFileItem.Errors);
                }
            }

            // Close files.
            fileIn.Close();


            // Get potential word data list.
            WordDataList wordDataList;

            if (!WordDataList.TryParse(wordData, aCrozzle, out wordDataList))
            {
                Errors.AddRange(WordDataList.Errors);
            }
            aCrozzle.WordDataList = wordDataList;


            // Validate file sections.
            // Check the configuration file name.
            if (aCrozzle.Configuration != null)
            {
                if (aCrozzle.Configuration.ConfigurationPath != aCrozzle.ConfigurationPath)
                {
                    Errors.Add(String.Format(CrozzleFileErrors.ConfigurationFilenameError, aCrozzle.ConfigurationPath, aCrozzle.Configuration.ConfigurationFileName));
                }
            }

            // Check the word list file name.
            if (aCrozzle.WordList != null)
            {
                if (aCrozzle.WordList.WordlistPath != aCrozzle.WordListPath)
                {
                    Errors.Add(String.Format(CrozzleFileErrors.WordlistFilenameError, aCrozzle.WordListPath, aCrozzle.WordList.WordlistFileName));
                }
            }

            // Raw word data of horizontal and vertical words were obtained when reading the crozzle file,
            // but now we need to create crozzle rows and crozzle columns that represent the crozzle.
            aCrozzle.CreateCrozzleRows(aCrozzle.WordDataList);
            aCrozzle.CreateCrozzleColumns(aCrozzle.WordDataList);

            // Store validity.
            aCrozzle.FileValid = Errors.Count == 0;
            return(aCrozzle.FileValid);
        }
Exemplo n.º 5
0
        public static Boolean TryParse(String path, Configuration aConfiguration, out WordList aWordList)
        {
            StreamReader fileIn = new StreamReader(path);

            Errors    = new List <String>();
            aWordList = new WordList(path, aConfiguration);

            /// Split the sequence file, and extract the WordDataValidator.
            aWordList.OriginalList = fileIn.ReadToEnd().Split(WordSeparators).Where(x => x != String.Empty).ToArray();

            /// Validate the SequenceValidator; possible case of invalid fields.
            SequenceData seq;

            SequenceData.TryParse(aWordList.OriginalList.First(), IS_VALIDATOR, out seq);
            if (SequenceData.Errors.Any())
            {
                Errors.AddRange(SequenceData.Errors);
            }
            else
            {
                aWordList.SequenceValidator = seq;
                aWordList.OriginalList      = aWordList.OriginalList.Skip(1).ToArray(); /// existence of magic number.

                // Check each field in the wordlist.
                int totalPotentialScore     = 0,
                    totalPotentialLength    = 0,
                    totalPotentialAsciiSum  = 0,
                    totalPotentialHashTotal = 0;
                foreach (String potentialWord in aWordList.OriginalList)
                {
                    SequenceData data;
                    SequenceData.TryParse(potentialWord, !IS_VALIDATOR, out data);
                    if (SequenceData.Errors.Any())
                    {
                        Errors.AddRange(SequenceData.Errors);
                    }
                    else
                    {
                        /// Check that the sequence is not empty.
                        if (data.Sequence.Length > 0)
                        {
                            /// Check if sequence is alphabetic, then check if sequence length matches its pre-determined length.
                            if (Regex.IsMatch(data.Sequence, aWordList.SequenceValidator.Sequence))
                            {
                                if (data.ReturnLength() != data.SequenceLength)
                                {
                                    Errors.Add(String.Format(WordListErrors.NonIdenticalLengthError, data.OriginalData));
                                }
                                else
                                {
                                    aWordList.Add(data);
                                    totalPotentialLength += data.SequenceLength;
                                }
                            }
                            else
                            {
                                Errors.Add(String.Format(WordListErrors.AlphabeticError, data.Sequence, data.OriginalData));
                            }

                            totalPotentialScore += data.Score;

                            /// Check if sequence's ASCII sum matches its pre-determined sum.
                            if (data.ReturnAsciiSum() != data.AsciiSum)
                            {
                                Errors.Add(String.Format(WordListErrors.NonIdenticalAsciiSumError, data.OriginalData));
                            }
                            else
                            {
                                totalPotentialAsciiSum += data.AsciiSum;
                            }

                            /// Check if seqence's hash total matches its pre-determined total.
                            if (data.ReturnHashTotal() != data.HashTotal)
                            {
                                Errors.Add(String.Format(WordListErrors.NonIdenticalHashTotalError, data.OriginalData));
                            }
                            else
                            {
                                totalPotentialHashTotal += data.HashTotal;
                            }
                        }
                        else
                        {
                            Errors.Add(String.Format(WordListErrors.MissingWordError, data.OriginalData));
                        }
                    }
                }

                /// Check if totaled potential values match the sequence validator.
                if (totalPotentialScore != aWordList.SequenceValidator.Score)
                {
                    Errors.Add(String.Format(WordListErrors.IncorrectBatchScoreError, totalPotentialScore, aWordList.SequenceValidator.Score));
                }
                if (totalPotentialLength != aWordList.SequenceValidator.SequenceLength)
                {
                    Errors.Add(String.Format(WordListErrors.IncorrectBatchLengthError, totalPotentialLength, aWordList.SequenceValidator.SequenceLength));
                }
                if (totalPotentialAsciiSum != aWordList.SequenceValidator.AsciiSum)
                {
                    Errors.Add(String.Format(WordListErrors.IncorrectBatchAsciiSumError, totalPotentialAsciiSum, aWordList.SequenceValidator.SequenceLength));
                }
                if (totalPotentialHashTotal != aWordList.SequenceValidator.HashTotal)
                {
                    Errors.Add(String.Format(WordListErrors.IncorrectBatchHashTotalError, totalPotentialHashTotal, aWordList.SequenceValidator.HashTotal));
                }

                // Check the minimmum word limit.
                if (aWordList.Count < aConfiguration.MinimumNumberOfUniqueWords)
                {
                    Errors.Add(String.Format(WordListErrors.MinimumSizeError, aWordList.Count, aConfiguration.MinimumNumberOfUniqueWords));
                }

                // Check the maximum word limit.
                if (aWordList.Count > aConfiguration.MaximumNumberOfUniqueWords)
                {
                    Errors.Add(String.Format(WordListErrors.MaximumSizeError, aWordList.Count, aConfiguration.MaximumNumberOfUniqueWords));
                }
            }

            aWordList.Valid = Errors.Count == 0;
            return(aWordList.Valid);
        }
Exemplo n.º 6
0
        public static Boolean TryParse(String path, Configuration aConfiguration, WordList wordList, out Crozzle aCrozzle)
        {
            Errors   = new List <String>();
            aCrozzle = new Crozzle(path, aConfiguration, wordList);

            // Open file.
            StreamReader  fileIn   = new StreamReader(path);
            List <String> wordData = new List <string>();

            String section  = null;
            bool   newBlock = false;

            // Validate file
            while (!fileIn.EndOfStream)
            {
                // Read a line.
                String line = fileIn.ReadLine();

                // Processing empty lines
                if (Regex.IsMatch(line, @"^\s*$"))
                {
                    continue;
                }
                line = line.Trim();

                // Processing comments
                if (line.Contains("//"))
                {
                    if (line.StartsWith("//"))
                    {
                        continue;
                    }
                    else
                    {
                        Errors.Add(String.Format(ConfigurationErrors.MixConfigWithComentError, line));
                        continue;
                    }
                }

                // Section check
                switch (line)
                {
                case "FILE-DEPENDENCIES":
                case "CROZZLE-SIZE":
                case "HORIZONTAL-SEQUENCES":
                case "VERTICAL-SEQUENCES":
                    section  = line;
                    newBlock = true;
                    break;

                case "END-FILE-DEPENDENCIES":
                case "END-CROZZLE-SIZE":
                case "END-HORIZONTAL-SEQUENCES":
                case "END-VERTICAL-SEQUENCES":
                    section  = null;
                    newBlock = true;
                    break;

                default:
                    break;
                }

                if (newBlock)
                {
                    newBlock = false;
                    continue;
                }

                // Parse a crozzle file item.
                CrozzleFileItem aCrozzleFileItem;

                // Out of section comment
                if (section == null)
                {
                    Errors.Add(String.Format(ConfigurationErrors.OutOfSectionError, line));
                }
                // Parse a crozzle item
                else if (CrozzleFileItem.TryParse(line, out aCrozzleFileItem))
                {
                    if (aCrozzleFileItem.IsConfigurationFile)
                    {
                        // Get the configuration file name.
                        String configurationPath = aCrozzleFileItem.KeyValue.Value;
                        if (configurationPath == null)
                        {
                            Errors.Add(CrozzleFileErrors.ConfigurationFilenameMissing);
                        }
                        else
                        {
                            configurationPath = configurationPath.Trim();
                            if (Validator.IsDelimited(configurationPath, StringDelimiters))
                            {
                                configurationPath = configurationPath.Trim(StringDelimiters);
                            }

                            if (!Path.IsPathRooted(configurationPath))
                            {
                                String directoryName = Path.GetDirectoryName(path);
                                configurationPath = directoryName + @"\" + configurationPath;
                            }

                            aCrozzle.ConfigurationPath = configurationPath;
                        }
                    }
                    else if (aCrozzleFileItem.IsWordListFile)
                    {
                        // Get the word list file name.
                        String wordListPath = aCrozzleFileItem.KeyValue.Value;
                        if (wordListPath == null)
                        {
                            Errors.Add(CrozzleFileErrors.WordlistFilenameMissing);
                        }
                        else
                        {
                            wordListPath = wordListPath.Trim();
                            if (Validator.IsDelimited(wordListPath, StringDelimiters))
                            {
                                wordListPath = wordListPath.Trim(StringDelimiters);
                            }

                            if (!Path.IsPathRooted(wordListPath))
                            {
                                String directoryName = Path.GetDirectoryName(path);
                                wordListPath = directoryName + @"\" + wordListPath;
                            }

                            aCrozzle.WordListPath = wordListPath;
                        }
                    }
                    // Replace
                    else if (aCrozzleFileItem.IsSize)
                    {
                        // Split row & col
                        String   rawSizeData = aCrozzleFileItem.KeyValue.Value.Trim();
                        String[] sizeSplit   = rawSizeData.Split(new String[] { SizeDelimiter }, 2, StringSplitOptions.None);
                        if (sizeSplit.Length != SizeValueLength)
                        {
                            Errors.Add(String.Format(KeyValueErrors.FieldCountError, sizeSplit.Length, rawSizeData, SizeValueLength));
                        }
                        else
                        {
                            int rows;
                            if (Validator.IsInt32(sizeSplit[0].Trim(), out rows))
                            {
                                aCrozzle.Rows = rows;
                            }
                            else
                            {
                                Errors.Add(String.Format(CrozzleFileErrors.RowError, aCrozzleFileItem.KeyValue.OriginalKeyValue, Validator.Errors[0]));
                            }

                            int columns;
                            if (Validator.IsInt32(sizeSplit[1].Trim(), out columns))
                            {
                                aCrozzle.Columns = columns;
                            }
                            else
                            {
                                Errors.Add(String.Format(CrozzleFileErrors.ColumnError, aCrozzleFileItem.KeyValue.OriginalKeyValue, Validator.Errors[0]));
                            }
                        }
                    }

                    else if (aCrozzleFileItem.IsSequence)
                    {
                        // Collect potential word data for a horizontal word.
                        //wordData.Add(aCrozzleFileItem.KeyValue.OriginalKeyValue);
                        String type;

                        if (section == "HORIZONTAL-SEQUENCES")
                        {
                            type = "ROW";

                            try
                            {
                                String oldFormat = aCrozzleFileItem.KeyValue.OriginalKeyValue;

                                oldFormat = oldFormat.Substring("SEQUENCE=".Length);
                                string[] split;
                                split = oldFormat.Split(',');
                                String key = split[0];
                                String row = split[1].Split('=')[1];
                                String col = split[2];

                                String newFormat = type + "=" + row + "," + key + "," + col;
                                Console.WriteLine("New Format = " + newFormat);
                                wordData.Add(newFormat);
                            }
                            catch (Exception e)
                            {
                                Errors.Add(String.Format(CrozzleFileErrors.SequenceFormatError, aCrozzleFileItem.KeyValue.OriginalKeyValue));
                            }
                        }
                        else if (section == "VERTICAL-SEQUENCES")
                        {
                            type = "COLUMN";


                            try
                            {
                                String oldFormat = aCrozzleFileItem.KeyValue.OriginalKeyValue;

                                oldFormat = oldFormat.Substring("SEQUENCE=".Length);
                                string[] split;
                                split = oldFormat.Split(',');
                                String key = split[0];
                                String row = split[1].Split('=')[1];
                                String col = split[2];

                                String newFormat = type + "=" + col + "," + key + "," + row;
                                Console.WriteLine("New Format = " + newFormat);
                                wordData.Add(newFormat);
                            }
                            catch (Exception e)
                            {
                                Errors.Add(String.Format(CrozzleFileErrors.SequenceFormatError, aCrozzleFileItem.KeyValue.OriginalKeyValue));
                            }
                        }
                        else
                        {
                            Errors.AddRange(CrozzleFileItem.Errors);
                            break;
                        }
                    }
                }
                else
                {
                    Errors.AddRange(CrozzleFileItem.Errors);
                }
            }

            // Close files.
            fileIn.Close();


            // Get potential word data list.
            WordDataList wordDataList;

            if (!WordDataList.TryParse(wordData, aCrozzle, out wordDataList))
            {
                Errors.AddRange(WordDataList.Errors);
            }
            aCrozzle.WordDataList = wordDataList;


            // Validate file sections.
            // Check the configuration file name.
            if (aCrozzle.Configuration != null)
            {
                if (aCrozzle.Configuration.ConfigurationPath != aCrozzle.ConfigurationPath)
                {
                    Errors.Add(String.Format(CrozzleFileErrors.ConfigurationFilenameError, aCrozzle.ConfigurationPath, aCrozzle.Configuration.ConfigurationFileName));
                }
            }

            // Check the word list file name.
            if (aCrozzle.WordList != null)
            {
                if (aCrozzle.WordList.WordlistPath != aCrozzle.WordListPath)
                {
                    Errors.Add(String.Format(CrozzleFileErrors.WordlistFilenameError, aCrozzle.WordListPath, aCrozzle.WordList.WordlistFileName));
                }
            }

            // Raw word data of horizontal and vertical words were obtained when reading the crozzle file,
            // but now we need to create crozzle rows and crozzle columns that represent the crozzle.
            aCrozzle.CreateCrozzleRows(aCrozzle.WordDataList);
            aCrozzle.CreateCrozzleColumns(aCrozzle.WordDataList);

            // Store validity.
            aCrozzle.FileValid = Errors.Count == 0;
            return(aCrozzle.FileValid);
        }
Exemplo n.º 7
0
        public static Boolean TryParse(String path, Configuration aConfiguration, out WordList aWordList)
        {
            StreamReader fileIn = new StreamReader(path);

            Errors    = new List <String>();
            aWordList = new WordList(path, aConfiguration);
            bool isHeader = true;

            String[] words = new string[] {};

            // Build word list
            while (!fileIn.EndOfStream)
            {
                String   line   = fileIn.ReadLine();
                String[] values = line.Split(',');

                if (isHeader)
                {
                    // TODO - check header regex + all totals
                    isHeader = false;
                    continue;
                }

                // TODO - Calculate word points
                // TODO - Check length
                // TODO - Check ASCII sum
                // TODO - Check total
                // Get Word
                String word = values[0];
                Array.Resize(ref words, words.Length + 1);
                words[words.Length - 1] = word;
            }

            // Split the original wordlist from the file.
            //aWordList.OriginalList = fileIn.ReadLine().Split(WordSeparators);
            aWordList.OriginalList = words;

            // Check each field in the wordlist.
            int fieldNumber = 0;

            foreach (String potentialWord in aWordList.OriginalList)
            {
                // Check that the field is not empty.
                if (potentialWord.Length > 0)
                {
                    // Check that the field is alphabetic.
                    if (Regex.IsMatch(potentialWord, Configuration.allowedCharacters))
                    {
                        aWordList.Add(potentialWord);
                    }
                    else
                    {
                        Errors.Add(String.Format(WordListErrors.AlphabeticError, potentialWord, fieldNumber));
                    }
                }
                else
                {
                    Errors.Add(String.Format(WordListErrors.MissingWordError, fieldNumber));
                }

                fieldNumber++;
            }

            // Check the minimmum word limit.
            if (aWordList.Count < aConfiguration.MinimumNumberOfUniqueWords)
            {
                Errors.Add(String.Format(WordListErrors.MinimumSizeError, aWordList.Count, aConfiguration.MinimumNumberOfUniqueWords));
            }

            // Check the maximum word limit.
            if (aWordList.Count > aConfiguration.MaximumNumberOfUniqueWords)
            {
                Errors.Add(String.Format(WordListErrors.MaximumSizeError, aWordList.Count, aConfiguration.MaximumNumberOfUniqueWords));
            }

            aWordList.Valid = Errors.Count == 0;
            return(aWordList.Valid);
        }
Exemplo n.º 8
0
        public static Boolean TryParse(String path, Configuration aConfiguration, WordList wordList, out Crozzle aCrozzle)
        {
            Errors   = new List <String>();
            aCrozzle = new Crozzle(path, aConfiguration, wordList);

            StreamReader fileIn;

            if (path.Contains("http"))
            {
                WebClient webClient = new WebClient();
                Stream    aStream   = webClient.OpenRead(path);
                fileIn = new StreamReader(aStream);
            }
            else
            {
                fileIn = new StreamReader(path);
            }


            List <String> wordData = new List <string>();

            // Validate file.
            while (!fileIn.EndOfStream)
            {
                // Read a line.
                String line = fileIn.ReadLine();

                // Parse a crozzle file item.
                CrozzleFileItem aCrozzleFileItem;
                if (CrozzleFileItem.TryParse(line, out aCrozzleFileItem))
                {
                    if (aCrozzleFileItem.IsConfigurationFile)
                    {
                        // Get the configuration file name.
                        String configurationPath = aCrozzleFileItem.KeyValue.Value;
                        if (configurationPath == null)
                        {
                            Errors.Add(CrozzleFileErrors.ConfigurationFilenameMissing);
                        }
                        else
                        {
                            configurationPath = configurationPath.Trim();
                            if (Validator.IsDelimited(configurationPath, StringDelimiters))
                            {
                                configurationPath = configurationPath.Trim(StringDelimiters);
                            }

                            if (!Path.IsPathRooted(configurationPath))
                            {
                                // Seperate local files and files from web server
                                if (!path.Contains("http"))
                                {
                                    String directoryName = Path.GetDirectoryName(path);
                                    configurationPath = directoryName + @"\" + configurationPath;
                                }
                            }

                            aCrozzle.ConfigurationPath = configurationPath;
                        }
                    }
                    else if (aCrozzleFileItem.IsWordListFile)
                    {
                        // Get the word list file name.
                        String wordListPath = aCrozzleFileItem.KeyValue.Value;
                        if (wordListPath == null)
                        {
                            Errors.Add(CrozzleFileErrors.WordlistFilenameMissing);
                        }
                        else
                        {
                            wordListPath = wordListPath.Trim();
                            if (Validator.IsDelimited(wordListPath, StringDelimiters))
                            {
                                wordListPath = wordListPath.Trim(StringDelimiters);
                            }

                            if (!Path.IsPathRooted(wordListPath))
                            {
                                // Seperate local files and files from web server
                                if (!path.Contains("http"))
                                {
                                    String directoryName = Path.GetDirectoryName(path);
                                    wordListPath = directoryName + @"\" + wordListPath;
                                }
                            }

                            aCrozzle.WordListPath = wordListPath;
                        }
                    }
                    else if (aCrozzleFileItem.IsRows)
                    {
                        // Get the number of rows.
                        int rows;
                        if (Validator.IsInt32(aCrozzleFileItem.KeyValue.Value.Trim(), out rows))
                        {
                            aCrozzle.Rows = rows;
                        }
                        else
                        {
                            Errors.Add(String.Format(CrozzleFileErrors.RowError, aCrozzleFileItem.KeyValue.OriginalKeyValue, Validator.Errors[0]));
                        }
                    }
                    else if (aCrozzleFileItem.IsColumns)
                    {
                        // Get the number of columns.
                        int columns;
                        if (Validator.IsInt32(aCrozzleFileItem.KeyValue.Value.Trim(), out columns))
                        {
                            aCrozzle.Columns = columns;
                        }
                        else
                        {
                            Errors.Add(String.Format(CrozzleFileErrors.ColumnError, aCrozzleFileItem.KeyValue.OriginalKeyValue, Validator.Errors[0]));
                        }
                    }

                    else if (aCrozzleFileItem.IsRow)
                    {
                        // Collect potential word data for a horizontal word.
                        wordData.Add(aCrozzleFileItem.KeyValue.OriginalKeyValue);
                    }
                    else if (aCrozzleFileItem.IsColumn)
                    {
                        // Collect potential word data for a vertical word.
                        wordData.Add(aCrozzleFileItem.KeyValue.OriginalKeyValue);
                    }
                }
                else
                {
                    Errors.AddRange(CrozzleFileItem.Errors);
                }
            }

            // Close files.
            fileIn.Close();

            // If the file does not have location and orientation of words
            if (wordData.Count == 0)
            {
                // Initialize an empty key-value group
                List <String> GenerateKeyValueGroup = new List <String>();

                // Use an dictionary to store inserting and non-inserting words score
                Dictionary <char, int> IntersectingPointsPerLetter    = new Dictionary <char, int>();
                Dictionary <char, int> NonIntersectingPointsPerLetter = new Dictionary <char, int>();

                // Append score to corresponding letter
                char[] alphabet = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
                for (int i = 0; i < alphabet.Length; i++)
                {
                    IntersectingPointsPerLetter.Add(alphabet[i], aConfiguration.IntersectingPointsPerLetter[i]);
                    NonIntersectingPointsPerLetter.Add(alphabet[i], aConfiguration.NonIntersectingPointsPerLetter[i]);
                }

                // Use greedy algorithm to get a group with maximun number of words
                Grid grid = new Grid(aCrozzle.Rows, aCrozzle.Columns, IntersectingPointsPerLetter, NonIntersectingPointsPerLetter, aConfiguration.PointsPerWord);
                grid.GetConfiguration(aCrozzle.Configuration);
                GenerateKeyValueGroup = grid.GreedyAlgorithm(wordList.List, aConfiguration.MaximumNumberOfGroups, aConfiguration.MinimumNumberOfGroups, out aCrozzle.timeConsume);

                // Append NewkeyValue instead of OriginalKeyValue to old program in terms of compatibility
                foreach (string GenerateKeyValue in GenerateKeyValueGroup)
                {
                    wordData.Add(GenerateKeyValue);
                }
            }

            // Get potential word data list.
            WordDataList wordDataList;

            if (!WordDataList.TryParse(wordData, aCrozzle, out wordDataList))
            {
                Errors.AddRange(WordDataList.Errors);
            }
            aCrozzle.WordDataList = wordDataList;


            // Validate file sections.
            // Check the configuration file name.
            if (aCrozzle.Configuration != null)
            {
                if (aCrozzle.Configuration.ConfigurationPath != aCrozzle.ConfigurationPath)
                {
                    Errors.Add(String.Format(CrozzleFileErrors.ConfigurationFilenameError, aCrozzle.ConfigurationPath, aCrozzle.Configuration.ConfigurationFileName));
                }
            }

            // Check the word list file name.
            if (aCrozzle.WordList != null)
            {
                if (aCrozzle.WordList.WordlistPath != aCrozzle.WordListPath)
                {
                    Errors.Add(String.Format(CrozzleFileErrors.WordlistFilenameError, aCrozzle.WordListPath, aCrozzle.WordList.WordlistFileName));
                }
            }

            // Raw word data of horizontal and vertical words were obtained when reading the crozzle file,
            // but now we need to create crozzle rows and crozzle columns that represent the crozzle.
            aCrozzle.CreateCrozzleRows(aCrozzle.WordDataList);
            aCrozzle.CreateCrozzleColumns(aCrozzle.WordDataList);

            // Store validity.
            aCrozzle.FileValid = Errors.Count == 0;
            return(aCrozzle.FileValid);
        }
Exemplo n.º 9
0
        public static Boolean TryParse(String path, Configuration aConfiguration, out WordList aWordList)
        {
            Errors = new List <String>();
            // path for wordlist
            aWordList = new WordList(path, aConfiguration);
            StreamReader    fileIn           = new StreamReader(path);
            List <Sequence> WordListSequence = new List <Sequence>();
            // Read all the line inside the file
            int row = 0;

            while (!fileIn.EndOfStream)
            {
                // New UPDATE
                // Split the original wordlist from the file usin specific regex
                // Which will skip the comma ',' inside the double-quotes
                Regex CSVParser = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
                aWordList.OriginalList = CSVParser.Split(fileIn.ReadLine());

                // Check each field in the wordlist.
                // which in the new class
                //int fieldNumber = 0;
                Sequence wordList = new Sequence();
                wordList.Word   = aWordList.OriginalList[0];
                wordList.Score  = aWordList.OriginalList[1];
                wordList.Length = aWordList.OriginalList[2];
                wordList.Ascii  = aWordList.OriginalList[3];
                wordList.Total  = aWordList.OriginalList[4];
                WordListSequence.Add(wordList);
                if (row > 0)
                {
                    Configuration.PointsPerWord.Add(aWordList.OriginalList[0] + "," + aWordList.OriginalList[1]);
                }
                row++;
            }
            int totalPointPerWord = 0;
            int totalLengthWord   = 0;
            int totalASCIIPoint   = 0;
            int totalAccPoint     = 0;

            // Repeat for all the word listed in the group
            for (int i = 1; i < WordListSequence.Capacity; i++)
            {
                if (Sequence.Test(WordListSequence[i].Word, WordListSequence[0].Word))
                {
                    if (Regex.IsMatch(WordListSequence[i].Word, Configuration.allowedCharacters))
                    {
                        aWordList.Add(WordListSequence[i].Word);
                    }
                    else
                    {
                        Errors.Add(String.Format(WordListErrors.AlphabeticError, WordListSequence[i].Word, i - 1));
                    }
                }
                else
                {
                    Errors.Add(String.Format(WordListErrors.UnidentifiedSequenceWordError, WordListSequence[i].Word));
                }

                // Check the total of character of the word
                // Initialisation
                int countChar;
                Validator.IsInt32(WordListSequence[i].Length, out countChar);
                if (WordListSequence[i].Word.Length != countChar)
                {
                    Errors.Add(String.Format(WordListErrors.CharacterWordLengthError, WordListSequence[i].Word));
                }
                int    asciiNum   = 0;
                byte[] asciiBytes = Encoding.ASCII.GetBytes(WordListSequence[i].Word);
                // Accumulating the ASCII score for each character inside a word
                foreach (byte ascii in asciiBytes)
                {
                    asciiNum += (int)ascii;
                }
                int asciiString;
                Validator.IsInt32(WordListSequence[i].Ascii, out asciiString);
                // If and error management
                if (asciiNum != asciiString)
                {
                    Errors.Add(String.Format(WordListErrors.AsciiNumberofWordError, WordListSequence[i].Word));
                }

                // Check the Total validation number of the word\
                // Initialisation
                int intScore;
                Validator.IsInt32(WordListSequence[i].Score, out intScore);
                int Total = asciiNum + intScore + countChar;
                int intTotal;
                // If and error management
                Validator.IsInt32(WordListSequence[i].Total, out intTotal);
                if (Total != intTotal)
                {
                    Errors.Add(String.Format(WordListErrors.TotalNumberValidationError, WordListSequence[i].Word));
                }
                // calculating the total point each row
                totalPointPerWord += intScore;
                totalLengthWord   += countChar;
                totalASCIIPoint   += asciiNum;
                totalAccPoint     += Total;
            }
            // Check the accumulation at the top for point row
            int rulesPoint;

            Validator.IsInt32(WordListSequence[0].Score, out rulesPoint);
            if (totalPointPerWord != rulesPoint)
            {
                Errors.Add(String.Format(WordListErrors.TotalPointPerRowError));
            }

            // Check the accumulation at the top for length row
            int rulesLength;

            Validator.IsInt32(WordListSequence[0].Length, out rulesLength);
            if (totalLengthWord != rulesLength)
            {
                Errors.Add(String.Format(WordListErrors.TotalLengthPointError));
            }

            // Check the accumulation at the top for ascii row
            int rulesASCII;

            Validator.IsInt32(WordListSequence[0].Ascii, out rulesASCII);
            if (totalASCIIPoint != rulesASCII)
            {
                Errors.Add(String.Format(WordListErrors.TotalAsciiPointError));
            }

            // Check the accumulation at the top for accumulation point row
            int rulesAccPoint;

            Validator.IsInt32(WordListSequence[0].Total, out rulesAccPoint);
            if (totalAccPoint != rulesAccPoint)
            {
                Errors.Add(String.Format(WordListErrors.TotalAccumulationPointError));
            }

            // Check the minimmum word limit.
            if (aWordList.Count < aConfiguration.MinimumNumberOfUniqueWords)
            {
                Errors.Add(String.Format(WordListErrors.MinimumSizeError, aWordList.Count, aConfiguration.MinimumNumberOfUniqueWords));
            }

            // Check the maximum word limit.
            if (aWordList.Count > aConfiguration.MaximumNumberOfUniqueWords)
            {
                Errors.Add(String.Format(WordListErrors.MaximumSizeError, aWordList.Count, aConfiguration.MaximumNumberOfUniqueWords));
            }

            aWordList.Valid = Errors.Count == 0;
            return(aWordList.Valid);
        }
Exemplo n.º 10
0
        private void openCrozzleFileRemotely()
        {
            crozzleToolStripMenuItem.Enabled = false;

            // Process crozzle file to get configuration filename
            String configurationFileName = GetConfigurationFileNameRemotely(crozzleComboBox.Text);

            if (configurationFileName == null)
            {
                MessageBox.Show("configuration filename is missing from the crozzle file", ApplicationAboutBox.AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                String filename = configurationFileName.Trim();
                if (Validator.IsDelimited(filename, Crozzle.StringDelimiters))
                {
                    filename = filename.Trim(Crozzle.StringDelimiters);
                }
                configurationFileName = filename;
            }

            // Parse configuration file.
            Configuration aConfiguration = null;

            Configuration.TryParse(configurationFileName, out aConfiguration, true);

            // Get wordlist filename.
            String wordListFileName = GetWordlistFileNameRemotely(crozzleComboBox.Text);

            if (wordListFileName == null)
            {
                MessageBox.Show("wordlist filename is missing from the crozzle file", ApplicationAboutBox.AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                String filename = wordListFileName.Trim();
                if (Validator.IsDelimited(filename, Crozzle.StringDelimiters))
                {
                    filename = filename.Trim(Crozzle.StringDelimiters);
                }
                wordListFileName = filename;
            }

            // Parse wordlist file.
            WordList wordList = null;

            WordList.TryParse(wordListFileName, aConfiguration, out wordList, true);

            // Parse crozzle file.
            Crozzle aCrozzle;

            Crozzle.TryParse(crozzleComboBox.Text, aConfiguration, wordList, out aCrozzle, true);
            SIT323Crozzle = aCrozzle;

            // Update GUI - menu enabled, display crozzle data (whether valid or invalid), and crozzle file errors.
            if (SIT323Crozzle.FileValid && SIT323Crozzle.Configuration.Valid && SIT323Crozzle.WordList.Valid)
            {
                crozzleToolStripMenuItem.Enabled = true;
            }

            crozzleWebBrowser.DocumentText          = SIT323Crozzle.ToStringHTML();
            ErrorListViewer.WebBrowser.DocumentText =
                SIT323Crozzle.FileErrorsHTML +
                SIT323Crozzle.Configuration.FileErrorsHTML +
                SIT323Crozzle.WordList.FileErrorsHTML;

            // Log errors.
            SIT323Crozzle.LogFileErrors(SIT323Crozzle.FileErrorsTXT, true);
            SIT323Crozzle.LogFileErrors(SIT323Crozzle.Configuration.FileErrorsTXT, true);
            SIT323Crozzle.LogFileErrors(SIT323Crozzle.WordList.FileErrors, true);
        }
Exemplo n.º 11
0
        private void saveAndOpenWebCrozzleFile()
        {
            string tempCrozzlePath       = @"..\..\..\TempCrozzleFile\TempCrozzle.txt";
            string tempWordlistPath      = @"..\..\..\TempCrozzleFile\TempWordlist.txt";
            string tempConfigurationPath = @"..\..\..\TempCrozzleFile\TempConfiguration.txt";

            this.downloadFile(this.comboBox1.Text, tempCrozzlePath);

            // As we are opening a crozzle file,
            // indicate crozzle file, and crozzle are not valid, and clear GUI.
            crozzleToolStripMenuItem.Enabled        = false;
            crozzleWebBrowser.DocumentText          = "";
            ErrorListViewer.WebBrowser.DocumentText = "";

            // Process crozzle file.
            // Get configuration filename.
            String configurationFileName = GetConfigurationFileName(tempCrozzlePath);

            if (configurationFileName == null)
            {
                MessageBox.Show("configuration filename is missing from the crozzle file", ApplicationAboutBox.AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                String filename = configurationFileName.Trim().Replace("\"", string.Empty);
                this.downloadFile(filename, tempConfigurationPath);
            }

            // Parse configuration file.
            Configuration aConfiguration = null;

            Configuration.TryParse(tempConfigurationPath, out aConfiguration);

            // Get wordlist filename.
            String wordListFileName = GetWordlistFileName(tempCrozzlePath);

            if (wordListFileName == null)
            {
                MessageBox.Show("wordlist filename is missing from the crozzle file", ApplicationAboutBox.AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                String filename = wordListFileName.Trim().Replace("\"", string.Empty);
                this.downloadFile(filename, tempWordlistPath);
            }

            // Parse wordlist file.
            WordList wordList = null;

            WordList.TryParse(tempWordlistPath, aConfiguration, out wordList);

            // Parse crozzle file.
            Crozzle aCrozzle;

            Crozzle.TryParse(tempCrozzlePath, aConfiguration, wordList, out aCrozzle);
            SIT323Crozzle = aCrozzle;

            // Update GUI - menu enabled, display crozzle data (whether valid or invalid), and crozzle file errors.
            if (SIT323Crozzle.FileValid && SIT323Crozzle.Configuration.Valid && SIT323Crozzle.WordList.Valid)
            {
                crozzleToolStripMenuItem.Enabled = true;
            }

            crozzleWebBrowser.DocumentText          = SIT323Crozzle.ToStringHTML();
            ErrorListViewer.WebBrowser.DocumentText =
                SIT323Crozzle.FileErrorsHTML +
                SIT323Crozzle.Configuration.FileErrorsHTML +
                SIT323Crozzle.WordList.FileErrorsHTML;

            // Log errors.
            SIT323Crozzle.LogFileErrors(SIT323Crozzle.FileErrorsTXT);
            SIT323Crozzle.LogFileErrors(SIT323Crozzle.Configuration.FileErrorsTXT);
            SIT323Crozzle.LogFileErrors(SIT323Crozzle.WordList.FileErrors);
        }
        public static Boolean TryParse(String path, Configuration aConfiguration, out WordList aWordList)
        {
            StreamReader fileIn = new StreamReader(path);

            Errors    = new List <String>();
            aWordList = new WordList(path, aConfiguration);

            // Split the original wordlist from the file and store it in a temporarily list
            String[] TempList = fileIn.ReadToEnd().Split(WordSeparators);

            // Find the first line in ".seq" for validation
            aWordList.Validation = new Validator(TempList[0]);
            // Clear the first line
            for (int i = 0; i < TempList.Length - 1; i++)
            {
                TempList[i] = TempList[i + 1];
            }
            // Clear the last line
            TempList[TempList.Length - 1] = "";


            // Use Lambda to append the list to originalList property
            aWordList.OriginalList = TempList.Where(s => !String.IsNullOrEmpty(s)).ToArray();

            // Find out whether wordlist contains duplicated content
            String duplicate = Validator.ContainsDuplicates(aWordList.OriginalList);

            if (duplicate != "")
            {
                Errors.Add(String.Format(WordListErrors.DuplicateError, duplicate));
            }

            // Check each field in the wordlist.
            int TotalScore = 0, TotalLength = 0, TotalASCII = 0, TotalHash = 0;

            foreach (String potentialWord in aWordList.OriginalList)
            {
                Validator line = new Validator(potentialWord);

                // If it goes to the last line
                if (String.IsNullOrEmpty(potentialWord))
                {
                    break;
                }
                TotalScore  += line.Score;
                TotalLength += line.Length;
                TotalASCII  += line.ASCII;
                TotalHash   += line.Hash;

                // Check the word and word length
                if (line.Length > 0)
                {
                    // Check that the field is alphabetic
                    if (Regex.IsMatch(line.Word, Configuration.allowedCharacters))
                    {
                        aWordList.Add(line);
                        // Check if the actual length of word is equal to its pre-defined length
                        if (line.Word.Length != line.Length)
                        {
                            Errors.Add(String.Format(WordListErrors.WordLengthError, line.Word, line.Length));
                        }

                        /*if (line.Word.Length == line.Length)
                         *  aWordList.Add(line);
                         * else
                         *  Errors.Add(String.Format(WordListErrors.WordLengthError, line.Word, line.Length));*/
                    }
                    else
                    {
                        Errors.Add(String.Format(WordListErrors.AlphabeticError, line.Word, line.OriginalLine));
                    }

                    // Check the word ASCII
                    if (line.GetWordASCII() == line.ASCII)
                    {
                        //TotalASCII += line.ASCII;
                    }
                    else
                    {
                        Errors.Add(String.Format(WordListErrors.WordASCIIError, line.Word, line.ASCII));
                    }
                    // Check the word Hash
                    if ((line.Length + line.Score + line.ASCII) == line.Hash)
                    {
                        //TotalHash += line.Hash;
                    }
                    else
                    {
                        Errors.Add(String.Format(WordListErrors.WordHashError, line.OriginalLine, line.Hash));
                    }
                }
                else
                {
                    if (line.Word.Length > 0)
                    {
                        Errors.Add(String.Format(WordListErrors.InvalidWordError, line.Word, line.OriginalLine));
                    }
                    else
                    {
                        Errors.Add(String.Format(WordListErrors.MissingWordError, line.OriginalLine));
                    }
                }
            }

            // Compare the total values above and those in the first line in ".seq"
            if (TotalLength != aWordList.Validation.Length)
            {
                Errors.Add(String.Format(WordListErrors.TotalLengthError, TotalLength, aWordList.Validation.Length));
            }
            if (TotalHash != aWordList.Validation.Hash)
            {
                Errors.Add(String.Format(WordListErrors.TotalHashError, TotalHash, aWordList.Validation.Hash));
            }
            if (TotalScore != aWordList.Validation.Score)
            {
                Errors.Add(String.Format(WordListErrors.TotalScoreError, TotalScore, aWordList.Validation.Score));
            }
            if (TotalASCII != aWordList.Validation.ASCII)
            {
                Errors.Add(String.Format(WordListErrors.TotalASCIIError, TotalASCII, aWordList.Validation.ASCII));
            }

            // Check the minimmum word limit.
            if (aWordList.Count < aConfiguration.MinimumNumberOfUniqueWords)
            {
                Errors.Add(String.Format(WordListErrors.MinimumSizeError, aWordList.Count, aConfiguration.MinimumNumberOfUniqueWords));
            }

            // Check the maximum word limit.
            if (aWordList.Count > aConfiguration.MaximumNumberOfUniqueWords)
            {
                Errors.Add(String.Format(WordListErrors.MaximumSizeError, aWordList.Count, aConfiguration.MaximumNumberOfUniqueWords));
            }

            aWordList.Valid = Errors.Count == 0;
            return(aWordList.Valid);
        }
Exemplo n.º 13
0
        public static Boolean TryParse(String path, Configuration aConfiguration, WordList wordList, out Crozzle aCrozzle)
        {
            Errors   = new List <String>();
            aCrozzle = new Crozzle(path, aConfiguration, wordList);

            // Open file.
            StreamReader            fileIn   = new StreamReader(path);
            List <SequenceFragment> wordData = new List <SequenceFragment>();

            // Validate file.
            while (!fileIn.EndOfStream)
            {
                List <String> fragment = new List <String>();
                do
                {
                    /// Add multiple lines as part of a text fragment until the last element is empty or null.
                    fragment.Add(fileIn.ReadLine());
                } while (!String.IsNullOrEmpty(fragment.Last()));

                // Parse a crozzle file fragment.
                FileFragment <CrozzleFileItem> aCrozzleFileFragment;
                if (CrozzleFileItem.TryParse(fragment, out aCrozzleFileFragment))
                {
                    String aFragmentKey = aCrozzleFileFragment.Name;

                    foreach (CrozzleFileItem aItem in aCrozzleFileFragment.Items)
                    {
                        /// Process the key-value, given the current fragment key.
                        if (aFragmentKey == CrozzleFileKeys.DEPENDENCIES_OPENBRACKET)
                        {
                            if (aItem.Name == CrozzleFileKeys.DEPENDENCIES_CONFIGDATA)
                            {
                                String configurationPath = aItem.KeyValue.Value;
                                if (configurationPath == null)
                                {
                                    Errors.Add(CrozzleFileErrors.ConfigurationFilenameMissing);
                                }
                                else
                                {
                                    configurationPath = configurationPath.Trim();
                                    if (Validator.IsDelimited(configurationPath, StringDelimiters))
                                    {
                                        configurationPath = configurationPath.Trim(StringDelimiters);
                                    }

                                    if (!Path.IsPathRooted(configurationPath))
                                    {
                                        String directoryName = Path.GetDirectoryName(path);
                                        configurationPath = directoryName + @"\" + configurationPath;
                                    }

                                    aCrozzle.ConfigurationPath = configurationPath;
                                }
                            }
                            else if (aItem.Name == CrozzleFileKeys.DEPENDENCIES_SEQDATA)
                            {
                                String wordListPath = aItem.KeyValue.Value;
                                if (wordListPath == null)
                                {
                                    Errors.Add(CrozzleFileErrors.WordlistFilenameMissing);
                                }
                                else
                                {
                                    wordListPath = wordListPath.Trim();
                                    if (Validator.IsDelimited(wordListPath, StringDelimiters))
                                    {
                                        wordListPath = wordListPath.Trim(StringDelimiters);
                                    }

                                    if (!Path.IsPathRooted(wordListPath))
                                    {
                                        String directoryName = Path.GetDirectoryName(path);
                                        wordListPath = directoryName + @"\" + wordListPath;
                                    }

                                    aCrozzle.WordListPath = wordListPath;
                                }
                            }
                        }
                        else if (aFragmentKey == CrozzleFileKeys.SIZE_OPENBRACKET)
                        {
                            int      rows, columns;
                            String[] values = aItem.KeyValue.Value.Trim().Split(',');
                            if (Validator.IsInt32(values[0], out rows))
                            {
                                aCrozzle.Rows = rows;
                            }
                            else
                            {
                                Errors.Add(String.Format(CrozzleFileErrors.RowError, aItem.KeyValue.OriginalKeyValue, Validator.Errors[0]));
                            }

                            if (Validator.IsInt32(values[1], out columns))
                            {
                                aCrozzle.Columns = columns;
                            }
                            else
                            {
                                Errors.Add(String.Format(CrozzleFileErrors.ColumnError, aItem.KeyValue.OriginalKeyValue, Validator.Errors[0]));
                            }
                        }
                        else if (new[] { CrozzleFileKeys.HORZSEQ_OPENBRACKET, CrozzleFileKeys.VERTSEQ_OPENBRACKET }.Contains(aFragmentKey))
                        {
                            wordData.Add(new SequenceFragment(aFragmentKey, aItem.KeyValue.OriginalKeyValue));
                        }
                        else
                        {
                            Errors.AddRange(CrozzleFileItem.Errors);
                        }
                    }
                }
            }

            // Close files.
            fileIn.Close();


            // Get potential word data list.
            WordDataList wordDataList;

            if (!WordDataList.TryParse(wordData, aCrozzle, out wordDataList))
            {
                Errors.AddRange(WordDataList.Errors);
            }
            aCrozzle.WordDataList = wordDataList;


            // Validate file sections.
            // Check the configuration file name.
            if (aCrozzle.Configuration != null)
            {
                if (aCrozzle.Configuration.ConfigurationPath != aCrozzle.ConfigurationPath)
                {
                    Errors.Add(String.Format(CrozzleFileErrors.ConfigurationFilenameError, aCrozzle.ConfigurationPath, aCrozzle.Configuration.ConfigurationFileName));
                }
            }

            // Check the word list file name.
            if (aCrozzle.WordList != null)
            {
                if (aCrozzle.WordList.WordlistPath != aCrozzle.WordListPath)
                {
                    Errors.Add(String.Format(CrozzleFileErrors.WordlistFilenameError, aCrozzle.WordListPath, aCrozzle.WordList.WordlistFileName));
                }
            }

            // Raw word data of horizontal and vertical words were obtained when reading the crozzle file,
            // but now we need to create crozzle rows and crozzle columns that represent the crozzle.
            aCrozzle.CreateCrozzleRows(aCrozzle.WordDataList);
            aCrozzle.CreateCrozzleColumns(aCrozzle.WordDataList);

            // Store validity.
            aCrozzle.FileValid = Errors.Count == 0;
            return(aCrozzle.FileValid);
        }
Exemplo n.º 14
0
        /* This section is added for Assessment 2 */
        private void button1_Click(object sender, EventArgs e)
        {
            // Crozzle generataion start
            label1.Text = "Generating crozzle...";
            // Get URL address
            crozzleName = URL.Text;

            String configurationFileName = GetConfigurationFileName(crozzleName);

            if (configurationFileName == null)
            {
                MessageBox.Show("configuration filename is missing from the crozzle file", ApplicationAboutBox.AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                String filename = configurationFileName.Trim();
                if (Validator.IsDelimited(filename, Crozzle.StringDelimiters))
                {
                    filename = filename.Trim(Crozzle.StringDelimiters);
                }
                configurationFileName = filename;

                if (!Path.IsPathRooted(configurationFileName) && !crozzleName.Contains("http"))
                {
                    configurationFileName = Path.GetDirectoryName(crozzleName) + @"\" + configurationFileName;
                }
            }

            // Parse configuration file.
            Configuration aConfiguration = null;

            Configuration.TryParse(configurationFileName, out aConfiguration);

            // Get wordlist filename.
            String wordListFileName = GetWordlistFileName(crozzleName);

            if (wordListFileName == null)
            {
                MessageBox.Show("wordlist filename is missing from the crozzle file", ApplicationAboutBox.AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            else
            {
                String filename = wordListFileName.Trim();
                if (Validator.IsDelimited(filename, Crozzle.StringDelimiters))
                {
                    filename = filename.Trim(Crozzle.StringDelimiters);
                }
                wordListFileName = filename;

                if (!Path.IsPathRooted(wordListFileName) && !crozzleName.Contains("http"))
                {
                    wordListFileName = Path.GetDirectoryName(crozzleName) + @"\" + wordListFileName;
                }
            }

            // Parse wordlist file.
            WordList wordList = null;

            WordList.TryParse(wordListFileName, aConfiguration, out wordList);

            // Parse crozzle file.
            Crozzle aCrozzle;

            Crozzle.TryParse(crozzleName, aConfiguration, wordList, out aCrozzle);
            SIT323Crozzle = aCrozzle;

            // Update GUI - menu enabled, display crozzle data (whether valid or invalid), and crozzle file errors.
            if (SIT323Crozzle.FileValid && SIT323Crozzle.Configuration.Valid && SIT323Crozzle.WordList.Valid)
            {
                crozzleToolStripMenuItem.Enabled = true;
            }

            crozzleWebBrowser.DocumentText          = SIT323Crozzle.ToStringHTML();
            ErrorListViewer.WebBrowser.DocumentText =
                SIT323Crozzle.FileErrorsHTML +
                SIT323Crozzle.Configuration.FileErrorsHTML +
                SIT323Crozzle.WordList.FileErrorsHTML;

            // Crozzle generataion complete
            label1.Text = "Crozzle generation succeed";

            // Log errors.
            SIT323Crozzle.LogFileErrors(SIT323Crozzle.FileErrorsTXT);
            SIT323Crozzle.LogFileErrors(SIT323Crozzle.Configuration.FileErrorsTXT);
            SIT323Crozzle.LogFileErrors(SIT323Crozzle.WordList.FileErrors);
        }
Exemplo n.º 15
0
        private void openCrozzleFile()
        {
            DialogResult result;

            // As we are opening a crozzle file,
            // indicate crozzle file, and crozzle are not valid, and clear GUI.
            crozzleToolStripMenuItem.Enabled        = false;
            crozzleWebBrowser.DocumentText          = "";
            ErrorListViewer.WebBrowser.DocumentText = "";

            // Process crozzle file.
            result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                // Get configuration filename.
                String configurationFileName = GetConfigurationFileName(openFileDialog1.FileName);
                if (configurationFileName == null)
                {
                    MessageBox.Show("configuration filename is missing from the crozzle file", ApplicationAboutBox.AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // Add root to the path
                else
                {
                    String filename = configurationFileName.Trim();
                    if (Validator.IsDelimited(filename, Crozzle.StringDelimiters))
                    {
                        filename = filename.Trim(Crozzle.StringDelimiters);
                    }
                    configurationFileName = filename;

                    if (!Path.IsPathRooted(configurationFileName))
                    {
                        configurationFileName = Path.GetDirectoryName(openFileDialog1.FileName) + @"\" + configurationFileName;
                    }
                }

                // Parse configuration file.
                Configuration aConfiguration = null;
                Configuration.TryParse(configurationFileName, out aConfiguration);

                // Get wordlist filename.
                String wordListFileName = GetWordlistFileName(openFileDialog1.FileName);
                if (wordListFileName == null)
                {
                    MessageBox.Show("wordlist filename is missing from the crozzle file", ApplicationAboutBox.AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                else
                {
                    String filename = wordListFileName.Trim();
                    if (Validator.IsDelimited(filename, Crozzle.StringDelimiters))
                    {
                        filename = filename.Trim(Crozzle.StringDelimiters);
                    }
                    wordListFileName = filename;

                    if (!Path.IsPathRooted(wordListFileName))
                    {
                        wordListFileName = Path.GetDirectoryName(openFileDialog1.FileName) + @"\" + wordListFileName;
                    }
                }

                // Parse wordlist file.
                WordList wordList = null;
                WordList.TryParse(wordListFileName, aConfiguration, out wordList);

                // Parse crozzle file.
                Crozzle aCrozzle;
                Crozzle.TryParse(openFileDialog1.FileName, aConfiguration, wordList, out aCrozzle);
                SIT323Crozzle = aCrozzle;

                // Update GUI - menu enabled, display crozzle data (whether valid or invalid), and crozzle file errors.
                if (SIT323Crozzle.FileValid && SIT323Crozzle.Configuration.Valid && SIT323Crozzle.WordList.Valid)
                {
                    crozzleToolStripMenuItem.Enabled = true;
                }

                crozzleWebBrowser.DocumentText          = SIT323Crozzle.ToStringHTML();
                ErrorListViewer.WebBrowser.DocumentText =
                    SIT323Crozzle.FileErrorsHTML +
                    SIT323Crozzle.Configuration.FileErrorsHTML +
                    SIT323Crozzle.WordList.FileErrorsHTML;

                // Log errors.
                SIT323Crozzle.LogFileErrors(SIT323Crozzle.FileErrorsTXT);
                SIT323Crozzle.LogFileErrors(SIT323Crozzle.Configuration.FileErrorsTXT);
                SIT323Crozzle.LogFileErrors(SIT323Crozzle.WordList.FileErrors);
            }
        }
Exemplo n.º 16
0
        public static Boolean TryParse(String path, Configuration aConfiguration, WordList wordList, out Crozzle aCrozzle, bool isRemote = false)
        {
            Errors   = new List <String>();
            aCrozzle = new Crozzle(path, aConfiguration, wordList, isRemote);

            // Open file.
            StreamReader fileIn = null;

            if (!isRemote)
            {
                fileIn = new StreamReader(path);
            }
            else
            {
                WebClient webClient = new WebClient();
                Stream    stream    = webClient.OpenRead(path);
                fileIn = new StreamReader(stream);
            }

            List <String> wordData = new List <string>();

            // Validate file.
            while (!fileIn.EndOfStream)
            {
                // Read a line.
                String line = fileIn.ReadLine();

                // Parse a crozzle file item.
                CrozzleFileItem aCrozzleFileItem;
                if (CrozzleFileItem.TryParse(line, out aCrozzleFileItem))
                {
                    if (aCrozzleFileItem.IsConfigurationFile)
                    {
                        // Get the configuration file name.
                        String configurationPath = aCrozzleFileItem.KeyValue.Value;
                        if (configurationPath == null)
                        {
                            Errors.Add(CrozzleFileErrors.ConfigurationFilenameMissing);
                        }
                        else
                        {
                            configurationPath = configurationPath.Trim();
                            if (Validator.IsDelimited(configurationPath, StringDelimiters))
                            {
                                configurationPath = configurationPath.Trim(StringDelimiters);
                            }

                            if (!isRemote && !Path.IsPathRooted(configurationPath))
                            {
                                String directoryName = Path.GetDirectoryName(path);
                                configurationPath = directoryName + @"\" + configurationPath;
                            }

                            aCrozzle.ConfigurationPath = configurationPath;
                        }
                    }
                    else if (aCrozzleFileItem.IsWordListFile)
                    {
                        // Get the word list file name.
                        String wordListPath = aCrozzleFileItem.KeyValue.Value;
                        if (wordListPath == null)
                        {
                            Errors.Add(CrozzleFileErrors.WordlistFilenameMissing);
                        }
                        else
                        {
                            wordListPath = wordListPath.Trim();
                            if (Validator.IsDelimited(wordListPath, StringDelimiters))
                            {
                                wordListPath = wordListPath.Trim(StringDelimiters);
                            }

                            if (!isRemote && !Path.IsPathRooted(wordListPath))
                            {
                                String directoryName = Path.GetDirectoryName(path);
                                wordListPath = directoryName + @"\" + wordListPath;
                            }

                            aCrozzle.WordListPath = wordListPath;
                        }
                    }
                    else if (aCrozzleFileItem.IsRows)
                    {
                        // Get the number of rows.
                        int rows;
                        if (Validator.IsInt32(aCrozzleFileItem.KeyValue.Value.Trim(), out rows))
                        {
                            aCrozzle.Rows = rows;
                        }
                        else
                        {
                            Errors.Add(String.Format(CrozzleFileErrors.RowError, aCrozzleFileItem.KeyValue.OriginalKeyValue, Validator.Errors[0]));
                        }
                    }
                    else if (aCrozzleFileItem.IsColumns)
                    {
                        // Get the number of columns.
                        int columns;
                        if (Validator.IsInt32(aCrozzleFileItem.KeyValue.Value.Trim(), out columns))
                        {
                            aCrozzle.Columns = columns;
                        }
                        else
                        {
                            Errors.Add(String.Format(CrozzleFileErrors.ColumnError, aCrozzleFileItem.KeyValue.OriginalKeyValue, Validator.Errors[0]));
                        }
                    }
                    else if (aCrozzleFileItem.IsRow)
                    {
                        // Collect potential word data for a horizontal word.
                        wordData.Add(aCrozzleFileItem.KeyValue.OriginalKeyValue);
                    }
                    else if (aCrozzleFileItem.IsColumn)
                    {
                        // Collect potential word data for a vertical word.
                        wordData.Add(aCrozzleFileItem.KeyValue.OriginalKeyValue);
                    }
                }
                else
                {
                    Errors.AddRange(CrozzleFileItem.Errors);
                }
            }

            // Close files.
            fileIn.Close();

            aCrozzle.Node = Node.GreedyAlgorithm(aCrozzle.Rows, aCrozzle.Columns, aConfiguration, wordList.List);

            // Validate file sections.
            // Check the configuration file name.
            if (aCrozzle.Configuration != null)
            {
                if (aCrozzle.Configuration.ConfigurationPath != aCrozzle.ConfigurationPath)
                {
                    Errors.Add(String.Format(CrozzleFileErrors.ConfigurationFilenameError, aCrozzle.ConfigurationPath, aCrozzle.Configuration.ConfigurationFileName));
                }
            }

            // Check the word list file name.
            if (aCrozzle.WordList != null)
            {
                if (aCrozzle.WordList.WordlistPath != aCrozzle.WordListPath)
                {
                    Errors.Add(String.Format(CrozzleFileErrors.WordlistFilenameError, aCrozzle.WordListPath, aCrozzle.WordList.WordlistFileName));
                }
            }

            aCrozzle.CrozzleRows    = aCrozzle.Node.Grid.GridRows;
            aCrozzle.CrozzleColumns = aCrozzle.Node.Grid.GridColumns;

            // Store validity.
            aCrozzle.FileValid = Errors.Count == 0;
            return(aCrozzle.FileValid);
        }
Exemplo n.º 17
0
        public static Boolean TryParse(String path, Configuration aConfiguration, WordList wordList, out Crozzle aCrozzle)
        {
            Errors   = new List <String>();
            aCrozzle = new Crozzle(path, aConfiguration, wordList);

            // Open file.
            StreamReader         fileIn   = new StreamReader(path);
            List <TitleSequence> wordData = new List <TitleSequence>();

            // Validate file.
            while (!fileIn.EndOfStream)
            {
                // Create a Block to store a group of data
                List <String> Block = new List <String>();

                // Read a line.
                String line = fileIn.ReadLine();
                while (!String.IsNullOrEmpty(line))
                {
                    Block.Add(line);
                    line = fileIn.ReadLine();
                }

                // Parse a block in crozzle file
                CzlGroup aCrozzleFileGroup;
                if (CrozzleFileItem.TryParse(Block, out aCrozzleFileGroup))
                {
                    String title = aCrozzleFileGroup.CzlTitle;

                    for (int i = 0; i < aCrozzleFileGroup.Lines.Count; i++)
                    {
                        // Whether the title equals to "FILE-DEPENDENCIES"
                        if (title == CrozzleKeys.FileDependencies)
                        {
                            if (aCrozzleFileGroup.Lines[i].Name == CrozzleKeys.ConfigData)
                            {
                                String configurationPath = aCrozzleFileGroup.Lines[i].KeyValue.Value;
                                if (configurationPath == null)
                                {
                                    Errors.Add(CrozzleFileErrors.ConfigurationFilenameMissing);
                                }
                                else
                                {
                                    configurationPath = configurationPath.Trim();

                                    if (Validator.IsDelimited(configurationPath, StringDelimiters))
                                    {
                                        configurationPath = configurationPath.Trim(StringDelimiters);
                                    }

                                    if (!Path.IsPathRooted(configurationPath))
                                    {
                                        String directoryName = Path.GetDirectoryName(path);
                                        configurationPath = directoryName + @"\" + configurationPath;
                                    }

                                    aCrozzle.ConfigurationPath = configurationPath;
                                }
                            }
                            else if (aCrozzleFileGroup.Lines[i].Name == CrozzleKeys.SequenceData)
                            {
                                String wordListPath = aCrozzleFileGroup.Lines[i].KeyValue.Value;
                                if (wordListPath == null)
                                {
                                    Errors.Add(CrozzleFileErrors.ConfigurationFilenameMissing);
                                }
                                else
                                {
                                    wordListPath = wordListPath.Trim();

                                    if (Validator.IsDelimited(wordListPath, StringDelimiters))
                                    {
                                        wordListPath = wordListPath.Trim(StringDelimiters);
                                    }

                                    if (!Path.IsPathRooted(wordListPath))
                                    {
                                        String directoryName = Path.GetDirectoryName(path);
                                        wordListPath = directoryName + @"\" + wordListPath;
                                    }

                                    aCrozzle.WordListPath = wordListPath;
                                }
                            }
                        }

                        // Whether the title equals to "CROZZLE-SIZE"
                        else if (title == CrozzleKeys.CrozzleSize)
                        {
                            int      rows, columns;
                            String[] coordinate = aCrozzleFileGroup.Lines[i].KeyValue.Value.Split(',');
                            if (Validator.IsInt32(coordinate[0].Trim(), out rows))
                            {
                                aCrozzle.Rows = rows;
                            }
                            else
                            {
                                Errors.Add(String.Format(CrozzleFileErrors.RowError, aCrozzleFileGroup.Lines[i].KeyValue.OriginalKeyValue, Errors[0]));
                            }

                            if (Validator.IsInt32(coordinate[1].Trim(), out columns))
                            {
                                aCrozzle.Columns = columns;
                            }
                            else
                            {
                                Errors.Add(String.Format(CrozzleFileErrors.ColumnError, aCrozzleFileGroup.Lines[i].KeyValue.OriginalKeyValue, Errors[1]));
                            }
                        }

                        // Whether the title equals to "HORIZONTAL-SEQUENCES" or "VERTICAL-SEQUENCE"
                        else if (title == CrozzleKeys.HorizontalSequence || title == CrozzleKeys.VerticalSequence)
                        {
                            TitleSequence temp = new TitleSequence(title, aCrozzleFileGroup.Lines[i].KeyValue.OriginalKeyValue);
                            wordData.Add(temp);
                        }

                        // If there exist unidentified titles
                        else
                        {
                            Errors.AddRange(CrozzleFileItem.Errors);
                        }
                    }
                }
            }
            // Close files.
            fileIn.Close();

            // Get potential word data list.
            WordDataList wordDataList;

            if (!WordDataList.TryParse(wordData, aCrozzle, out wordDataList))
            {
                Errors.AddRange(WordDataList.Errors);
            }
            aCrozzle.WordDataList = wordDataList;


            // Validate file sections.
            // Check the configuration file name.
            if (aCrozzle.Configuration != null)
            {
                if (aCrozzle.Configuration.ConfigurationPath != aCrozzle.ConfigurationPath)
                {
                    Errors.Add(String.Format(CrozzleFileErrors.ConfigurationFilenameError, aCrozzle.ConfigurationPath, aCrozzle.Configuration.ConfigurationPath));
                }
            }

            // Check the word list file name.
            if (aCrozzle.WordList != null)
            {
                if (aCrozzle.WordList.WordlistPath != aCrozzle.WordListPath)
                {
                    Errors.Add(String.Format(CrozzleFileErrors.WordlistFilenameError, aCrozzle.WordListPath, aCrozzle.WordList.WordlistFileName));
                }
            }

            // Raw word data of horizontal and vertical words were obtained when reading the crozzle file,
            // but now we need to create crozzle rows and crozzle columns that represent the crozzle.
            aCrozzle.CreateCrozzleRows(aCrozzle.WordDataList);
            aCrozzle.CreateCrozzleColumns(aCrozzle.WordDataList);


            // Store validity.
            aCrozzle.FileValid = Errors.Count == 0;
            return(aCrozzle.FileValid);
        }