Ejemplo n.º 1
0
            }     // end SetRoleCoinWithID

            /// <summary>
            /// 获取角色穿戴的装备数据
            /// </summary>
            /// <param name="username"> 用户名 </param>
            /// <param name="roleindex"> 角色索引 </param>
            /// <param name="dict"> 穿戴的装备数据 </param>
            public static void GetWearInfoWithID(string username, int roleindex, out Dictionary <string, string> dict)
            {
                dict = new Dictionary <string, string>();
                string           tableName = "role_equip_table_" + username;
                SqliteDatabase   sqliteDB  = new SqliteDatabase("slidergame.db");
                SqliteDataReader reader    = sqliteDB.SelectWhere(tableName, new string[] {
                    ConstConfig.WEAPON, ConstConfig.NECKLACE, ConstConfig.RING, ConstConfig.WING, ConstConfig.ARMOR, ConstConfig.PANTS, ConstConfig.SHOES
                },
                                                                  new string[] { "roleindex" }, new string[] { "=" }, new string[] { ToValue(roleindex) });

                if (null == reader)
                {
                    sqliteDB.Disconnect();
                    return;
                } // end if
                try {
                    while (reader.Read())
                    {
                        dict[ConstConfig.WEAPON]   = reader.GetString(reader.GetOrdinal(ConstConfig.WEAPON));
                        dict[ConstConfig.NECKLACE] = reader.GetString(reader.GetOrdinal(ConstConfig.NECKLACE));
                        dict[ConstConfig.RING]     = reader.GetString(reader.GetOrdinal(ConstConfig.RING));
                        dict[ConstConfig.WING]     = reader.GetString(reader.GetOrdinal(ConstConfig.WING));
                        dict[ConstConfig.ARMOR]    = reader.GetString(reader.GetOrdinal(ConstConfig.ARMOR));
                        dict[ConstConfig.PANTS]    = reader.GetString(reader.GetOrdinal(ConstConfig.PANTS));
                        dict[ConstConfig.SHOES]    = reader.GetString(reader.GetOrdinal(ConstConfig.SHOES));
                    } // end while
                } catch (Exception ex) {
                    ConsoleTool.SetConsole(ex.ToString());
                } // end try
                sqliteDB.Disconnect();
            }     // end GetWearInfoWithID
Ejemplo n.º 2
0
            }     // end SetWearInfoWithID

            /// <summary>
            /// 获取对应背包的数据
            /// </summary>
            /// <param name="username"> 用户名 </param>
            /// <param name="roleindex"> 角色索引 </param>
            /// <param name="packType"> 背包类型 </param>
            /// <param name="dict"> 背包数据, 索引0 是ID, 索引1 是数量 </param>
            public static void GetPackInfoWithID(string username, int roleindex, string packType, out Dictionary <int, string[]> dict)
            {
                dict = new Dictionary <int, string[]>();
                string           tableName = "pack_list_table_" + username;
                SqliteDatabase   sqliteDB  = new SqliteDatabase("slidergame.db");
                SqliteDataReader reader    = sqliteDB.SelectWhere(tableName, new string[] { "gid", "id", "count" },
                                                                  new string[] { "roleindex", "gid", "type" }, new string[] { "=", "<", "=" }, new string[] { ToValue(roleindex), ToValue("25"), ToValue(packType) });

                if (null == reader)
                {
                    sqliteDB.Disconnect();
                    return;
                } // end if
                try {
                    while (reader.Read())
                    {
                        int gid = reader.GetInt32(reader.GetOrdinal("gid"));
                        dict[gid]    = new string[2];
                        dict[gid][0] = reader.GetString(reader.GetOrdinal("id"));
                        dict[gid][1] = reader.GetInt32(reader.GetOrdinal("count")).ToString();
                    } // end while
                } catch (Exception ex) {
                    ConsoleTool.SetConsole(ex.ToString());
                } // end try
                sqliteDB.Disconnect();
            }     // end GetEquipmentPackInfoWithID
