]> Dogcows Code - chaz/carfire/blobdiff - CarFire/CarFire/CarFire/MapReader.cs
Entity loading implemented.
[chaz/carfire] / CarFire / CarFire / CarFire / MapReader.cs
index 35089ba6531d7345f15e0a164790f01f81c3d322..cfb1f945219cb1bf73e315957bee1cc0fd7285f4 100644 (file)
@@ -2,10 +2,10 @@ using System;
 using System.Collections.Generic;\r
 using System.Linq;\r
 using System.Runtime.Serialization;\r
-using System.Text.RegularExpressions;\r
 using Microsoft.Xna.Framework;\r
 using Microsoft.Xna.Framework.Content;\r
 using Microsoft.Xna.Framework.Graphics;\r
+using System.Reflection;\r
 \r
 namespace CarFire\r
 {\r
@@ -15,272 +15,429 @@ namespace CarFire
     /// </summary>\r
     public class MapReader : ContentTypeReader<Map>\r
     {\r
+        #region Public Exceptions\r
+\r
+        /// <summary>\r
+        /// This exception is thrown during the loading of a map if any\r
+        /// part of the map file is inconsistent with the expected format\r
+        /// and order.\r
+        /// </summary>\r
         public class ParserException : System.ApplicationException\r
         {\r
-            public ParserException()\r
-            {\r
-            }\r
+            public ParserException() {}\r
 \r
             public ParserException(string message) :\r
-                base(message)\r
-            {\r
-            }\r
+                base(message) {}\r
 \r
             public ParserException(string message, System.Exception inner) :\r
-                base(message, inner)\r
-            {\r
-            }\r
+                base(message, inner) {}\r
 \r
             protected ParserException(SerializationInfo info, StreamingContext context) :\r
-                base(info, context)\r
-            {\r
-            }\r
+                base(info, context) {}\r
         }\r
 \r
-        ContentReader mInput;\r
-        int mLineNumber = 0;\r
-        int mExpectedNumberOfLines;\r
+        #endregion\r
 \r
-        Map.Data mData;\r
 \r
+        #region Protected Methods\r
 \r
         protected override Map Read(ContentReader input, Map existingInstance)\r
         {\r
-            mInput = input;\r
-            mExpectedNumberOfLines =  mInput.ReadInt32();\r
+            mImpl = new Impl(input);\r
+            return mImpl.GetMap();\r
+        }\r
 \r
-            ReadData();\r
+        #endregion\r
 \r
-            return new Map(mData);\r
-        }\r
 \r
+        #region Private Types\r
 \r
-        #region Private Reading Methods\r
-        \r
-        string ReadLine()\r
+        /// <summary>\r
+        /// This private class wraps around ContentReader to make it more\r
+        /// convenient to use it as an input stream reader.\r
+        /// </summary>\r
+        class LineReader\r
         {\r
-            return mInput.ReadString();\r
+            ContentReader mInput;\r
+            int mLineNumber = 0;\r
+            int mExpectedNumberOfLines;\r
+\r
+            public LineReader(ContentReader input)\r
+            {\r
+                mInput = input;\r
+                mExpectedNumberOfLines = mInput.ReadInt32();\r
+            }\r
+\r
+            public string ReadLine()\r
+            {\r
+                mLineNumber++;\r
+                return mInput.ReadString();\r
+            }\r
+\r
+            public int LineNumber { get { return mLineNumber; } }\r
+\r
+            public bool End { get { return mLineNumber >= mExpectedNumberOfLines; } }\r
         }\r
 \r
-        void ReadData()\r
+\r
+        /// <summary>\r
+        /// This class is the actual implementation.  The implementation is wrapped\r
+        /// in a subclass because the invoker seems to only be able to invoke public\r
+        /// methods, and this needs to invoke methods that shouldn't be public.\r
+        /// </summary>\r
+        class Impl\r
         {\r
-            mData = new Map.Data();\r
+            public Impl(ContentReader input)\r
+            {\r
+                mInput = new LineReader(input);\r
+                ReadSectionHeaders();\r
+                PostProcess();\r
+            }\r
 \r
-            while (mLineNumber < mExpectedNumberOfLines)\r
+            public Map GetMap()\r
             {\r
-                string line = ReadLine();\r
-                mLineNumber++;\r
+                return new Map(mMetadata, mGrid, mEntities);\r
+            }\r
+\r
 \r
-                while (line != null)\r
+            public void ReadSectionHeaders()\r
+            {\r
+                mMetadata = new Map.Metadata();\r
+\r
+                while (!mInput.End)\r
                 {\r
-                    if (!IsLineSignificant(line)) break;\r
+                    string line = mInput.ReadLine();\r
 \r
-                    string section = Parse.IniSectionHeader(line);\r
-                    if (section != null)\r
+                    while (line != null)\r
                     {\r
-                        if (section == "metadata")\r
+                        if (!IsLineSignificant(line)) break;\r
+\r
+                        string section = Parse.IniSectionHeader(line);\r
+                        if (section != null)\r
                         {\r
-                            line = ReadMetadataSection();\r
+                            if (section == "metadata")\r
+                            {\r
+                                line = ReadMetadataSection();\r
+                            }\r
+                            else if (section == "maptable")\r
+                            {\r
+                                line = ReadMapTableSection();\r
+                            }\r
+                            else if (section.Length == 1 && IsValidEntityIdentifier(section[0]))\r
+                            {\r
+                                line = ReadEntitySection(section[0]);\r
+                            }\r
+                            else\r
+                            {\r
+                                throw new ParserException("Unexpected section on line " + mInput.LineNumber + ": " + section);\r
+                            }\r
                         }\r
-                        else if (section == "maptable")\r
+                        else\r
                         {\r
-                            line = ReadMapTableSection();\r
+                            throw new ParserException("Unexpected text on line " + mInput.LineNumber + ": " + line);\r
                         }\r
-                        else if (section.Length == 1)\r
+                    }\r
+                }\r
+            }\r
+\r
+            string ReadMetadataSection()\r
+            {\r
+                while (!mInput.End)\r
+                {\r
+                    string line = mInput.ReadLine();\r
+                    if (!IsLineSignificant(line)) continue;\r
+\r
+                    string[] pair = Parse.KeyValuePair(line);\r
+                    if (pair != null)\r
+                    {\r
+                        try\r
                         {\r
-                            line = ReadEntitySection(section[0]);\r
+                            string methodName = "set_" + pair[0].ToLowerInvariant();\r
+                            object[] args = new object[1];\r
+                            args[0] = pair[1];\r
+                            GetType().InvokeMember(methodName, BindingFlags.InvokeMethod, null, this, args);\r
                         }\r
-                        else\r
+#pragma warning disable 0168\r
+                        catch (System.MissingMethodException ex)\r
+#pragma warning restore 0168\r
                         {\r
-                            ThrowException("Unknown section", section);\r
+                            throw new ParserException("Unexpected key on line " + mInput.LineNumber + ": " + pair[0]);\r
                         }\r
                     }\r
                     else\r
                     {\r
-                        ThrowException("Unexpected text", line);\r
+                        return line;\r
                     }\r
                 }\r
+\r
+                return null;\r
             }\r
-        }\r
 \r
-        string ReadMetadataSection()\r
-        {\r
-            while (mLineNumber < mExpectedNumberOfLines)\r
+            string ReadMapTableSection()\r
             {\r
-                string line = ReadLine();\r
-                mLineNumber++;\r
+                if (mMetadata == null || mMetadata.GridWidth == 0 || mMetadata.GridHeight == 0)\r
+                {\r
+                    throw new ParserException("Unexpected section on line " + mInput.LineNumber +\r
+                        ": You must define the map dimensions before this section.");\r
+                }\r
 \r
-                if (!IsLineSignificant(line)) continue;\r
+                mGrid = new char[mMetadata.GridWidth, mMetadata.GridHeight];\r
 \r
-                string[] pair = Parse.KeyValuePair(line);\r
-                if (pair != null)\r
+                int y;\r
+                for (y = 0; y < mMetadata.GridHeight && !mInput.End; y++)\r
                 {\r
-                    if (pair[0] == "type")\r
+                    string line = mInput.ReadLine();\r
+\r
+                    if (line.Length < mMetadata.GridWidth)\r
                     {\r
-                        object type = Parse.Constant<Map.Type>(pair[1]);\r
-                        if (type != null)\r
-                        {\r
-                            mData.Type = (Map.Type)type;\r
-                        }\r
-                        else\r
-                        {\r
-                            ThrowException("Invalid type", pair[1]);\r
-                        }\r
+                        throw new ParserException("Unexpected EOL on line " + mInput.LineNumber +\r
+                            ": The number of characters should match the width dimension (" + mMetadata.GridWidth + ").");\r
                     }\r
-                    else if (pair[0] == "dimensions")\r
+\r
+                    for (int x = 0; x < mMetadata.GridWidth; x++)\r
                     {\r
-                        Point? dimensions = Parse.Coordinates(pair[1]);\r
-                        if (dimensions != null)\r
-                        {\r
-                            mData.Dimensions = dimensions.Value;\r
-                            if (mData.Dimensions.X <= 0 || mData.Dimensions.Y <= 0)\r
-                            {\r
-                                ThrowException("Invalid dimensions", pair[1]);\r
-                            }\r
-                        }\r
-                        else\r
-                        {\r
-                            ThrowException("Invalid value", pair[1]);\r
-                        }\r
+                        mGrid[x, y] = line[x];\r
                     }\r
-                    else if (pair[0] == "tileset")\r
+                }\r
+\r
+                if (y < mMetadata.GridHeight)\r
+                {\r
+                    throw new ParserException("Unexpected EOF on line " + mInput.LineNumber +\r
+                        ": The number of lines in this section should match the height dimension (" + mMetadata.GridHeight + ").");\r
+                }\r
+\r
+                return null;\r
+            }\r
+\r
+            string ReadEntitySection(char identifier)\r
+            {\r
+                Dictionary<string, string> pairs = new Dictionary<string, string>();\r
+                mEntitySections[identifier] = pairs;\r
+\r
+                while (!mInput.End)\r
+                {\r
+                    string line = mInput.ReadLine();\r
+\r
+                    string[] pair = Parse.KeyValuePair(line);\r
+                    if (pair != null)\r
                     {\r
-                        string tileset = Parse.String(pair[1]);\r
-                        if (tileset != null)\r
-                        {\r
-                            mData.Tileset = tileset;\r
-                        }\r
-                        else\r
-                        {\r
-                            ThrowException("Invalid tileset", pair[1]);\r
-                        }\r
+                        pairs[pair[0]] = pair[1];\r
                     }\r
-                    else if (pair[0] == "numplayers")\r
+                    else\r
                     {\r
-                        int[] numPlayers = Parse.Range(pair[1]);\r
-                        if (numPlayers != null)\r
-                        {\r
-                            mData.MinNumPlayers = numPlayers[0];\r
-                            mData.MaxNumPlayers = numPlayers[1];\r
-                            if (mData.MinNumPlayers <= 0 || mData.MaxNumPlayers <= 0 ||\r
-                                mData.MinNumPlayers > mData.MaxNumPlayers)\r
-                            {\r
-                                ThrowException("Invalid range", pair[1]);\r
-                            }\r
-                        }\r
-                        else\r
-                        {\r
-                            ThrowException("Invalid value", pair[1]);\r
-                        }\r
+                        return line;\r
                     }\r
-                    else if (pair[0] == "author")\r
+                }\r
+\r
+                return null;\r
+            }\r
+\r
+\r
+            void PostProcess()\r
+            {\r
+                if (mMetadata == null || mGrid == null)\r
+                {\r
+                    throw new ParserException("Missing a required section.  Make sure the metadata and grid are there.");\r
+                }\r
+\r
+                mEntities = new List<Map.RawEntity>();\r
+                mPlayerPositions = new Point[mMetadata.NumPlayers.Max() + 1];\r
+\r
+                // create entities defined completely\r
+                foreach (char identifier in mEntitySections.Keys)\r
+                {\r
+                    Dictionary<string, string> pairs = mEntitySections[identifier];\r
+                    if (pairs.ContainsKey("create"))\r
                     {\r
-                        string author = Parse.String(pair[1]);\r
-                        if (author != null)\r
+                        string[] list = Parse.List(pairs["create"]);\r
+                        foreach (string positionString in list)\r
                         {\r
-                            mData.Author = author;\r
-                        }\r
-                        else\r
-                        {\r
-                            ThrowException("Invalid value", pair[1]);\r
+                            Point? position = Parse.Coordinates(positionString);\r
+                            if (position != null)\r
+                            {\r
+                                Map.RawEntity createEntity = new Map.RawEntity();\r
+                                createEntity.Id = identifier;\r
+                                createEntity.Position = position.Value;\r
+                                createEntity.Attributes = pairs;\r
+                                mEntities.Add(createEntity);\r
+                            }\r
+                            else\r
+                            {\r
+                                throw new ParserException("Unexpected value of key `create' defined for entity " + identifier + ".");\r
+                            }\r
                         }\r
+                        pairs.Remove("create");\r
                     }\r
-                    else if (pair[0] == "levelname")\r
+                }\r
+\r
+                // create entities with positions defined on the grid\r
+                // and get player starting positions\r
+                for (int x = 0; x < mMetadata.GridWidth; x++)\r
+                {\r
+                    for (int y = 0; y < mMetadata.GridHeight; y++)\r
                     {\r
-                        string level = Parse.String(pair[1]);\r
-                        if (level != null)\r
+                        char identifier = mGrid[x, y];\r
+                        if (IsValidEntityIdentifier(identifier))\r
                         {\r
-                            mData.Name = level;\r
+                            if (mEntitySections.ContainsKey(identifier))\r
+                            {\r
+                                Map.RawEntity createEntity = new Map.RawEntity();\r
+                                createEntity.Id = identifier;\r
+                                createEntity.Position = new Point(x, y);\r
+                                createEntity.Attributes = mEntitySections[identifier];\r
+                                mEntities.Add(createEntity);\r
+                            }\r
+                            else\r
+                            {\r
+                                throw new ParserException("Unexpected entity (" + identifier +\r
+                                    ") placed on the grid at [" + x + "," + y + "] but not defined.");\r
+                            }\r
+                            mGrid[x, y] = mDefaultTile;\r
                         }\r
-                        else\r
+                        else if ('1' <= identifier && identifier <= '9')\r
                         {\r
-                            ThrowException("Invalid value", pair[1]);\r
+                            int playerNum = identifier - 48;\r
+                            if (playerNum < mPlayerPositions.Count())\r
+                            {\r
+                                mPlayerPositions[playerNum] = new Point(x, y);\r
+                            }\r
+                            mGrid[x, y] = mDefaultTile;\r
                         }\r
                     }\r
-                    else\r
-                    {\r
-                        Console.WriteLine("Unimplemented key: " + pair[0]);\r
-                    }\r
                 }\r
-                else\r
+\r
+                // check if all needed player positions are defined\r
+                for (int i = 1; i < mPlayerPositions.Count(); i++)\r
                 {\r
-                    return line;\r
+                    if (mPlayerPositions[i] == default(Point))\r
+                    {\r
+                        throw new ParserException("Not enough player positions were defined on the grid; " +\r
+                            "are missing a spot for player " + i + ".");\r
+                    }\r
                 }\r
             }\r
 \r
-            return null;\r
-        }\r
 \r
-        string ReadMapTableSection()\r
-        {\r
-            if (mData.Dimensions.X == 0 || mData.Dimensions.Y == 0)\r
+            bool IsLineSignificant(string line)\r
+            {\r
+                if (line.Trim().Length == 0 || Parse.IniComment(line) != null) return false;\r
+                return true;\r
+            }\r
+\r
+            bool IsValidEntityIdentifier(char id)\r
             {\r
-                ThrowException("Unexpected section", "You must define the map dimensions before this section.");\r
+                if (('a' <= id && id <= 'z') || ('A' <= id && id <= 'Z')) return true;\r
+                return false;\r
             }\r
 \r
-            mData.Grid = new char[mData.Dimensions.X, mData.Dimensions.Y];\r
 \r
-            int y;\r
-            for (y = 0; y < mData.Dimensions.Y && mLineNumber < mExpectedNumberOfLines; y++)\r
+            public void set_author(string atom)\r
             {\r
-                string line = ReadLine();\r
-                mLineNumber++;\r
+                string value = Parse.String(atom);\r
+                if (value != null) mMetadata.Author = value;\r
+                else throw new ParserException("Unexpected value on line " + mInput.LineNumber + ": " + atom);\r
+            }\r
 \r
-                if (line.Length < mData.Dimensions.X)\r
+            public void set_levelname(string atom)\r
+            {\r
+                string value = Parse.String(atom);\r
+                if (value != null) mMetadata.Name = value;\r
+                else throw new ParserException("Unexpected value on line " + mInput.LineNumber + ": " + atom);\r
+            }\r
+\r
+            public void set_type(string atom)\r
+            {\r
+                Map.Type value = Parse.Constant<Map.Type>(atom);\r
+                if (value != default(Map.Type)) mMetadata.Type = value;\r
+                else throw new ParserException("Unexpected type on line " + mInput.LineNumber + ": " + atom);\r
+            }\r
+\r
+            public void set_dimensions(string atom)\r
+            {\r
+                Point? dimensions = Parse.Coordinates(atom);\r
+                if (dimensions != null)\r
                 {\r
-                    ThrowException("Not enough characters", "Expecting " + mData.Dimensions.X + " characters.");\r
+                    mMetadata.GridWidth = dimensions.Value.X;\r
+                    mMetadata.GridHeight = dimensions.Value.Y;\r
+                    if (mMetadata.GridWidth <= 0 || mMetadata.GridHeight <= 0)\r
+                    {\r
+                        throw new ParserException("Invalid dimensions on line " + mInput.LineNumber + ": " + atom);\r
+                    }\r
                 }\r
-\r
-                for (int x = 0; x < mData.Dimensions.X; x++)\r
+                else\r
                 {\r
-                    mData.Grid[x, y] = line[x];\r
+                    throw new ParserException("Unexpected value on line " + mInput.LineNumber + ": " + atom);\r
                 }\r
             }\r
 \r
-            if (y < mData.Dimensions.Y)\r
+            public void set_tileset(string atom)\r
             {\r
-                ThrowException("Unexpected ", "");\r
+                string value = Parse.String(atom);\r
+                if (value != null) mMetadata.Tileset = value;\r
+                else throw new ParserException("Unexpected tileset on line " + mInput.LineNumber + ": " + atom);\r
             }\r
 \r
-            return null;\r
-        }\r
-\r
-        string ReadEntitySection(char entity)\r
-        {\r
-            while (mLineNumber < mExpectedNumberOfLines)\r
+            public void set_defaulttile(string atom)\r
             {\r
-                string line = ReadLine();\r
-                mLineNumber++;\r
+                char? value = Parse.Char(atom);\r
+                if (value != null) mDefaultTile = value.Value;\r
+                else throw new ParserException("Unexpected tile value on line " + mInput.LineNumber + ": " + atom);\r
+            }\r
 \r
-                string[] pair = Parse.KeyValuePair(line);\r
-                if (pair != null)\r
+            public void set_numplayers(string atom)\r
+            {\r
+                string[] list = Parse.List(atom);\r
+                if (list != null)\r
                 {\r
-                    // TODO\r
+                    foreach (string item in list)\r
+                    {\r
+                        int[] range = Parse.Range(item);\r
+                        if (range != null)\r
+                        {\r
+                            for (int i = range[0]; i <= range[1]; i++)\r
+                            {\r
+                                mMetadata.NumPlayers.Add(i);\r
+                            }\r
+                            continue;\r
+                        }\r
+                        int? integer = Parse.Integer(item);\r
+                        if (integer != null)\r
+                        {\r
+                            mMetadata.NumPlayers.Add(integer.Value);\r
+                            continue;\r
+                        }\r
+\r
+                        throw new ParserException("Unexpected atom on line " + mInput.LineNumber + ": " + item);\r
+                    }\r
+                    if (mMetadata.NumPlayers.Count == 0)\r
+                    {\r
+                        throw new ParserException("No numbers given on line " + mInput.LineNumber + ": " + atom);\r
+                    }\r
                 }\r
                 else\r
                 {\r
-                    return line;\r
+                    throw new ParserException("Unexpected value on line " + mInput.LineNumber + ": " + atom);\r
                 }\r
             }\r
 \r
-            return null;\r
+\r
+            Map.Metadata mMetadata;\r
+            char[,] mGrid;\r
+            List<Map.RawEntity> mEntities;\r
+            Point[] mPlayerPositions;\r
+\r
+            Dictionary<char, Dictionary<string, string>> mEntitySections = new Dictionary<char, Dictionary<string, string>>();\r
+            char mDefaultTile = ' ';\r
+\r
+            LineReader mInput;\r
         }\r
 \r
         #endregion\r
 \r
 \r
-        #region Private Methods\r
+        #region Private Variables\r
 \r
-        bool IsLineSignificant(string line)\r
-        {\r
-            if (line.Length == 0 || Regex.IsMatch(line, @"^;|^\s*$")) return false;\r
-            return true;\r
-        }\r
-\r
-        void ThrowException(string problem, string text)\r
-        {\r
-            throw new ParserException(problem + " on line " + mLineNumber + ": " + text);\r
-        }\r
+        Impl mImpl;\r
 \r
         #endregion\r
     }\r
This page took 0.031454 seconds and 4 git commands to generate.