Просмотр исходного кода

1.使用unity3d类似的Component设计模式,不同的游戏对象是不同的Component组合起来的
2.mongodb连接测试OK,Component组合起来的对象可以直接存入mongodb,并且可以直接从mongodb中读取生成对象,操作非常简单

tanghai 11 лет назад
Родитель
Сommit
ad42eb45ad

+ 15 - 0
CSharp/CSharp.sln

@@ -50,6 +50,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Controller", "Game\Controll
 EndProject
 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BehaviorTreeModule", "App\Modules\BehaviorTreeModule\BehaviorTreeModule.csproj", "{6CD185D1-08E0-4729-A999-2D5B57BA8193}"
 EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MongoDBTest", "Game\MongoDBTest\MongoDBTest.csproj", "{93FB20CF-827A-4CED-A273-90117EB7192F}"
+EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 		Debug|Any CPU = Debug|Any CPU
@@ -234,6 +236,18 @@ Global
 		{6CD185D1-08E0-4729-A999-2D5B57BA8193}.Release|Mixed Platforms.Build.0 = Release|Any CPU
 		{6CD185D1-08E0-4729-A999-2D5B57BA8193}.Release|Win32.ActiveCfg = Release|Any CPU
 		{6CD185D1-08E0-4729-A999-2D5B57BA8193}.Release|x86.ActiveCfg = Release|Any CPU