Ejemplo n.º 3
0
            }     // end GetRoleInfoWithID

            /// <summary>
            /// 获取角色金币数量
            /// </summary>
            /// <param name="username"> 用户名 </param>
            /// <param name="roleindex"> 角色索引 </param>
            /// <returns>金币数量</returns>
            public static int GetRoleCoinWithID(string username, int roleindex)
            {
                SqliteDatabase   sqliteDB = new SqliteDatabase("slidergame.db");
                SqliteDataReader reader   = sqliteDB.SelectWhere("role_list_table_" + username, new string[] { "coin" },
                                                                 new string[] { "roleindex" }, new string[] { "=" }, new string[] { ToValue(roleindex) });

                if (null == reader)
                {
                    sqliteDB.Disconnect();
                    return(0);
                } // end if
                try {
                    while (reader.Read())
                    {
                        int result;
                        result = reader.GetInt32(reader.GetOrdinal("coin"));
                        if (result < 0)
                        {
                            result = 0;
                        }
                        // end if
                        sqliteDB.Disconnect();
                        return(result);
                    } // end while
                } catch (Exception ex) {
                    sqliteDB.Disconnect();
                    ConsoleTool.SetConsole(ex.ToString());
                } // end try
                sqliteDB.Disconnect();
                return(0);
            } // end GetRoleCoinWithID
Ejemplo n.º 4
0
            } // end DeleteRole

            /// <summary>
            /// 获取角色基本信息
            /// </summary>
            /// <param name="roleindex"> 用户名 </param>
            /// <param name="roleindex"> 角色索引 </param>
            /// <returns> 角色基本信息 [0] 为姓名,[1] 角色类型。不存在返回null </returns>
            public static string[] GetRoleInfoWithID(string username, int roleindex)
            {
                SqliteDatabase   sqliteDB = new SqliteDatabase("slidergame.db");
                SqliteDataReader reader   = sqliteDB.SelectWhere("role_list_table_" + username, new string[] { "name", "roletype" },
                                                                 new string[] { "roleindex" }, new string[] { "=" }, new string[] { ToValue(roleindex) });

                if (null == reader)
                {
                    sqliteDB.Disconnect();
                    return(null);
                } // end if
                try {
                    while (reader.Read())
                    {
                        string[] result = new string[2];
                        result[0] = reader.GetString(reader.GetOrdinal("name"));
                        result[1] = reader.GetString(reader.GetOrdinal("roletype"));
                        sqliteDB.Disconnect();
                        return(result);
                    } // end while
                } catch (Exception ex) {
                    sqliteDB.Disconnect();
                    ConsoleTool.SetConsole(ex.ToString());
                } // end try
                return(null);
            }     // end GetRoleInfoWithID
Ejemplo n.º 5
0
            } // end GetGameObject

            public void Recycling(string name, GameObject Go) {
                if (null == Go) {
#if __MY_DEBUG__
                    ConsoleTool.SetError(GetType() + "Recycling GameObject is NULL! Name:" + name);
#endif
                    return;
                } // end if
                if (string.IsNullOrEmpty(name)) {
#if __MY_DEBUG__
                    ConsoleTool.SetError(GetType() + "Recycling GameObject Name:" + name + " is null or empty!");
#endif
                    Object.Destroy(Go);
                    return;
                } // end if
                Stack<GameObject> objects;
                if (false == objectsMap.TryGetValue(name, out objects)) {
#if __MY_DEBUG__
                    ConsoleTool.SetError(GetType() + "Recycling GameObject Name:" + name + " dosn't build!!");
#endif
                    Object.Destroy(Go);
                    return;
                } // end if
                if (objects.Contains(Go)) {
#if __MY_DEBUG__
                    ConsoleTool.SetError(GetType() + "Recycling GameObject Name:" + name + " replace recycling!!");
#endif
                    Object.Destroy(Go);
                    return;
                }  // end if
                Go.SetActive(false);
                Go.transform.SetParent(poolParent, false);
                objects.Push(Go);
            } // end Recycling
