Esempio n. 1
0
        protected override void OnStartAffer()
        {
            try
            {
                var setting = new EnvironmentSetting();
                setting.ClientDesDeKey = "j6=9=1ac";
                setting.EntityAssembly = Assembly.Load("ZyGames.Doudizhu.Model");
                GameEnvironment.Start(setting);

                ScriptEngines.AddReferencedAssembly(new string[] {
                    "ZyGames.Doudizhu.Lang.dll",
                    "ZyGames.Doudizhu.Model.dll",
                    "ZyGames.Doudizhu.Bll.dll"
                });
                ActionFactory.SetActionIgnoreAuthorize(1012, 9001, 9203);

                AppstoreClientManager.Current.InitConfig();
                LoadUnlineUser();
                InitRanking();
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("OnStartAffer error:{0}", ex);
            }
        }
Esempio n. 2
0
        static void Main(string[] args)
        {
            string resultsFilePath = "results.txt";
            string command         = "all";

            args = new string[] { @"D:\C#" };
            if (args.Length == 3)
            {
                resultsFilePath = args[2];
            }
            if (args.Length == 2)
            {
                command = args[1];
            }
            if (args.Length == 0)
            {
                Console.WriteLine("Invalid folder path");
            }
            else
            {
                string folderPath = args[0];
                if (Directory.Exists(Path.GetDirectoryName(folderPath)))
                {
                    var list = new ActionFactory(new Helper()).DoAction(command, folderPath);
                    File.WriteAllLines(resultsFilePath, list);
                }
                else
                {
                    System.Console.WriteLine("Folder not found");
                }
            }
            Console.ReadKey();
        }
        public static void ConfigureActions(this ActionFactory f, JToken details, ActionType actionType)
        {
            // ReSharper disable once SwitchStatementHandlesSomeKnownEnumValuesWithDefault
            switch (actionType)
            {
            case ActionType.Publish:
                f.PublishOptions = new PublishOptions
                {
                    Loop              = details.Value <bool>("isLoop"),
                    Playback          = details.Value <bool>("playback"),
                    Shuffle           = details.Value <bool>("isShuffle"),
                    RateDetails       = ToRateDetails(details["rateDetails"] !),
                    RoutingKeyDetails = ToRoutingKeyDetails(details["routingKeyDetails"] !),
                    Plugin            = ToPlugin(details["plugin"])
                };
                if (f.Exchange == "")     //Default AMQP exchange
                {
                    f.PublishOptions.RoutingKeyDetails.RoutingKeyType = PublishRoutingKeyType.Custom;
                    f.PublishOptions.RoutingKeyDetails.CustomValue    = f.Queue;
                }

                break;

            case ActionType.Record:
                f.RecordOptions = new RecordOptions
                {
                    BindingRoutingKey = details.Value <string>("bindingRoutingKey")
                };
                break;
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Builder
        /// </summary>
        public ToolBox()
            : base()
        {
            InitializeComponent();
            this.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom;

            //Panels are created based on the categories defined
            List <Category> categories = Category.GetCategories();

            for (int i = 0; i < categories.Count; i++)
            {
                ToolPanel toolPanel = new ToolPanel(categories[i], ActionFactory.GetToolsAction(categories[i].Name), this.Location);
                //The panel is placed based on the previous
                try
                {
                    toolPanel.Location = new Point(0, this.toolPanels[i - 1].Bottom + PANEL_MARGIN);
                }
                catch
                {
                    //If it is the first one skips the exception and it is placed in the initial position
                    toolPanel.Location = new Point(0, 0);
                }
                toolPanel.InitInsert   += new ToolEventHandler(toolsPanel_InitInsert);
                toolPanel.DoInsert     += new PointEventHandler(toolsPanel_DoInsert);
                toolPanel.CancelInsert += new EventHandler(toolPanel_CancelInsert);
                toolPanel.ShowPanel    += new GroupPanelEventHandler(toolPanel_ShowPanel);
                toolPanel.ClosePanel   += new EventHandler(toolPanel_ClosePanel);
                this.pContainer.Controls.Add(toolPanel);
                this.toolPanels.Add(toolPanel);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Loads code from a file, must be in native format
        /// </summary>
        /// <param name="parentNode">node to load from</param>
        public void LoadScript(IAppContext context, XmlNode parentNode)
        {
            XmlNodeList nodeList = parentNode.SelectNodes("Action");

            if (nodeList == null)
            {
                return;
            }
            foreach (XmlNode node in nodeList)
            {
                string     actionType = node.Attributes["ActionType"].Value;
                ActionBase action     = ActionFactory.Create(actionType);
                if (action == null)
                {
                    continue;
                }
                action.AppContext = context;
                if (action == null)
                {
                    MessageBox.Show("Action " + node.Name + " could not be mapped-- application needs updating.",
                                    "Load Map Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    continue;
                }
                action.ParentTest = this;
                action.LoadFromXml(node);
                Add(action);
            }
        }
Esempio n. 6
0
        private void When_constructing_file_info_for_missing_file_it_must_succeed()
        {
            // Arrange
            const string path = @"c:\some\file.txt";

            IFileSystem fileSystem = new FakeFileSystemBuilder()
                                     .IncludingDirectory(@"c:\some")
                                     .Build();

            // Act
            IFileInfo fileInfo = fileSystem.ConstructFileInfo(path);

            // Assert
            fileInfo.Name.Should().Be("file.txt");
            fileInfo.Extension.Should().Be(".txt");
            fileInfo.FullName.Should().Be(path);
            fileInfo.DirectoryName.Should().Be(@"c:\some");
            fileInfo.Exists.Should().BeFalse();
            ActionFactory.IgnoreReturnValue(() => fileInfo.Length)
            .ShouldThrow <FileNotFoundException>().WithMessage(@"Could not find file 'c:\some\file.txt'.");
            fileInfo.IsReadOnly.Should().BeTrue();
            fileInfo.Attributes.Should().Be(MissingFileAttributes);

            fileInfo.CreationTime.Should().Be(ZeroFileTimeUtc.ToLocalTime());
            fileInfo.CreationTimeUtc.Should().Be(ZeroFileTimeUtc);
            fileInfo.LastAccessTime.Should().Be(ZeroFileTimeUtc.ToLocalTime());
            fileInfo.LastAccessTimeUtc.Should().Be(ZeroFileTimeUtc);
            fileInfo.LastWriteTime.Should().Be(ZeroFileTimeUtc.ToLocalTime());
            fileInfo.LastWriteTimeUtc.Should().Be(ZeroFileTimeUtc);

            IDirectoryInfo directoryInfo = fileInfo.Directory.ShouldNotBeNull();

            directoryInfo.FullName.Should().Be(@"c:\some");
        }
Esempio n. 7
0
 protected override void OnStartAffer()
 {
     try
     {
         var setting = new EnvironmentSetting();
         setting.EntityAssembly = Assembly.Load("GameRanking.Model");
         ScriptEngines.AddReferencedAssembly("GameRanking.Model.dll");
         ActionFactory.SetActionIgnoreAuthorize(1000, 1001);
         var cacheSetting = new CacheSetting();
         cacheSetting.ChangedHandle += OnChangedNotify;
         GameEnvironment.Start(setting, cacheSetting);
         var       cache = new ShareCacheStruct <UserRanking>();
         Stopwatch t     = new Stopwatch();
         t.Start();
         var list = cache.FindAll(false);
         t.Stop();
         if (list.Count > 0)
         {
         }
         Console.WriteLine("The server is staring...");
     }
     catch (Exception ex)
     {
         TraceLog.WriteError("App star error:{0}", ex);
     }
 }
Esempio n. 8
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSwaggerGen(c =>
            {
                var basePath = AppContext.BaseDirectory;

                c.SwaggerDoc("v1",
                             new OpenApiInfo
                {
                    Title       = "Slack integration",
                    Version     = "v1",
                    Description = File.ReadAllText(Path.Combine(basePath, "README.md"))
                });
            });

            services.Configure <AppOptions>(Configuration);
            services.AddMvc();

            services.AddSingleton(_ => new MessageThrottler(Scheduler.Default));
            services.AddSingleton <ISlackMessaging, SlackMessaging>();
            services.AddTransient <ISlackActionFetcher, SlackActionFetcher>();

            ActionFactory.AddActionFactoryServicesToDi(serviceCollection: services);

            services.AddTransient <ActionFactory>();
        }
Esempio n. 9
0
        /// <summary>
        /// 获取Action处理的输出字节流
        /// </summary>
        /// <returns></returns>
        private static byte[] ProcessActionResponse(IActionDispatcher actionDispatcher, int actionId, ActionGetter actionGetter)
        {
            BaseStruct         baseStruct = ActionFactory.FindRoute(GameEnvironment.Setting.ActionTypeName, actionGetter, actionId);
            SocketGameResponse response   = new SocketGameResponse();

            response.WriteErrorCallback += actionDispatcher.ResponseError;
            baseStruct.SetPush();
            baseStruct.DoInit();
            if (actionGetter.Session.EnterLock(actionId))
            {
                try
                {
                    if (!baseStruct.GetError() &&
                        baseStruct.ReadUrlElement() &&
                        baseStruct.DoAction() &&
                        !baseStruct.GetError())
                    {
                        baseStruct.WriteResponse(response);
                    }
                    else
                    {
                        baseStruct.WriteErrorAction(response);
                    }
                }
                finally
                {
                    actionGetter.Session.ExitLock(actionId);
                }
            }
            else
            {
                baseStruct.WriteLockTimeoutAction(response, false);
            }
            return(response.ReadByte());
        }
        public void ActionsForBook_Test()
        {
            PaymentDetailsDto paymentDetailsDto = new PaymentDetailsDto();

            paymentDetailsDto.ProductType = ProductEnum.Book;
            paymentDetailsDto.ProductDto  = new ProductDto
            {
                Price     = 1000,
                ProductId = 1
            };

            var actions = ActionFactory.CreateActions(paymentDetailsDto);

            Assert.IsTrue(actions.Count == 2); // one of packing slip for shipping and agent payment generation

            paymentDetailsDto.AgentDto = new AgentDto
            {
                AgentId   = 200,
                AgentName = "John Miller"
            };
            foreach (var action in actions)
            {
                Assert.IsNotNull(action.DoProcess());
            }
        }
        public void ActionsForMembershipUpgrade_Test()
        {
            PaymentDetailsDto paymentDetailsDto = new PaymentDetailsDto();

            paymentDetailsDto.ProductType   = ProductEnum.UpgradeMembership;
            paymentDetailsDto.MembershipDto = new MembershipDto
            {
                MembershipId   = 10001,
                MembershipName = "Prime Membership"
            };
            paymentDetailsDto.CustomerDto = new CustomerDto
            {
                CustomerEmail = "*****@*****.**",
                CustomerId    = 120,
                CustomerName  = "Vithal Deshpande"
            };

            var actions = ActionFactory.CreateActions(paymentDetailsDto);

            Assert.IsTrue(actions.Count == 2); // membership upgrade and sending email

            foreach (var action in actions)
            {
                Assert.IsNotNull(action.DoProcess());
            }
        }
        /// <summary>
        /// 添加活动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void view_AddAction(object sender, EventArgs arg)
        {
            //确保在录制状态下
            Context.State.IsRecord = true;
            var    item       = sender as ToolStripItem;
            string actionName = item.Tag as string;

            if (string.IsNullOrEmpty(actionName))
            {
                throw new ApplicationException("活动没有定义名称");
            }
            ICoreBrowser browser       = Context.Browser;
            IHTMLElement activeElement = null;

            if (browser.Selector.SelectorElement != null)
            {
                activeElement = browser.Selector.SelectorElement;
            }

            var parameter = ActionFactory.CreateParameter(actionName);

            parameter.Element = activeElement;
            if (parameter is MultiStepActionParameter)
            {
                //用户选择同类元素处理逻辑在browserPresenter.editBrowser_WBLButtonDown处理
                var mp = parameter as MultiStepActionParameter;
                mp.AddActionFun = new Action <string, ActionParameter>(AddAction);
                Context.MultiStepActionParameter = mp;
                return;
            }
            AddAction(actionName, parameter);
        }
Esempio n. 13
0
 private RandomizedTester(TargetFactory <T> targetFactory, ActionFactory <T, F> actionFactory, Action <T, F> failingAction, F failure)
 {
     this._targetFactory = targetFactory;
     this._actionFactory = actionFactory;
     this._failingAction = failingAction;
     this._failure       = failure;
 }
Esempio n. 14
0
 public void SetActions(Piece piece, List <SkillStats> skills, Game game)
 {
     if (skills.Count > 0)
     {
         this.action_A = ActionFactory.MakeAction
                         (
             skills [0].name,
             game.GetBoard().GetCell(piece)
                         );
     }
     if (skills.Count > 1)
     {
         this.action_B = ActionFactory.MakeAction
                         (
             skills [1].name,
             game.GetBoard().GetCell(piece)
                         );
     }
     if (skills.Count > 2)
     {
         this.action_C = ActionFactory.MakeAction
                         (
             skills [2].name,
             game.GetBoard().GetCell(piece)
                         );
     }
 }
Esempio n. 15
0
        private void When_constructing_drive_info_for_missing_drive_it_must_succeed([NotNull] string driveName)
        {
            // Arrange
            IFileSystem fileSystem = new FakeFileSystemBuilder()
                                     .Build();

            // Act
            IDriveInfo driveInfo = fileSystem.ConstructDriveInfo(driveName);

            // Assert
            driveInfo.Name.Should().Be(@"X:\");
            driveInfo.IsReady.Should().BeFalse();
            ActionFactory.IgnoreReturnValue(() => driveInfo.AvailableFreeSpace).Should().ThrowExactly <DriveNotFoundException>()
            .WithMessage(@"Could not find the drive 'X:\'. The drive might not be ready or might not be mapped.");
            ActionFactory.IgnoreReturnValue(() => driveInfo.TotalFreeSpace).Should().ThrowExactly <DriveNotFoundException>()
            .WithMessage(@"Could not find the drive 'X:\'. The drive might not be ready or might not be mapped.");
            ActionFactory.IgnoreReturnValue(() => driveInfo.TotalSize).Should().ThrowExactly <DriveNotFoundException>()
            .WithMessage(@"Could not find the drive 'X:\'. The drive might not be ready or might not be mapped.");
            driveInfo.DriveType.Should().Be(DriveType.NoRootDirectory);
            ActionFactory.IgnoreReturnValue(() => driveInfo.DriveFormat).Should().ThrowExactly <DriveNotFoundException>()
            .WithMessage(@"Could not find the drive 'X:\'. The drive might not be ready or might not be mapped.");
            ActionFactory.IgnoreReturnValue(() => driveInfo.VolumeLabel).Should().ThrowExactly <DriveNotFoundException>()
            .WithMessage(@"Could not find the drive 'X:\'. The drive might not be ready or might not be mapped.");
            driveInfo.ToString().Should().Be(@"X:\");

            IDirectoryInfo directoryInfo = driveInfo.RootDirectory.ShouldNotBeNull();

            directoryInfo.FullName.Should().Be(@"X:\");
            directoryInfo.Exists.Should().BeFalse();
        }
Esempio n. 16
0
 public MapState()
 {
     actions = new List <IAction> {
         ActionFactory.GetAction <OpenCloseMapAction>(),
         ActionFactory.GetAction <UserInputAction>()
     };
 }
        /// <summary>
        ///    Gets the actions for the given <paramref name = "eventType" /> for the given <paramref name = "profileNode" />.
        /// </summary>
        /// <param name = "profileNode">The profile node.</param>
        /// <param name = "eventType">Type of the event.</param>
        /// <returns>A list of <see cref = "IAction" />s for the given <paramref name = "eventType" />, or an empty list.</returns>
        private static IEnumerable <IAction> GetProfileActions(XmlNode profileNode, EventType eventType)
        {
            string eventTypeString = eventType.ToString();

            eventTypeString = eventTypeString[0].ToString().ToLower() + eventTypeString.Substring(1);

            var             nodeList   = profileNode.SelectNodes(string.Format(XPATH_EVENTHANDLER_ACTION, eventTypeString));
            IList <IAction> actionList = new List <IAction>();

            if (nodeList != null)
            {
                foreach (XmlNode node in nodeList)
                {
                    IDictionary <string, string> parameters = (from XmlAttribute xmlAttribute
                                                               in node.Attributes
                                                               where xmlAttribute.Name != "type"
                                                               select new { key = xmlAttribute.Name, value = xmlAttribute.InnerText }
                                                               ).ToDictionary(item => item.key, item => item.value);

                    // Create and add the action
                    if (node.Name == "action")
                    {
                        // Generic action, use the "type" attribute to figure out the type
                        actionList.Add(ActionFactory.Create(node.Attributes["type"].InnerText, parameters));
                    }
                    else
                    {
                        // Specific action; the node is the name of the action
                        actionList.Add(ActionFactory.Create(node.Name, parameters));
                    }
                }
            }
            return(actionList);
        }
 public UsedActionsController(UsedActionFactory factory, UserFactory userFactory, ActionFactory actionFactory, PartnerFactory partnerFactory)
 {
     _factory        = factory;
     _partnerFactory = partnerFactory;
     _actionFactory  = actionFactory;
     _userFactory    = userFactory;
 }
Esempio n. 19
0
 public BattleState()
 {
     actions = new List <IAction> {
         ActionFactory.GetAction <MovePirateDuringEventAction>(),
         ActionFactory.GetAction <UserInputAction>()
     };
 }
Esempio n. 20
0
        private static Transformation ReadTransform(XmlNode transformNode)
        {
            string morpheme = transformNode.Attributes["morpheme"].InnerText;

            string actionName = transformNode.Attributes["action"].InnerText;

            string operandOne = transformNode.Attributes["operandOne"] != null
                ? transformNode.Attributes["operandOne"].InnerText
                : "";

            string operandTwo = transformNode.Attributes["operandTwo"] != null
                ? transformNode.Attributes["operandTwo"].InnerText
                : "";

            string flag = transformNode.Attributes["flag"] != null
                ? transformNode.Attributes["flag"].InnerText
                : "";

            BaseAction action = ActionFactory.Create(actionName, _alphabet, operandOne, operandTwo, flag);

            ConditionContainer conditions = ConditionContainer.EmptyContainer();

            if (transformNode.HasChildNodes)
            {
                conditions = ReadConditionContainer(transformNode.FirstChild);
            }

            return(new Transformation(action, morpheme, conditions));
        }
Esempio n. 21
0
        private static ToolStripMenuItem Parse(XmlNode node)
        {
            ToolStripMenuItem item = ActionFactory.GetAction(node).ToMenuItem();

            if (item == null)
            {
                return(null);
            }

            // Add folder items.
            if (node.Name.ToLowerInvariant() == "root")
            {
                foreach (XmlNode subNode in node.ChildNodes)
                {
                    var subMenuItem = Parse(subNode);

                    if (subMenuItem != null)
                    {
                        item.DropDown.Items.Add(subMenuItem);
                    }
                }

                return(item);
            }

            return(item);
        }
Esempio n. 22
0
 public void ReadJson(Dictionary <string, object> _jsonObj)
 {
     if (_jsonObj.ContainsKey("mTotalTime"))
     {
         mTotalTime = int.Parse(_jsonObj["mTotalTime"].ToString());
     }
     mEvents.Clear();
     if (_jsonObj.ContainsKey("mEvents"))
     {
         List <object> lst = _jsonObj["mEvents"] as List <object>;
         if (lst != null)
         {
             for (int i = 0; i < lst.Count; i++)
             {
                 Dictionary <string, object> action_json = lst[i] as Dictionary <string, object>;
                 ActionObject.ActionType     actioinType = ActionObject.ActionType.DoNothing;
                 if (action_json.ContainsKey("mActionType"))
                 {
                     actioinType = (ActionObject.ActionType) int.Parse(action_json["mActionType"].ToString());
                 }
                 ActionEvent ev = ActionFactory.CreateActionEvent(actioinType);
                 if (ev != null)
                 {
                     ev.ReadJson(action_json);
                 }
                 mEvents.Add(ev);
             }
         }
     }
 }
Esempio n. 23
0
        private StateCollection CreateParserStates(CGTContent content)
        {
            rules = CreateRules(content);

            StateCollection states = new StateCollection();
            foreach (LALRStateRecord record in content.LALRStateTable)
            {
                State state = new State(record.Index);
                states.Add(state);
            }

            foreach (LALRStateRecord record in content.LALRStateTable)
            {
                State state = states[record.Index];
                foreach (ActionSubRecord subRecord in record.ActionSubRecords)
                {
                    Action action =
                        ActionFactory.CreateAction(subRecord,
                                                   states,
                                                   symbols,
                                                   rules);
                    state.Actions.Add(action);
                }

            }
            return states;
        }
Esempio n. 24
0
        /// <summary>
        /// PROBLEMA:
        ///
        /// Implementar um algoritmo para o controle de posição de um drone em um plano cartesiano (X, Y).
        ///
        /// O ponto inicial do drone é "(0, 0)" para cada execução do método Evaluate ao ser executado cada teste unitário.
        ///
        /// A string de entrada pode conter os seguintes caracteres N, S, L, e O representando Norte, Sul, Leste e Oeste respectivamente.
        /// Estes catacteres podem estar presentes aleatóriamente na string de entrada.
        /// Uma string de entrada "NNNLLL" irá resultar em uma posição final "(3, 3)", assim como uma string "NLNLNL" irá resultar em "(3, 3)".
        ///
        /// Caso o caracter X esteja presente, o mesmo irá cancelar a operação anterior.
        /// Caso houver mais de um caracter X consecutivo, o mesmo cancelará mais de uma ação na quantidade em que o X estiver presente.
        /// Uma string de entrada "NNNXLLLXX" irá resultar em uma posição final "(1, 2)" pois a string poderia ser simplificada para "NNL".
        ///
        /// Além disso, um número pode estar presente após o caracter da operação, representando o "passo" que a operação deve acumular.
        /// Este número deve estar compreendido entre 1 e 2147483647.
        /// Deve-se observar que a operação 'X' não suporta opção de "passo" e deve ser considerado inválido. Uma string de entrada "NNX2" deve ser considerada inválida.
        /// Uma string de entrada "N123LSX" irá resultar em uma posição final "(1, 123)" pois a string pode ser simplificada para "N123L"
        /// Uma string de entrada "NLS3X" irá resultar em uma posição final "(1, 1)" pois a string pode ser siplificada para "NL".
        ///
        /// Caso a string de entrada seja inválida ou tenha algum outro problema, o resultado deve ser "(999, 999)".
        ///
        /// OBSERVAÇÕES:
        /// Realizar uma implementação com padrões de código para ambiente de "produção".
        /// Comentar o código explicando o que for relevânte para a solução do problema.
        /// Adicionar testes unitários para alcançar uma cobertura de testes relevânte.
        /// </summary>
        /// <param name="input">String no padrão "N1N2S3S4L5L6O7O8X"</param>
        /// <returns>String representando o ponto cartesiano após a execução dos comandos (X, Y)</returns>
        public static string Evaluate(string input)
        {
            var stringInput = new Input(input);

            try
            {
                // TODO: Este método é o ponto de entrada para a lógica.

                if (stringInput.IsValid())
                {
                    var actions        = new ActionFactory(stringInput);
                    var actionsInOrder = actions.GetActionsInOrder();

                    var drone = new Drone();

                    foreach (var action in actionsInOrder)
                    {
                        drone.Move(action);
                    }

                    return(drone.ToString());
                }
                else
                {
                    return(stringInput.GetCoordinateError());
                }
            }
            catch (ArgumentException)
            {
                return(stringInput.GetCoordinateError());
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Runs an action referenced by ActionName property in its own thread.
        /// </summary>
        /// <param name="deviceListString"></param>
        /// <param name="actionName"></param>
        public void RunAction(string deviceListString, string actionName)
        {
            var actiontype = _loadedActions[actionName].GetType();
            var action     = ActionFactory.InstantiateAction(actiontype);

            RunAction(deviceListString, action);
        }
Esempio n. 26
0
        public void TestCustomCSharpAction_InSeperateAssembly()
        {
            var old = Compiler.Instance.TypeFactory;

            try
            {
                // Setup the TypeFactory to use both the main Wanderer assembly and our assembly
                Compiler.Instance.TypeFactory = new TypeCollectionFactory(typeof(Compiler).Assembly, typeof(TestAction).Assembly);

                var blue = Compiler.Instance.Deserializer.Deserialize <ActionBlueprint>(yaml);

                var dir = Path.Combine(TestContext.CurrentContext.TestDirectory, "EmptyFolder");
                Directory.CreateDirectory(dir);

                var wf = new WorldFactory()
                {
                    ResourcesDirectory = dir
                };
                var world = wf.Create();

                var f      = new ActionFactory();
                var action = f.Create(world, world.Player, blue);

                Assert.IsInstanceOf(typeof(TestAction), action);
            }
            finally
            {
                Compiler.Instance.TypeFactory = old;
            }
        }
Esempio n. 27
0
        protected override bool DoSuccess(int userId, out IUser user)
        {
            user = null;
            var      cacheSet  = new PersonalCacheStruct <GameUser>();
            var      roleCache = new PersonalCacheStruct <UserRole>();
            var      roleList  = roleCache.FindAll(Uid);
            GameUser gameUser  = cacheSet.FindKey(Uid);

            if (gameUser == null || roleList.Count == 0)
            {
                //通知客户跳转到创建角色接口
                GuideId = 1005;
                return(true);
            }
            user = gameUser;
            if (gameUser.CurrRoleId == 0)
            {
                gameUser.CurrRoleId = roleList[0].RoleId;
            }

            var notifyUsers = new List <GameUser>();

            notifyUsers.Add(gameUser);
            ActionFactory.SendAsyncAction(notifyUsers, (int)ActionType.World, null, null);
            return(true);
        }
Esempio n. 28
0
        private void Update()
        {
            if (EnabledTileMap)
            {
                //This is being called too many times.
                //Need a fix for this, I need to not draw a tile if the mouse is over the position AND be allowed to highlight the tile to show the action.
                Vector3Int locationAtMouse = LocationAtMouse(this.GrassMap);
                //if(this.GrassMap.HasTile(locationAtMouse))
                // todo only have this occur in situations where the farming is enabled.
                // It is called every frame and is useless to call when not needed.
                this.HighlightTileAtPosition(locationAtMouse);

                if (Input.GetMouseButtonDown(0) &&
                    this.Tilemaps[0].HasTile(locationAtMouse))
                {
                    Debug.Log($"Tile clicked. Selected tile {FarmerPlayer.instance.GetSelectedSeed()}");

                    IEnumerable <KeyValuePair <ActionBase, FarmingActionUI> > ActionsAtGridLocation = FarmingActionManager.instance.ActionsAtLocation(locationAtMouse);

                    if (ActionsAtGridLocation.Count() > 0)
                    {
                        foreach (KeyValuePair <ActionBase, FarmingActionUI> baseA in ActionsAtGridLocation)
                        {
                            Debug.Log(baseA.Key.GetName());
                        }
                    }

                    TillSoilAction action = ActionFactory.Create <TillSoilAction>(locationAtMouse);
                    FarmingActionManager.instance.EnqueueNewAction(action);
                }
            }
        }
Esempio n. 29
0
    private void ActionDone(ActionBase action)
    {
        if (action.IsSuccess())
        {
            if (action is ActionGoTo && (action as ActionGoTo).FinalPosition == DesiredPosition)
            {
                Debug.Log(action.ToString() + "is done, setting E_AT_TARGET_POS to true");
                Owner.WorldState.SetWSProperty(E_PropKey.E_AT_TARGET_POS, true);
            }
            else if (action is ActionWeaponShow)
            {
                Debug.Log(action.ToString() + "is done, setting E_WEAPON_IN_HANDS to " + (action as ActionWeaponShow).Show.ToString());
                Owner.WorldState.SetWSProperty(E_PropKey.E_WEAPON_IN_HANDS, (action as ActionWeaponShow).Show);
            }
            else if (action is ActionUseLever)
            {
                Owner.WorldState.SetWSProperty(E_PropKey.E_USE_WORLD_OBJECT, false);
                InteractionObject = null;
                Interaction       = E_InteractionType.None;
            }
            else if (action is ActionPlayAnim)
            {
                Owner.WorldState.SetWSProperty(E_PropKey.E_PLAY_ANIM, false);
                DesiredAnimation = null;
            }
        }

        ActionFactory.Return(action);
    }
Esempio n. 30
0
        public GameSession()
        {
            // Create message log
            messageLog = new MessageLog();

            // Populate player object
            CurrentPlayer = new Player("Dom", 500, 500, 0, 1, 0);

            // Create new GUI dimensions
            gui = new GUI(100, 30);

            // Create new WorldFactory
            WorldFactory worldFactory = new WorldFactory();

            // Put it into CurrentWorld property
            CurrentWorld    = worldFactory.CreateWorld();
            CurrentLocation = CurrentWorld.GetLocation(0, 0);

            // Create new ActionFactory
            ActionFactory actionFactory = new ActionFactory();

            action       = actionFactory.CreateAction();
            battleAction = actionFactory.CreateBattleAction();


            CurrentPlayer.AddItemToInventory(ItemFactory.CreateItem(2001));
            CurrentPlayer.AddItemToInventory(ItemFactory.CreateItem(2002));
            CurrentPlayer.AddItemToInventory(ItemFactory.CreateItem(2003));
            CurrentPlayer.AddItemToInventory(ItemFactory.CreateItem(1001));

            CurrentPlayer.CurrentWeapon = CurrentPlayer.Inventory.Where(i => i.Type == Item.ItemType.Weapon).FirstOrDefault();
        }