+		{93FB20CF-827A-4CED-A273-90117EB7192F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{93FB20CF-827A-4CED-A273-90117EB7192F}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{93FB20CF-827A-4CED-A273-90117EB7192F}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
+		{93FB20CF-827A-4CED-A273-90117EB7192F}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
+		{93FB20CF-827A-4CED-A273-90117EB7192F}.Debug|Win32.ActiveCfg = Debug|Any CPU
+		{93FB20CF-827A-4CED-A273-90117EB7192F}.Debug|x86.ActiveCfg = Debug|Any CPU
+		{93FB20CF-827A-4CED-A273-90117EB7192F}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{93FB20CF-827A-4CED-A273-90117EB7192F}.Release|Any CPU.Build.0 = Release|Any CPU
+		{93FB20CF-827A-4CED-A273-90117EB7192F}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
+		{93FB20CF-827A-4CED-A273-90117EB7192F}.Release|Mixed Platforms.Build.0 = Release|Any CPU
+		{93FB20CF-827A-4CED-A273-90117EB7192F}.Release|Win32.ActiveCfg = Release|Any CPU
+		{93FB20CF-827A-4CED-A273-90117EB7192F}.Release|x86.ActiveCfg = Release|Any CPU
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
 		HideSolutionNode = FALSE
@@ -254,5 +268,6 @@ Global
 		{0FA529D1-D0A9-4A8E-90F5-117CE80F2EDE} = {D0CC1FF4-2747-4278-A51F-BE9AA959175B}
 		{E69C1F22-E004-4D69-8667-787BD243454B} = {D0CC1FF4-2747-4278-A51F-BE9AA959175B}
 		{6CD185D1-08E0-4729-A999-2D5B57BA8193} = {C4C64188-4FAE-4CC3-A9E6-D9D4AF7429B6}
+		{93FB20CF-827A-4CED-A273-90117EB7192F} = {D0CC1FF4-2747-4278-A51F-BE9AA959175B}
 	EndGlobalSection
 EndGlobal

+ 1 - 0
CSharp/CSharp.sln.DotSettings

@@ -7,6 +7,7 @@
 	<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=ConvertToAutoProperty/@EntryIndexedValue">DO_NOT_SHOW</s:String>
 	<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=ConvertToAutoPropertyWithPrivateSetter/@EntryIndexedValue">DO_NOT_SHOW</s:String>
 	<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=DelegateSubtraction/@EntryIndexedValue">DO_NOT_SHOW</s:String>
+	<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=FieldCanBeMadeReadOnly_002EGlobal/@EntryIndexedValue">DO_NOT_SHOW</s:String>
 	<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=ForCanBeConvertedToForeach/@EntryIndexedValue">DO_NOT_SHOW</s:String>
 	<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=ImplicitlyCapturedClosure/@EntryIndexedValue">DO_NOT_SHOW</s:String>
 	<s:String x:Key="/Default/CodeInspection/Highlighting/InspectionSeverities/=InconsistentNaming/@EntryIndexedValue">DO_NOT_SHOW</s:String>

+ 3 - 1
CSharp/Game/BehaviorTree/BehaviorTree.csproj

@@ -52,7 +52,6 @@
     <Compile Include="NodeAttribute.cs" />
     <Compile Include="NodeType.cs" />
     <Compile Include="Not.cs" />
-    <Compile Include="Properties\AssemblyInfo.cs" />
     <Compile Include="Selector.cs" />
     <Compile Include="Sequence.cs" />
   </ItemGroup>
@@ -65,6 +64,9 @@
   <ItemGroup>
     <None Include="packages.config" />
   </ItemGroup>
+  <ItemGroup>
+    <Folder Include="Properties\" />
+  </ItemGroup>
   <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
   <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
   <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 

+ 0 - 39
CSharp/Game/BehaviorTree/Properties/AssemblyInfo.cs

@@ -1,39 +0,0 @@
-using System.Reflection;
-using System.Runtime.InteropServices;
-
-// 有关程序集的常规信息通过以下
-// 特性集控制。更改这些特性值可修改
-// 与程序集关联的信息。
-
-[assembly: AssemblyTitle("BehaviorTree")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("")]
-[assembly: AssemblyProduct("BehaviorTree")]
-[assembly: AssemblyCopyright("Copyright ©  2013")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// 将 ComVisible 设置为 false 使此程序集中的类型
-// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
-// 则将该类型上的 ComVisible 特性设置为 true。
-
-[assembly: ComVisible(false)]
-
-// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
-
-[assembly: Guid("cde1ceab-c151-495d-845e-53d620807b40")]
-
-// 程序集的版本信息由下面四个值组成:
-//
-//      主版本
-//      次版本 
-//      生成号
-//      修订号
-//
-// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
-// 方法是按如下所示使用“*”:
-// [assembly: AssemblyVersion("1.0.*")]
-
-[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]

+ 16 - 7
CSharp/Game/Controller/Controller.csproj

@@ -9,8 +9,9 @@
     <AppDesignerFolder>Properties</AppDesignerFolder>
     <RootNamespace>Controller</RootNamespace>
     <AssemblyName>Controller</AssemblyName>
-    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+    <TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
     <FileAlignment>512</FileAlignment>
+    <TargetFrameworkProfile />
   </PropertyGroup>
   <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
     <DebugSymbols>true</DebugSymbols>
@@ -32,15 +33,23 @@
   <ItemGroup>
     <Reference Include="System" />
     <Reference Include="System.Core" />
-    <Reference Include="System.Xml.Linq" />
-    <Reference Include="System.Data.DataSetExtensions" />
-    <Reference Include="Microsoft.CSharp" />
-    <Reference Include="System.Data" />
-    <Reference Include="System.Xml" />
   </ItemGroup>
   <ItemGroup>
     <Compile Include="BuffController.cs" />
-    <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="GameObjectFactory.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <Folder Include="Properties\" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="..\..\Platform\Common\Common.csproj">
+      <Project>{19f8f043-1f99-4550-99df-dea5c7d77e55}</Project>
+      <Name>Common</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\Model\Model.csproj">
+      <Project>{0fa529d1-d0a9-4a8e-90f5-117ce80f2ede}</Project>
+      <Name>Model</Name>
+    </ProjectReference>
   </ItemGroup>
   <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
   <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 

+ 14 - 0
CSharp/Game/Controller/GameObjectFactory.cs

@@ -0,0 +1,14 @@
+using Model;
+
+namespace Controller
+{
+    public class GameObjectFactory
+    {
+        public static GameObject CreatePlayer()
+        {
+            GameObject gameObject = new GameObject();
+            gameObject.AddComponent<BuffComponent>();
+            return gameObject;
+        }
+    }
+}

+ 0 - 39
CSharp/Game/Controller/Properties/AssemblyInfo.cs

@@ -1,39 +0,0 @@
-using System.Reflection;
-using System.Runtime.InteropServices;
-
-// 有关程序集的常规信息通过以下
-// 特性集控制。更改这些特性值可修改
-// 与程序集关联的信息。
-
-[assembly: AssemblyTitle("Controller")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Microsoft")]
-[assembly: AssemblyProduct("Controller")]
-[assembly: AssemblyCopyright("Copyright © Microsoft 2014")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// 将 ComVisible 设置为 false 使此程序集中的类型
-// 对 COM 组件不可见。  如果需要从 COM 访问此程序集中的类型,
-// 则将该类型上的 ComVisible 特性设置为 true。
-
-[assembly: ComVisible(false)]
-
-// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
-
-[assembly: Guid("2857e4a1-f2c1-4c17-8b67-6d25f98265ed")]
-
-// 程序集的版本信息由下面四个值组成: 
-//
-//      主版本
-//      次版本 
-//      生成号
-//      修订号
-//
-// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
-// 方法是按如下所示使用“*”: 
-// [assembly: AssemblyVersion("1.0.*")]
-
-[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]

+ 0 - 36
CSharp/Game/Handler/Properties/AssemblyInfo.cs

@@ -1,36 +0,0 @@
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-// 有关程序集的常规信息通过以下
-// 特性集控制。更改这些特性值可修改
-// 与程序集关联的信息。
-[assembly: AssemblyTitle("Logic")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("")]
-[assembly: AssemblyProduct("Logic")]
-[assembly: AssemblyCopyright("Copyright ©  2013")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// 将 ComVisible 设置为 false 使此程序集中的类型
-// 对 COM 组件不可见。  如果需要从 COM 访问此程序集中的类型,
-// 则将该类型上的 ComVisible 特性设置为 true。
-[assembly: ComVisible(false)]
-
-// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
-[assembly: Guid("f6d7a707-2a9f-4eac-9776-f3c56e4cd55a")]
-
-// 程序集的版本信息由下面四个值组成: 
-//
-//      主版本
-//      次版本 
-//      生成号
-//      修订号
-//
-// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
-// 方法是按如下所示使用“*”: 
-// [assembly: AssemblyVersion("1.0.*")]
-[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]

+ 14 - 1
CSharp/Game/Model/Buff.cs

@@ -1,9 +1,22 @@
 using Common.Base;
+using MongoDB.Bson.Serialization.Attributes;
 
 namespace Model
 {
     public class Buff: Object
     {
-        public int Type { get; set; }
+        private BuffType type;
+
+        public BuffType Type
+        {
+            get
+            {
+                return this.type;
+            }
+            set
+            {
+                this.type = value;
+            }
+        }
     }
 }

+ 116 - 0
CSharp/Game/Model/BuffComponent.cs

@@ -0,0 +1,116 @@
+using System.Collections.Generic;
+using System.ComponentModel;
+using Common.Base;
+using MongoDB.Bson;
+using MongoDB.Bson.Serialization.Attributes;
+using Component = Common.Base.Component;
+
+namespace Model
+{
+    public class BuffComponent: Component, ISupportInitialize
+    {
+        [BsonElement]
+        public HashSet<Buff> Buffs { get; set; }
+
+        private Dictionary<ObjectId, Buff> buffGuidDict { get; set; }
+
+        private MultiMap<BuffType, Buff> buffTypeMMap { get; set; }
+
+        public BuffComponent()
+        {
+            this.Buffs = new HashSet<Buff>();
+            this.buffGuidDict = new Dictionary<ObjectId, Buff>();
+            this.buffTypeMMap = new MultiMap<BuffType, Buff>();
+        }
+
+        void ISupportInitialize.BeginInit()
+        {
+        }
+
+        void ISupportInitialize.EndInit()
+        {
+            foreach (var buff in this.Buffs)
+            {
+                this.buffGuidDict.Add(buff.Guid, buff);
+            }
+
+            foreach (var buff in this.Buffs)
+            {
+                this.buffTypeMMap.Add(buff.Type, buff);
+            }
+        }
+
+        public bool Add(Buff buff)
+        {
+            if (this.Buffs.Contains(buff))
+            {
+                return false;
+            }
+
+            if (this.buffGuidDict.ContainsKey(buff.Guid))
+            {
+                return false;
+            }
+
+            if (this.buffTypeMMap.GetOne(buff.Type) != null)
+            {
+                return false;
+            }
+
+            this.Buffs.Add(buff);
+            this.buffGuidDict.Add(buff.Guid, buff);
+            this.buffTypeMMap.Add(buff.Type, buff);
+
+            return true;
+        }
+
+        public Buff GetByGuid(ObjectId guid)
+        {
+            if (!this.buffGuidDict.ContainsKey(guid))
+            {
+                return null;
+            }
+
+            return this.buffGuidDict[guid];
+        }
+
+        public Buff GetOneByType(BuffType type)
+        {
+            return this.buffTypeMMap.GetOne(type);
+        }
+
+        public Buff[] GetByType(BuffType type)
+        {
+            return this.buffTypeMMap.GetByKey(type);
+        }
+
+        private bool Remove(Buff buff)
+        {
+            if (buff == null)
+            {
+                return false;
+            }
+
+            this.Buffs.Remove(buff);
+            this.buffGuidDict.Remove(buff.Guid);
+            this.buffTypeMMap.Remove(buff.Type, buff);
+
+            return true;
+        }
+
+        public bool RemoveByGuid(ObjectId guid)
+        {
+            Buff buff = this.GetByGuid(guid);
+            return this.Remove(buff);
+        }
+
+        public void RemoveByType(BuffType type)
+        {
+            Buff[] buffs = this.GetByType(type);
+            foreach (Buff buff in buffs)
+            {
+                this.Remove(buff);
+            }
+        }
+    }
+}

+ 0 - 109
CSharp/Game/Model/BuffManager.cs

@@ -1,109 +0,0 @@
-using System.Collections.Generic;
-using System.ComponentModel;
-using Common.Base;
-using MongoDB.Bson;
-using MongoDB.Bson.Serialization.Attributes;
-using Component = Common.Base.Component;
-
-namespace Model
-{
-    public class BuffManager: Component, ISupportInitialize
-    {
-        public HashSet<Buff> Buffs { get; private set; }
-
-        [BsonIgnore]
-        public Dictionary<ObjectId, Buff> BuffGuidDict { get; private set; }
-
-        [BsonIgnore]
-        public MultiMap<int, Buff> BuffTypeDict { get; private set; }
-
-        public BuffManager()
-        {
-            this.Buffs = new HashSet<Buff>();
-            this.BuffGuidDict = new Dictionary<ObjectId, Buff>();
-            this.BuffTypeDict = new MultiMap<int, Buff>();
-        }
-
-        void ISupportInitialize.BeginInit()
-        {
-        }
-
-        void ISupportInitialize.EndInit()
-        {
-            foreach (var buff in this.Buffs)
-            {
-                this.BuffGuidDict.Add(buff.Guid, buff);
-            }
-
-            foreach (var buff in this.Buffs)
-            {
-                this.BuffTypeDict.Add(buff.Type, buff);
-            }
-        }
-
-        public bool Add(Buff buff)
-        {
-            if (this.Buffs.Contains(buff))
-            {
-                return false;
-            }
-
-            if (this.BuffGuidDict.ContainsKey(buff.Guid))
-            {
-                return false;
-            }
-
-            if (this.BuffTypeDict.Get(buff.Type) != null)
-            {
-                return false;
-            }
-
-            this.Buffs.Add(buff);
-            this.BuffGuidDict.Add(buff.Guid, buff);
-            this.BuffTypeDict.Add(buff.Type, buff);
-
-            return true;
-        }
-
-        public Buff GetByGuid(ObjectId guid)
-        {
-            if (!this.BuffGuidDict.ContainsKey(guid))
-            {
-                return null;
-            }
-
-            return this.BuffGuidDict[guid];
-        }
-
-        public Buff GetByType(int type)
-        {
-            return this.BuffTypeDict.Get(type);
-        }
-
-        private bool Remove(Buff buff)
-        {
-            if (buff == null)
-            {
-                return false;
-            }
-
-            this.Buffs.Remove(buff);
-            this.BuffGuidDict.Remove(buff.Guid);
-            this.BuffTypeDict.Remove(buff.Type, buff);
-
-            return true;
-        }
-
-        public bool RemoveByGuid(ObjectId guid)
-        {
-            Buff buff = this.GetByGuid(guid);
-            return this.Remove(buff);
-        }
-
-        public bool RemoveByType(int type)
-        {
-            Buff buff = this.GetByType(type);
-            return this.Remove(buff);
-        }
-    }
-}

+ 8 - 0
CSharp/Game/Model/BuffType.cs

@@ -0,0 +1,8 @@
+namespace Model
+{
+    public enum BuffType
+    {
+        // 眩晕
+        Dizziness = 0,
+    }
+}

+ 18 - 1
CSharp/Game/Model/GameObject.cs

@@ -2,8 +2,25 @@
 
 namespace Model
 {
+    public enum GameObjectType
+    {
+        Player = 0,
+    }
+
     public class GameObject: Entity
     {
-        public int Type { get; set; }
+        private GameObjectType type;
+
+        public GameObjectType Type
+        {
+            get
+            {
+                return this.type;
+            }
+            set
+            {
+                this.type = value;
+            }
+        }
     }
 }

+ 3 - 3
CSharp/Game/Model/GameObjectManager.cs

@@ -10,8 +10,8 @@ namespace Model
         private readonly Dictionary<ObjectId, GameObject> gameObjects =
                 new Dictionary<ObjectId, GameObject>();
 
-        private readonly Dictionary<int, Dictionary<ObjectId, GameObject>> typeGameObjects =
-                new Dictionary<int, Dictionary<ObjectId, GameObject>>();
+        private readonly Dictionary<GameObjectType, Dictionary<ObjectId, GameObject>> typeGameObjects =
+                new Dictionary<GameObjectType, Dictionary<ObjectId, GameObject>>();
 
         public void Add(GameObject gameObject)
         {
@@ -30,7 +30,7 @@ namespace Model
             return gameObject;
         }
 
-        public GameObject[] GetOneType(int type)
+        public GameObject[] GetOneType(GameObjectType type)
         {
             Dictionary<ObjectId, GameObject> oneTypeGameObjects = null;
             if (!this.typeGameObjects.TryGetValue(type, out oneTypeGameObjects))

+ 7 - 6
CSharp/Game/Model/Model.csproj

@@ -7,8 +7,8 @@
     <ProjectGuid>{0FA529D1-D0A9-4A8E-90F5-117CE80F2EDE}</ProjectGuid>
     <OutputType>Library</OutputType>
     <AppDesignerFolder>Properties</AppDesignerFolder>
-    <RootNamespace>Component</RootNamespace>
-    <AssemblyName>Component</AssemblyName>
+    <RootNamespace>Model</RootNamespace>
+    <AssemblyName>Model</AssemblyName>
     <TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
     <FileAlignment>512</FileAlignment>
     <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\</SolutionDir>
@@ -46,22 +46,23 @@
   </ItemGroup>
   <ItemGroup>
     <Compile Include="Buff.cs" />
-    <Compile Include="BuffManager.cs" />
+    <Compile Include="BuffComponent.cs" />
+    <Compile Include="BuffType.cs" />
     <Compile Include="GameObject.cs" />
     <Compile Include="GameObjectManager.cs" />
   </ItemGroup>
   <ItemGroup>
     <Folder Include="Properties\" />
   </ItemGroup>
-  <ItemGroup>
-    <None Include="packages.config" />
-  </ItemGroup>
   <ItemGroup>
     <ProjectReference Include="..\..\Platform\Common\Common.csproj">
       <Project>{19f8f043-1f99-4550-99df-dea5c7d77e55}</Project>
       <Name>Common</Name>
     </ProjectReference>
   </ItemGroup>
+  <ItemGroup>
+    <None Include="packages.config" />
+  </ItemGroup>
   <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
   <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
   <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 

+ 1 - 1
CSharp/Game/Model/packages.config

@@ -1,4 +1,4 @@
 <?xml version="1.0" encoding="utf-8"?>
 <packages>
-  <package id="mongocsharpdriver" version="1.9.2" targetFramework="net45" />
+  <package id="mongocsharpdriver" version="1.9.2" targetFramework="net451" />
 </packages>

+ 36 - 0
CSharp/Game/MongoDBTest/MongoDBTest.cs

@@ -0,0 +1,36 @@
+using System;
+using Common.Helper;
+using Controller;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using Model;
+using MongoDB.Driver;
+using MongoDB.Driver.Builders;
+
+namespace MongoDBTest
+{
+    [TestClass]
+    public class MongoDBTest
+    {
+        [TestMethod]
+        public void TestMongoDB()
+        {
+            const string connectionString = "mongodb://localhost";
+            var client = new MongoClient(connectionString);
+            var server = client.GetServer();
+            var database = server.GetDatabase("test");
+            var collection = database.GetCollection<GameObject>("GameObjects");
+
+            GameObject player1 = GameObjectFactory.CreatePlayer();
+            player1.GetComponent<BuffComponent>().Add(new Buff());
+            player1["hp"] = 10;
+
+            collection.Insert(player1);
+
+            var query = Query<GameObject>.EQ(e => e.Guid, player1.Guid);
+            GameObject player2 = collection.FindOne(query);
+
+            Console.WriteLine(MongoHelper.ToJson(player2));
+            Assert.AreEqual(MongoHelper.ToJson(player1), MongoHelper.ToJson(player2));
+        }
+    }
+}

+ 118 - 0
CSharp/Game/MongoDBTest/MongoDBTest.csproj

@@ -0,0 +1,118 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProjectGuid>{93FB20CF-827A-4CED-A273-90117EB7192F}</ProjectGuid>
+    <OutputType>Library</OutputType>
+    <AppDesignerFolder>Properties</AppDesignerFolder>
+    <RootNamespace>MongoDBTest</RootNamespace>
+    <AssemblyName>MongoDBTest</AssemblyName>
+    <TargetFrameworkVersion>v4.5.1</TargetFrameworkVersion>
+    <FileAlignment>512</FileAlignment>
+    <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
+    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
+    <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
+    <ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
+    <IsCodedUITest>False</IsCodedUITest>
+    <TestProjectType>UnitTest</TestProjectType>
+    <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\</SolutionDir>
+    <RestorePackages>true</RestorePackages>
+    <TargetFrameworkProfile />
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>..\..\Bin\Debug\</OutputPath>
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>pdbonly</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>..\..\Bin\Release\</OutputPath>
+    <DefineConstants>TRACE</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="MongoDB.Bson">
+      <HintPath>..\..\packages\mongocsharpdriver.1.9.2\lib\net35\MongoDB.Bson.dll</HintPath>
+    </Reference>
+    <Reference Include="MongoDB.Driver">
+      <HintPath>..\..\packages\mongocsharpdriver.1.9.2\lib\net35\MongoDB.Driver.dll</HintPath>
+    </Reference>
+    <Reference Include="System" />
+  </ItemGroup>
+  <Choose>
+    <When Condition="('$(VisualStudioVersion)' == '10.0' or '$(VisualStudioVersion)' == '') and '$(TargetFrameworkVersion)' == 'v3.5'">
+      <ItemGroup>
+        <Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
+      </ItemGroup>
+    </When>
+    <Otherwise>
+      <ItemGroup>
+        <Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework" />
+      </ItemGroup>
+    </Otherwise>
+  </Choose>
+  <ItemGroup>
+    <Compile Include="MongoDBTest.cs" />
+  </ItemGroup>
+  <ItemGroup>
+    <None Include="packages.config" />
+  </ItemGroup>
+  <ItemGroup>
+    <ProjectReference Include="..\..\Platform\Common\Common.csproj">
+      <Project>{19F8F043-1F99-4550-99DF-DEA5C7D77E55}</Project>
+      <Name>Common</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\Controller\Controller.csproj">
+      <Project>{e69c1f22-e004-4d69-8667-787bd243454b}</Project>
+      <Name>Controller</Name>
+    </ProjectReference>
+    <ProjectReference Include="..\Model\Model.csproj">
+      <Project>{0fa529d1-d0a9-4a8e-90f5-117ce80f2ede}</Project>
+      <Name>Model</Name>
+    </ProjectReference>
+  </ItemGroup>
+  <ItemGroup>
+    <Folder Include="Properties\" />
+  </ItemGroup>
+  <Choose>
+    <When Condition="'$(VisualStudioVersion)' == '10.0' And '$(IsCodedUITest)' == 'True'">
+      <ItemGroup>
+        <Reference Include="Microsoft.VisualStudio.QualityTools.CodedUITestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
+          <Private>False</Private>
+        </Reference>
+        <Reference Include="Microsoft.VisualStudio.TestTools.UITest.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
+          <Private>False</Private>
+        </Reference>
+        <Reference Include="Microsoft.VisualStudio.TestTools.UITest.Extension, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
+          <Private>False</Private>
+        </Reference>
+        <Reference Include="Microsoft.VisualStudio.TestTools.UITesting, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
+          <Private>False</Private>
+        </Reference>
+      </ItemGroup>
+    </When>
+  </Choose>
+  <Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+  <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
+  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
+    <PropertyGroup>
+      <ErrorText>这台计算机上缺少此项目引用的 NuGet 程序包。启用“NuGet 程序包还原”可下载这些程序包。有关详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。</ErrorText>
+    </PropertyGroup>
+    <Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
+  </Target>
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
+       Other similar extension points exist, see Microsoft.Common.targets.
+  <Target Name="BeforeBuild">
+  </Target>
+  <Target Name="AfterBuild">
+  </Target>
+  -->
+</Project>

+ 4 - 0
CSharp/Game/MongoDBTest/packages.config

@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<packages>
+  <package id="mongocsharpdriver" version="1.9.2" targetFramework="net45" />
+</packages>

+ 21 - 2
CSharp/Platform/Common/Base/Component.cs

@@ -1,7 +1,26 @@
-namespace Common.Base
+using MongoDB.Bson.Serialization.Attributes;
+
+namespace Common.Base
 {
     public class Component: Object
     {
-        public Entity Owner { get; set; }
+        private Entity owner;
+
+        [BsonIgnore]
+        public Entity Owner {
+            get
+            {
+                return owner;
+            }
+            set
+            {
+                this.owner = value;
+                this.Guid = this.owner.Guid;
+            }
+        }
+
+        protected Component()
+        {
+        }
     }
 }

+ 10 - 6
CSharp/Platform/Common/Base/Entity.cs

@@ -5,24 +5,28 @@ namespace Common.Base
 {
     public class Entity: Object
     {
-        private readonly Dictionary<string, Component> components =
-                new Dictionary<string, Component>();
+        public Dictionary<string, Component> Components { get; private set; }
+
+        protected Entity()
+        {
+            this.Components = new Dictionary<string, Component>();
+        }
 
         public void AddComponent<T>() where T : Component, new()
         {
             T t = new T { Owner = this };
-            this.components.Add(typeof (T).Name, t);
+            this.Components.Add(typeof(T).Name, t);
         }
 
         public void RemoveComponent<T>() where T : Component
         {
-            this.components.Remove(typeof (T).Name);
+            this.Components.Remove(typeof(T).Name);
         }
 
         public T GetComponent<T>() where T : Component
         {
             Component t;
-            if (!this.components.TryGetValue(typeof (T).Name, out t))
+            if (!this.Components.TryGetValue(typeof(T).Name, out t))
             {
                 return null;
             }
@@ -31,7 +35,7 @@ namespace Common.Base
 
         public Component[] GetComponents()
         {
-            return this.components.Values.ToArray();
+            return this.Components.Values.ToArray();
         }
     }
 }

+ 4 - 4
CSharp/Platform/Common/Base/MultiMap.cs

@@ -56,20 +56,20 @@ namespace Common.Base
         /// </summary>
         /// <param name="t"></param>
         /// <returns></returns>
-        public List<K> GetAll(T t)
+        public K[] GetByKey(T t)
         {
             List<K> list;
             this.dictionary.TryGetValue(t, out list);
             if (list == null)
             {
-                return new List<K>();
+                return new K[0];
             }
             var newList = new List<K>();
             foreach (K k in list)
             {
                 newList.Add(k);
             }
-            return newList;
+            return newList.ToArray();
         }
 
         /// <summary>
@@ -87,7 +87,7 @@ namespace Common.Base
             }
         }
 
-        public K Get(T t)
+        public K GetOne(T t)
         {
             List<K> list;
             this.dictionary.TryGetValue(t, out list);

+ 36 - 11
CSharp/Platform/Common/Base/Object.cs

@@ -1,39 +1,51 @@
 using System.Collections.Generic;
 using MongoDB.Bson;
+using MongoDB.Bson.Serialization.Attributes;
 
 namespace Common.Base
 {
     public class Object
     {
-        public ObjectId Guid { get; set; }
+        [BsonId]
+        public ObjectId Guid { get; protected set; }
 
-        public Dictionary<string, object> Dict { get; private set; }
+        [BsonElement]
+        [BsonIgnoreIfNull]
+        public Dictionary<string, object> Values;
 
         protected Object()
         {
             this.Guid = ObjectId.GenerateNewId();
-            this.Dict = new Dictionary<string, object>();
+        }
+
+        protected Object(ObjectId guid)
+        {
+            this.Guid = guid;
         }
 
         public object this[string key]
         {
             set
             {
-                this.Dict[key] = value;
+                if (this.Values == null)
+                {
+                    this.Values = new Dictionary<string, object>();
+                }
+                this.Values[key] = value;
             }
             get
             {
-                return this.Dict[key];
+                return this.Values[key];
             }
         }
 
         public T Get<T>(string key)
         {
-            if (!this.Dict.ContainsKey(key))
+            if (!this.Values.ContainsKey(key))
             {
                 return default(T);
             }
-            return (T) this.Dict[key];
+            return (T) this.Values[key];
         }
 
         public T Get<T>()
@@ -43,22 +55,35 @@ namespace Common.Base
 
         public void Set(string key, object obj)
         {
-            this.Dict[key] = obj;
+            if (this.Values == null)
+            {
+                this.Values = new Dictionary<string, object>();
+            }
+            this.Values[key] = obj;
         }
 
         public void Set<T>(T obj)
         {
-            this.Dict[typeof (T).Name] = obj;
+            if (this.Values == null)
+            {
+                this.Values = new Dictionary<string, object>();
+            }
+            this.Values[typeof (T).Name] = obj;
         }
 
         public bool Contain(string key)
         {
-            return this.Dict.ContainsKey(key);
+            return this.Values.ContainsKey(key);
         }
 
         public bool Remove(string key)
         {
-            return this.Dict.Remove(key);
+            bool ret = this.Values.Remove(key);
+            if (this.Values.Count == 0)
+            {
+                this.Values = null;
+            }
+            return ret;
         }
     }
 }

+ 3 - 2
CSharp/Platform/Common/Common.csproj

@@ -82,7 +82,6 @@
     <Compile Include="Logger\Log.cs" />
     <Compile Include="Logger\NLogAdapter.cs" />
     <Compile Include="Logger\StackInfoDecorater.cs" />
-    <Compile Include="Properties\AssemblyInfo.cs" />
     <Compile Include="Helper\ProtobufHelper.cs" />
     <Compile Include="Helper\RandomHelper.cs" />
     <Compile Include="Helper\StringHelper.cs" />
@@ -93,7 +92,9 @@
     <None Include="Helper\Packages.config" />
     <None Include="packages.config" />
   </ItemGroup>
-  <ItemGroup />
+  <ItemGroup>
+    <Folder Include="Properties\" />
+  </ItemGroup>
   <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
   <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
   <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">

+ 0 - 39
CSharp/Platform/Common/Properties/AssemblyInfo.cs

@@ -1,39 +0,0 @@
-using System.Reflection;
-using System.Runtime.InteropServices;
-
-// 有关程序集的常规信息通过以下
-// 特性集控制。更改这些特性值可修改
-// 与程序集关联的信息。
-
-[assembly: AssemblyTitle("Common")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("Microsoft")]
-[assembly: AssemblyProduct("Common")]
-[assembly: AssemblyCopyright("Copyright © Microsoft 2014")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// 将 ComVisible 设置为 false 使此程序集中的类型
-// 对 COM 组件不可见。  如果需要从 COM 访问此程序集中的类型,
-// 则将该类型上的 ComVisible 特性设置为 true。
-
-[assembly: ComVisible(false)]
-
-// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
-
-[assembly: Guid("95298b49-4d85-4c6c-91bd-e1cd12d74187")]
-
-// 程序集的版本信息由下面四个值组成: 
-//
-//      主版本
-//      次版本 
-//      生成号
-//      修订号
-//
-// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
-// 方法是按如下所示使用“*”: 
-// [assembly: AssemblyVersion("1.0.*")]
-
-[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]