Ejemplo n.º 6
0
            } // end Update

            public GameObject GetGameObject(string name) {
                if (string.IsNullOrEmpty(name)) {
#if __MY_DEBUG__
                    ConsoleTool.SetError(GetType() + "GetGameObject name is null or empty! Name:" + name);
#endif
                    return null;
                } // end if
                Stack<GameObject> objects;
                if (false == objectsMap.TryGetValue(name, out objects)) {
#if __MY_DEBUG__
                    Debug.Log(GetType() + "GetGameObject Name:" + name + " build a pool!");
#endif
                    objects = new Stack<GameObject>();
                    objectsMap[name] = objects;
                } // end if
                GameObject Go = objects.Count > 0 ? objects.Pop() : null;
                if (Go != null) return Go;
                // end if
                GameObject prefab = ResourcesTool.LoadPrefabPool(name);
                if (null == prefab) {
#if __MY_DEBUG__
                    ConsoleTool.SetError(GetType() + "GetGameObject prefab is null! name:" + name);
#endif
                    return null;
                } // end if
                Go = Object.Instantiate(prefab, poolParent);
                Go.name = name;
                return Go;
            } // end GetGameObject
Ejemplo n.º 7
0
        public TaskPage7()
        {
            Car car = new Car("Обычный автомобиль", 120, 4, "Бензин", 90);
            CarWithElectronic carWithElectronic = new CarWithElectronic("Авто напичканное электроникой", 150, 2, "Дизель", 70);
            Bicycle           bicycle           = new Bicycle("Велосипед", 40, 2);

            ConsoleTool.WriteLineConsoleGreenMessage("Ниже представлены экземпляры объектов разных типов, но все они объединены одним базовым типом Transport через наследование.");
            ConsoleTool.WriteLineConsoleGreenMessage("Car и Bicycle унаследованы от Transport. CarWithElectronic унаследован от Car.");
            ConsoleTool.WriteLineConsoleGreenMessage("Вывожу о них данные я через foreach. И тут мне помогает полиморфизм, потому что я добавил все эти три экземпляра разных объектов в одну коллекцию под их общим типом.");

            transports = new List <Transport>()
            {
                car, carWithElectronic, bicycle
            };
            Console.WriteLine();
            foreach (Transport transport in transports)
            {
                Console.WriteLine(transport.ToString());
            }

            ConsoleTool.WriteLineConsoleGreenMessage("В качестве примера инкапсуляции можно рассмотреть метод StartEngine объекта CarWithElectronic, который сначало проверяет работают ли все системы должным образом, а только потом запускает базовый метод запуска мотора от класса Car.");
            ConsoleTool.WriteLineConsoleGreenMessage("Метод класса Car StartEngine сначало проверит, есть ли в баке авто топливо для запуска. Есть есть - мотор будет запущен. Если нет, выводится текст исключения. Это также пример инкапсуляции.");

            try
            {
                carWithElectronic.StartEngine();
            }
            catch (TransportException ex)
            {
                Console.WriteLine(ex.Message);
            }
            try
            {
                carWithElectronic.ForcedStartEngine();
            }
            catch (TransportException ex)
            {
                Console.WriteLine(ex.Message);
            }

            ConsoleTool.WriteLineConsoleGreenMessage("Давайте заправим этого зверя. Могли бы это сделать через метод. Но тут я хочу продемонстрировать инкапсуляцию на примере свойства. Перед присвоением здесь мы сначало сравним новое значение с максимальным, чтобы не переполнить топливный бак. И выставим то, что будет больше. Дальше попробуем снова запустить мотор.");

            try
            {
                carWithElectronic.AvailFuel = 100;
            }
            catch (TransportException ex)
            {
                Console.WriteLine(ex.Message);
            }
            try
            {
                carWithElectronic.ForcedStartEngine();
            }
            catch (TransportException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 8
0
        public void ConsoleFindPersonWorkPlaceByPersonData()
        {
            ConsoleTool.WriteLineConsoleGreenMessage("Пробуем найти объект, который точно есть в словаре: ");
            Console.WriteLine(FindPersonWorkPlaceByPersonData("Федоров", "Алексей", "Алексеевич", "11авы321dsdsad", "Москва"));

            ConsoleTool.WriteLineConsoleGreenMessage("Пробуем найти объект, которого нет в словаре: ");
            Console.WriteLine(FindPersonWorkPlaceByPersonData("Федоров1", "Алексей", "Алексеевич", "11авы321dsdsad", "Москва"));
        }
Ejemplo n.º 9
0
 public void ConsoleCarParkElementWithEnumerator()
 {
     ConsoleTool.WriteLineConsoleGreenMessage("Вывод авто из автопарка с использованием Enumerator: ");
     foreach (Car car in carPark)
     {
         Console.WriteLine(car.ToString());
     }
 }
Ejemplo n.º 10
0
 public void ConsoleFoodBasketItems()
 {
     ConsoleTool.WriteLineConsoleGreenMessage("Я сделал перечисления для каждого из классов на основе List. Собрал их всех в один список в классе FoodBasket. И через енумератор класса FoodBasket вывожу ниже: ");
     foreach (Food food in foodBasket)
     {
         Console.WriteLine(food.Name);
     }
 }
Ejemplo n.º 11
0
 public void ConsoleAllGeometricFiguresUsingForeach()
 {
     ConsoleTool.WriteLineConsoleGreenMessage("Выведем все фигуры с использованием foreach: ");
     foreach (var geometricFigure in geometricFigures)
     {
         Console.WriteLine(geometricFigure.Name);
     }
 }
Ejemplo n.º 12
0
        public static void Main()
        {
            List <int> sequence = new List <int>();

            ConsoleTool.LoadSequence(sequence);

            Console.WriteLine("Sum of sequence: " + CalculateSum(sequence));
            Console.WriteLine("Average of sequence: " + CalculateAverage(sequence));
        }
Ejemplo n.º 13
0
 private void GenerateRandomTables(int count)
 {
     ConsoleTool.WriteLineConsoleGreenMessage("Вывод сгенерированных случайным образом экземпляров объекта Table:");
     tables = new List <Table>();
     for (int i = 0; i < 100; i++)
     {
         tables.Add(new Table(GetRandomMaterial().ToString(), GetRandomNumberOfLegs(), GetRandomDate(), GetRandomSold()));
         Console.WriteLine(tables[i].ToString());
     }
 }
Ejemplo n.º 14
0
        public void ConsoleGroupedTablesByMaterial()
        {
            ConsoleTool.WriteLineConsoleGreenMessage("Группировка столов по использованному материалу:");
            var materials = GroupTablesByMaterial();

            foreach (var material in materials)
            {
                Console.WriteLine($"{material.Material} : {material.Count}");
            }
        }
Ejemplo n.º 15
0
        public void ConsoleTablesOrderByCreatedDateDesc()
        {
            ConsoleTool.WriteLineConsoleGreenMessage("Cтолы, отсортированные по дате создания, начиная с последнего:");
            var tables = GetTablesOrderByCreatedDateDesc();

            foreach (var table in tables)
            {
                Console.WriteLine(table.ToString());
            }
        }
Ejemplo n.º 16
0
        public void ConsoleSoldTables()
        {
            ConsoleTool.WriteLineConsoleGreenMessage("Проданные столы:");
            var soldTables = GetSoldTables();

            foreach (var table in soldTables)
            {
                Console.WriteLine(table.ToString());
            }
        }
Ejemplo n.º 17
0
            } // end SqliteDatabase

            /// <summary>
            /// 连接数据库
            /// </summary>
            /// <param name="connectionString"> 数据库名 </param>
            public void Connect(string connectionString)
            {
                string path = PlatformTool.GetSqliteDatabasePath(connectionString);

                try {
                    dbConnection = new SqliteConnection(path);
                    dbConnection.Open();
                } catch (Exception ex) {
                    ConsoleTool.SetConsole(ex.ToString());
                } // end try
            }     // end Open
Ejemplo n.º 18
0
        public TaskPage18()
        {
            ConsoleTool.WriteLineConsoleGreenMessage("Задача про явное/неявное преобразование. Собсвтенно реализация в классе Person. Демонстрация ниже. Создаем из строки класс - сделал в явном виде. Выводим в консоль через неявное преобразование. ");
            Person person = (Person)"Иванов Иван";

            Console.WriteLine(person);
            ConsoleTool.WriteLineConsoleGreenMessage("Делаем сравнение через оператор ==");
            Console.WriteLine((person == "Иванов Иван").ToString());
            ConsoleTool.WriteLineConsoleGreenMessage("Делаем сравнение через оператор Equals. По дефолту Equals при сравнении ссылочных типов (а строка это ссылочный тип) будет проверять именно ссылки. Т.к. в этом случаи ссылки ссылаются на разные области в куче, то ответ будет отрицательным.");
            Console.WriteLine((person.Equals("Иванов Иван")).ToString());
        }
Ejemplo n.º 19
0
        public void ConsoleTestStringComparer()
        {
            ConsoleTool.WriteLineConsoleGreenMessage("Тестируем работу оператора == для строки.");

            string a = "Строка 1";
            string b = "Строка 1";

            Console.WriteLine($"{a} == {b}");

            Console.WriteLine((a == b).ToString());
        }
Ejemplo n.º 20
0
            } // end 

            /// <summary>
            /// 授权回调
            /// </summary>
            /// <param name="reqID"></param>
            /// <param name="state"> 响应状态 </param>
            /// <param name="type"> 授权平台 </param>
            /// <param name="result"> 回调内容 </param>
            void AuthResultHandler(int reqID, ResponseState state, PlatformType type, Hashtable result) {

                if (state == ResponseState.Success) {
                    ConsoleTool.SetConsole("authorize success !");
                } else if (state == ResponseState.Fail) {
                    ConsoleTool.SetConsole("fail! throwable stack = " + result["stack"] + "; error msg = " + result["msg"]);
                }
                else if (state == ResponseState.Cancel) {
                    ConsoleTool.SetConsole("authorize cancel");
                } // end if
            } // end AuthResultHandler
Ejemplo n.º 21
0
        public void ConsoleAllEllipsesUsingWhile()
        {
            ConsoleTool.WriteLineConsoleGreenMessage("Выведем все элипсы с использованием While и реализованного IEnumerator: ");
            IEnumerator iEnumerator = elipses.GetEnumerator();

            while (iEnumerator.MoveNext())
            {
                Elipse elipseItem = iEnumerator.Current as Elipse;
                Console.WriteLine(elipseItem.Name);
            }
        }
Ejemplo n.º 22
0
        public void RunDir()
        {
            var cmd = new ConsoleTool("cmd.exe")
            {
                AssertSuccess = true
            };

            Task.WhenAll(
                cmd.Run("/c", "echo", "hello"),
                cmd.Run("/c", "dir")
                ).Wait();
        }
Ejemplo n.º 23
0
        public void ConsoleTestINotifyPropertyChanged()
        {
            ConsoleTool.WriteLineConsoleGreenMessage("Демонстрация работы INotifyPropertyChanged. Создаем объект, реализующий этот интерфейс. Подписываемся на событие PropertyChanged. При изменении property выводим его название.");
            Person p = new Person()
            {
                FirstName = "Иван", LastName = "Иванов", PaterName = "Иванович", BirthPlace = "Москва", Passport = "44534233423dsd3"
            };

            p.PropertyChanged += OnModelPropertyChanged;
            p.FirstName        = "Дмитрий";
            p.BirthPlace       = "Вашингтон";
        }
Ejemplo n.º 24
0
            } // end Disconnect

            /// <summary>
            /// 执行命令
            /// </summary>
            /// <param name="sqlQuery"> sql语句 </param>
            /// <returns> 结果读取器 </returns>
            public SqliteDataReader ExecuteQuery(string sqlQuery)
            {
                try {
                    dbCommand             = dbConnection.CreateCommand();
                    dbCommand.CommandText = sqlQuery;
                    reader = dbCommand.ExecuteReader();
                } catch (Exception ex) {
                    reader = null;
                    ConsoleTool.SetConsole(ex.ToString());
                } // end try
                return(reader);
            }     // end SqliteDataReader
Ejemplo n.º 25
0
 public static void SetScene(IScene scene) {
     GameManager.SetGameState(GameState.SWITCH);
     if (null != m_scene) { // 清理当前场景
         m_scene.Dispose();
     } // end if
     if (null == scene) {
         ConsoleTool.SetError("SceneManager SetScene scene is null!");
         DebugTool.LogError("don't have scene can play!");
         return;
     } // end if
     m_scene = scene;
 } // end SetSceneName
Ejemplo n.º 26
0
        public void ConsoleRemoveRepeatableSpaces()
        {
            ConsoleTool.WriteLineConsoleGreenMessage("Удалим лишние пробелы из строки: ");

            string someText = "  ea1359 29105    c4f29   a0f51           17d2  960 926f";

            ConsoleTool.WriteLineConsoleGreenMessage(someText);

            Regex regex  = new Regex(@"\s{1,}");
            var   result = regex.Replace(someText, " ");

            Console.WriteLine(result);
        }
Ejemplo n.º 27
0
            }     // end GetWearInfoWithID

            /// <summary>
            /// 修改角色穿戴的装备数据
            /// </summary>
            /// <param name="username"> 用户名 </param>
            /// <param name="roleindex"> 角色索引 </param>
            /// <param name="type"> 装备类型 </param>
            /// <param name="id"> 装备id </param>
            public static void SetWearInfoWithID(string username, int roleindex, string type, string id)
            {
                string         tableName = "role_equip_table_" + username;
                SqliteDatabase sqliteDB  = new SqliteDatabase("slidergame.db");

                try {
                    sqliteDB.Update(tableName, new string[] { type }, new string[] { ToValue(id) },
                                    new string[] { "roleindex" }, new string[] { "=" }, new string[] { ToValue(roleindex) });
                } catch (Exception ex) {
                    ConsoleTool.SetConsole(ex.ToString());
                } // end try
                sqliteDB.Disconnect();
            }     // end SetWearInfoWithID
Ejemplo n.º 28
0
            }     // end GetArrangePackInfoWithID

            /// <summary>
            /// 修改对应背包和对应格子的数据
            /// </summary>
            /// <param name="username"> 用户名 </param>
            /// <param name="roleindex"> 角色索引 </param>
            /// <param name="type"> 背包类型 </param>
            /// <param name="gid"> 格子id </param>
            /// <param name="id"> 物品id </param>
            /// <param name="grade"> 物品品级 </param>
            /// <param name="count"> 物品数量 </param>
            public static void SetPackInfoWithID(string username, int roleindex, string type, int gid, string id, string grade, int count)
            {
                string         tableName = "pack_list_table_" + username;
                SqliteDatabase sqliteDB  = new SqliteDatabase("slidergame.db");

                try {
                    sqliteDB.Update(tableName, new string[] { "id", "grade", "count" }, new string[] { ToValue(id), ToValue(grade), ToValue(count) },
                                    new string[] { "roleindex", "gid", "type" }, new string[] { "=", "=", "=" }, new string[] { ToValue(roleindex), ToValue(gid), ToValue(type) });
                } catch (Exception ex) {
                    ConsoleTool.SetConsole(ex.ToString());
                } // end try
                sqliteDB.Disconnect();
            }     // end SetPackInfoWithID
Ejemplo n.º 29
0
        public void ConsoleAnalyzingLegsCount()
        {
            ConsoleTool.WriteLineConsoleGreenMessage("Анализ количества ножек у столов:");

            int minLegsCount = GetMinLegsCount();
            int maxLegsCount = GetMaxLegsCount();
            int sumLegsCount = GetSumLegsCount();


            Console.WriteLine($"Минимальное количество ножек у стола: {minLegsCount}");
            Console.WriteLine($"Максимальное количество ножек у стола: {maxLegsCount}");
            Console.WriteLine($"Общее количество ножек у всех столов вместе: {sumLegsCount}");
        }
Ejemplo n.º 30
0
        public static void Main(string[] args)
        {
            Stack <int> stack = new Stack <int>();

            ConsoleTool.LoadStack(stack);

            while (stack.Count != 0)
            {
                System.Console.WriteLine(stack.Pop() + " ");
            }

            System.Console.WriteLine();
        }