/// <summary> /// Loads this combo with schemas relating to a specific type of geometry /// </summary> /// <param name="type">The spatial type(s) of interest</param> /// <returns>The default schema in the combo (if any)</returns> public ITable Load(SpatialType type) { ILayer layer = EditingController.Current.ActiveLayer; ITable[] schemas = EnvironmentContainer.Schemas(type, layer); Array.Sort <ITable>(schemas, delegate(ITable a, ITable b) { return(a.TableName.CompareTo(b.TableName)); }); this.DataSource = schemas; // If a specific geometric type was supplied, & the specified // layer has a default entity type, scroll to the first schema for that entity if (type == 0) { return(null); } //IEntity ent = EnvironmentContainer.GetDefaultEntity(type, layer); IEntity ent = CadastralMapModel.Current.GetDefaultEntity(type); if (ent != null) { ITable[] tabs = ent.DefaultTables; if (tabs.Length > 0) { this.SelectedItem = tabs[0]; return(tabs[0]); } } return(null); }
private void EntityTranslationForm_Shown(object sender, EventArgs e) { unknownTextBox.Text = m_Alias; IEntity[] ents = EnvironmentContainer.EntityTypes(m_Type); listBox.Items.AddRange(ents); }
private void AttachPointForm_Shown(object sender, EventArgs e) { // Load the entity combo box with a list for point features. m_PointType = entityTypeComboBox.Load(SpatialType.Point); // The option to make the selected type the default for // this command is ALWAYS set by default defaultCheckBox.Checked = true; // If there is a default entity for this command (on the // current editing layer), select that instead & disable // the corresponding checkbox int entId = ReadDefaultPointEntityTypeId(); if (entId > 0) { IEntity ent = EnvironmentContainer.FindEntityById(entId); if (ent != null) { entityTypeComboBox.SelectEntity(ent); defaultCheckBox.Enabled = false; m_PointType = ent; } } // Check auto-repeat option (default is to repeat) int repeat = GlobalUserSetting.ReadInt(REPEAT_KEY, 1); m_Repeat = (repeat != 0); repeatCheckBox.Checked = m_Repeat; }
/// <summary> /// Loads this combo with entity types relating to a specific /// editing layer, sorting the list by entity type name. /// </summary> /// <param name="type">The spatial type(s) of interest</param> /// <param name="layer">The layer of interest</param> /// <returns>The default entity type in the combo (if any)</returns> public IEntity Load(SpatialType type, ILayer layer) { IEntity[] entities = EnvironmentContainer.EntityTypes(type, layer); Array.Sort <IEntity>(entities, delegate(IEntity a, IEntity b) { return(a.Name.CompareTo(b.Name)); }); // If we're not supposed to show blank entities, weed them out if (!m_ShowBlankEntityType) { entities = Array.FindAll(entities, e => e.Name.Length > 0); } this.DataSource = entities; //IEntity ent = EnvironmentContainer.GetDefaultEntity(type, layer); IEntity ent = CadastralMapModel.Current.GetDefaultEntity(type); if (ent == null) { return(null); } // The objects representing the default may be in a different address // space, so ensure we return the item from the combo. ent = Array.Find <IEntity>(entities, e => (e.Name == ent.Name)); this.SelectedItem = ent; return(ent); }
/// <summary> /// Convert /// </summary> /// <param name="value">Value</param> /// <param name="targetType">Target type</param> /// <param name="parameter">Parameter</param> /// <param name="culture">Culture</param> /// <returns>Converted value</returns> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (!(value is Brush brush)) { return("#FFFFFF"); } return(EnvironmentContainer.ConvertMediaBrushToDrawingColor(brush).ToHexString()); }
/// <summary> /// Creates a <see cref="Player"/> from the provided token values. /// </summary> /// <param name="token"></param> /// <param name="env"></param> /// <returns></returns> public Player ConstructPlayer(JToken token, EnvironmentContainer env) { // Get and load the hero. var hero = ContentLoader.LoadHero(token["Hero"].ToString(), env.Content, env.Lua); // Enumerate and retieve the mana. var mana = (token["Mana"] as JArray).ToArray().Select((m) => new ManaType(m.ToString())); // Create the hero and return also getting the user id from the token. return(new Player(token["ID"].ToString(), hero, new ManaPool(mana.ToArray()))); }
private void ExecuteStopCommand() { MouseService.SetBusyState(); _cts?.Cancel(); _myStopwatch.Reset(); _currentStatusbarState = EStatusbarState.Default; SetCurrentBusinessData(); EnvironmentContainer.CreatePopUpWindow(EnvironmentContainer.ApplicationTitle, Application.Current.TryFindResource("CalculationStopped").ToString()); }
/// <summary> /// Records the active project. /// </summary> /// <param name="p">The project the user is working with</param> internal void SetProject(Project p) { m_ActiveLayer = EnvironmentContainer.FindLayerById(p.LayerId); if (m_ActiveLayer == null) { throw new ApplicationException("Cannot locate map layer associated with selected project"); } m_Project = p; }
/// <summary> /// Initializes a new instance of the <see cref="RowTextGeometry"/> class, using the supplied /// content placeholder and the row of attribute data that has been discovered. /// </summary> /// <param name="row">The row that contains the information to format</param> /// <param name="content">The content placeholder read from the database</param> /// <remarks>This constructor is utilized during deserialization from the database, which /// occurs when an editing project is opened.</remarks> internal RowTextGeometry(Row row, RowTextContent content) : base(content) { if (row == null) { throw new ArgumentNullException(); } m_Row = row; m_Template = EnvironmentContainer.FindTemplateById(content.TemplateId); //if (m_Template == null) // throw new ArgumentException("Text template not found"); }
private void OnStartCalculationPropertyChanged(object sender, PropertyChangedEventArgs e) { if (!e.PropertyName.Equals("IsSuccessfullyCompleted")) { return; } _currentStatusbarState = EStatusbarState.Default; _myStopwatch?.Stop(); SetCurrentBusinessData(); EnvironmentContainer.CreatePopUpWindow(EnvironmentContainer.ApplicationTitle, Application.Current.TryFindResource("CalculationFinished").ToString()); OnPropertyChanged(nameof(HierarchialData)); OnPropertyChanged(nameof(CollectionView)); }
/// <summary> /// Adds the cards fround in token to the provided player. /// </summary> public void AddCardsToPlayer(DuelFlow flow, Player player, JToken token, EnvironmentContainer env) { // Go through each card found in the json token. foreach (string cardId in token["Cards"]) { // Load the card. var card = ContentLoader.LoadCard(cardId, env.Content, env.Lua); // Create a new instance for each card. var CI = flow.CreateCardInstance(card, player); // Ensure the card has the correct cost. CI.Cost = CI.ImprintCost; // Add the card to the players hand. player.AddCardToHand(CI); } }
public MainWindow() { InitializeComponent(); Title = MyApp.AppSettings.ApplicationNameWithVersion; DockerInternalAddressWarningIsOk.SetVisible(false); EnvironmentContainer.SetVisible(false); Clear_Click(null, null); lastSaver = new LastSaver(MyApp.BuilderFolder); YourUID.Text = MyApp.AppStorage.YourUid; RunInSequence.IsChecked = MyApp.AppStorage.RunInSequence; CloseApplicationAfterRun.IsChecked = MyApp.AppStorage.CloseApplicationAfterRun; UpdateStatusBar(); UpdateAfterChecked(null, null); }
private async Task ExecuteStartCalculationCommandAsync() { MouseService.SetBusyState(); EnvironmentContainer.CreatePopUpWindow(EnvironmentContainer.ApplicationTitle, Application.Current.TryFindResource("CalculationStart").ToString()); _myStopwatch.Reset(); _myStopwatch.Start(); _currentStatusbarState = EStatusbarState.Busy; SetCurrentBusinessData(); _cts?.Dispose(); _cts = new CancellationTokenSource(); await EnvironmentContainer.Instance.StartCalculationAsync(HierarchialData.Where(p => p.HasChildren).ToList(), _cts.Token).ConfigureAwait(false); }
private void GetEntityForm_Shown(object sender, EventArgs e) { // Display appropriate form title if (m_Type == SpatialType.Point) { this.Text = "Entity type for points"; } else if (m_Type == SpatialType.Line) { this.Text = "Entity type for lines"; } else if (m_Type == SpatialType.Polygon) { this.Text = "Entity type for area labels"; } else if (m_Type == SpatialType.Text) { this.Text = "Entity type for text"; } else { this.Text = "Specify entity type"; } // Load the entity types for the spatial data type IEntity[] ents = EnvironmentContainer.EntityTypes(m_Type, m_Layer); listBox.Items.AddRange(ents); // Remove first item if it's blank if (listBox.Items.Count > 0 && listBox.Items[0].ToString().Length == 0) { listBox.Items.RemoveAt(0); } // Select the current default for the layer IEntity defEnt = GetListDefault(); listBox.SelectedItem = defEnt; // The polygon boundary checkbox should only be visible for lines // (and should be checked if the default entity type is topological). polBoundaryCheckBox.Visible = (m_Type == SpatialType.Line); if (polBoundaryCheckBox.Visible && defEnt != null) { polBoundaryCheckBox.Checked = defEnt.IsPolygonBoundaryValid; } }
private void NewPointForm_Load(object sender, EventArgs e) { // Display alternate window title if one has been supplied. if (!String.IsNullOrEmpty(m_Title)) { this.Text = m_Title; } ILayer layer = m_Cmd.ActiveLayer; IEntity[] entities = EnvironmentContainer.EntityTypes(SpatialType.Point, layer); Array.Sort <IEntity>(entities, delegate(IEntity a, IEntity b) { return(a.Name.CompareTo(b.Name)); }); entityTypeComboBox.DataSource = entities; // If it's not an update ... if (!InitUpdate()) { m_PointId = new IdHandle(); // Pick any default entity type (the change handler for the entity type combo will go on to load the ID combo) IEntity defEnt = CadastralMapModel.Current.DefaultPointType; if (defEnt != null) { entityTypeComboBox.SelectedItem = defEnt; // If we are auto-numbering, disable the ID combo. if (EditingController.Current.IsAutoNumber) { idComboBox.Enabled = false; } } else { idComboBox.Enabled = false; } // If the position is defined (because we're recalling // a previous command), fill in those fields too. if (Math.Abs(m_Position.X) > Double.Epsilon && Math.Abs(m_Position.Y) > Double.Epsilon) { ShowPosition(); } } }
/// <summary> /// Reads data that was previously written using <see cref="WriteData"/> /// </summary> /// <param name="editDeserializer">The mechanism for reading back content.</param> /// <param name="font">The text style</param> /// <param name="position">Position of the text's reference point</param> /// <param name="height">The height of the text, in meters on the ground.</param> /// <param name="width">The total width of the text, in meters on the ground.</param> /// <param name="rotation">Clockwise rotation from horizontal</param> static void ReadData(EditDeserializer editDeserializer, out IFont font, out PointGeometry position, out float height, out float width, out IAngle rotation) { if (editDeserializer.IsNextField(DataField.Font)) { int fontId = editDeserializer.ReadInt32(DataField.Font); font = EnvironmentContainer.FindFontById(fontId); } else { font = null; } position = editDeserializer.ReadPointGeometry(DataField.X, DataField.Y); width = (float)editDeserializer.ReadDouble(DataField.Width); height = (float)editDeserializer.ReadDouble(DataField.Height); rotation = editDeserializer.ReadRadians(DataField.Rotation); }
/// <summary> /// Also opens a style file referred to via the property /// <see cref="PropertyNaming.StyleFile"/> (if there is such a definition). /// It then reads the file into a <see cref="StyleFile"/> object for later use. /// </summary> /// <returns>The loaded style file (or null if no such file, or it could /// not be loaded). If the environment variable is undefined, you get back /// an object that represents an empty style file.</returns> StyleFile OpenStyleFile() { // Get the translation (if any) of the property // that refers to the standard style file. IProperty prop = EnvironmentContainer.FindPropertyByName(PropertyNaming.StyleFile); string stdfile = (prop == null ? null : prop.Value); if (String.IsNullOrEmpty(stdfile)) { return(new StyleFile()); } // Create a new style file object, and ask it to load the file. StyleFile file = new StyleFile(); int nStyle = file.Create(stdfile); // Return the file if it loaded ok return(nStyle > 0 ? file : null); }
private void LayerForm_Shown(object sender, EventArgs e) { nameTextBox.Text = m_Edit.Name; IEnvironmentContainer ec = EnvironmentContainer.Current; IEntity[] all = ec.EntityTypes; pointComboBox.Items.AddRange(EnvironmentContainer.Filter(all, SpatialType.Point)); lineComboBox.Items.AddRange(EnvironmentContainer.Filter(all, SpatialType.Line)); textComboBox.Items.AddRange(EnvironmentContainer.Filter(all, SpatialType.Text)); polygonComboBox.Items.AddRange(EnvironmentContainer.Filter(all, SpatialType.Polygon)); if (m_Edit.DefaultPointType != null) { pointComboBox.SelectedItem = m_Edit.DefaultPointType; } if (m_Edit.DefaultLineType != null) { lineComboBox.SelectedItem = m_Edit.DefaultLineType; } if (m_Edit.DefaultTextType != null) { textComboBox.SelectedItem = m_Edit.DefaultTextType; } if (m_Edit.DefaultPolygonType != null) { polygonComboBox.SelectedItem = m_Edit.DefaultPolygonType; } ITheme theme = m_Edit.Theme; if (theme != null) { themeLabel.Visible = true; themeTextBox.Visible = true; themeTextBox.Text = theme.Name; } }
/// <summary> /// Opens an entity translation file /// referred to via the Backsight property <see cref="PropertyNaming.EntityFile"/> /// (if there is such a definition). It then reads the file into an /// <see cref="EntityFile"/> object for later use. /// </summary> /// <returns>The loaded entity translation file (or null if no such file, or /// it could not be loaded).</returns> EntityFile OpenEntityFile() { // Get the translation (if any) of the property // that refers to the entity file. IProperty prop = EnvironmentContainer.FindPropertyByName(PropertyNaming.EntityFile); string entfile = (prop == null ? null : prop.Value); if (String.IsNullOrEmpty(entfile)) { return(null); } // Open the entity file. using (StreamReader sr = File.OpenText(entfile)) { // Create a new entity file object, and ask it to load the file. EntityFile file = new EntityFile(); int nblock = file.Create(sr); // Return the file if it loaded ok return(nblock > 0 ? file : null); } }
/// <summary> /// Initializes a new instance of the <see cref="AcLayerEntitySet"/> class. /// </summary> internal AcLayerEntitySet() { m_EntityToLayer = new Dictionary <string, string>(); m_Entities = new Dictionary <string, IEntity>(); m_Layers = new Dictionary <string, Layer>(); // Grab the entity types that relate to the active editing layer ILayer mapLayer = EditingController.Current.ActiveLayer; IEntity[] entities = EnvironmentContainer.EntityTypes(SpatialType.All, mapLayer); // Initialize entity type -> AC layer name (without any translation), as // well as entity name -> entity type index. foreach (IEntity e in entities) { m_EntityToLayer[e.Name] = e.Name; m_Entities[e.Name] = e; } // Grab any suffixes to append to AC layer names m_PinLayerSuffix = GetLayerSuffix("CED_PIN_LAYER_SUFFIX"); m_DistLayerSuffix = GetLayerSuffix("CED_DIST_LAYER_SUFFIX"); m_AngleLayerSuffix = GetLayerSuffix("CED_ANGLE_LAYER_SUFFIX"); }
/// <summary> /// Executes this new circle operation. /// </summary> internal void Execute() { FeatureFactory ff = new FeatureFactory(this); // The circle (and any closing point) will have the blank entity type (with ID=0). // If you don't do this, the factory will create stuff with default entity types, // and possibly a user-perceived ID. IEntity blank = EnvironmentContainer.FindBlankEntity(); ff.PointType = blank; ff.LineType = blank; base.Execute(ff); /* * // Get the radius, in meters on the ground. * double rad = m_Radius.GetDistance(m_Center).Meters; * if (rad < Constants.TINY) * throw new Exception("NewCircleOperation.Execute - Radius is too close to zero."); * * // If the radius was specified as an offset point, make the circle * // start at that point. * OffsetPoint offset = (m_Radius as OffsetPoint); * PointFeature start = (offset == null ? null : offset.Point); * * // Add a circle to the map. * CadastralMapModel map = MapModel; * ArcFeature arc = map.AddCompleteCircularArc(m_Center, rad, start, this); * * // Record the new arc in the base class. * SetNewLine(arc); * * // Peform standard completion steps * Complete(); */ }
public Sanctuary(int screenWidth, int screenHeight) : base(screenWidth, screenHeight) { if (Container == null) { IEnvironmentContainer environment = new EnvironmentContainer(); Container = environment; LevelWidth = Common.Settings.GlobalSettings.LevelWidth; LevelHeight = Common.Settings.GlobalSettings.LevelHeight; environment.Instances = LevelObjects; LevelItems = environment.Items; // Add Terrain var wall1 = new StaticObjectBehavior(new DungeonStoneWall(new Point(2400, 2600), environment)); var wall2 = new StaticObjectBehavior(new DungeonStoneWall(new Point(2900, 2900), environment)); // Add Items var CopperKey = new CopperKeyItem(new Point(2500, 2500)); var CopperKey3 = new CopperKeyItem(new Point(2560, 2500)); var Knife = new KnifeWeaponItem(new Point(3000, 2500)); // Add NPC var GuideChar = new GuideBehavior(new Sceleton(new KnifeWeaponItem(null), new Point(3000, 2600), environment)); var TestEnemy1 = new TestEnemyBehavior(new Sceleton(new KnifeWeaponItem(null), new Point(3000, 2800), environment)); var TestEnemy2 = new TestEnemyBehavior(new Sceleton(new KnifeWeaponItem(null), new Point(2500, 2400), environment)); var TestEnemy3 = new TestEnemyBehavior(new Sceleton(new KnifeWeaponItem(null), new Point(2700, 2800), environment)); var TestEnemy4 = new TestEnemyBehavior(new Sceleton(new KnifeWeaponItem(null), new Point(2500, 3100), environment)); // Init Player var playerActor = new Thief(new KnifeWeaponItem(null), new Point(2700, 2700), environment); Player = new Player(playerActor); //Player = new Player(playerActor, new InteractionHandler(new Messenger())); ViewPort = new ViewPort(screenWidth, screenHeight, (IInstance)Player); // Load all obstacles environment.AddInstance(wall1); environment.AddInstance(wall2); environment.AddInstance(GuideChar); environment.AddInstance(TestEnemy1); environment.AddInstance(TestEnemy2); environment.AddInstance(TestEnemy3); environment.AddInstance(TestEnemy4); for (var i = 3000; i < 3500; i += 50) { environment.AddInstance(new GuideBehavior(new Sceleton(new KnifeWeaponItem(null), new Point(i, i), environment))); } for (var i = 32; i < 6000; i += 32) { environment.AddInstance(new StaticObjectBehavior(new DungeonStoneWall(new Point(i, 3000), environment))); } environment.AddInstance((IInstance)Player); // Load all items environment.Items.Add(CopperKey); environment.Items.Add(CopperKey3); environment.Items.Add(Knife); } else { IEnvironmentContainer environment = Container; LevelWidth = Common.Settings.GlobalSettings.LevelWidth; LevelHeight = Common.Settings.GlobalSettings.LevelHeight; LevelObjects = environment.Instances; LevelItems = environment.Items; // Init Player var playerActor = new Thief(new KnifeWeaponItem(null), new Point(2600, 2700), environment); Player = new Player(playerActor); //Player = new Player(playerActor, new InteractionHandler(new Messenger())); ViewPort = new ViewPort(screenWidth, screenHeight, (IInstance)Player); environment.AddInstance((IInstance)Player); } SubscribeOnEvents(); }
private async void BaseWindow_Loaded(object sender, RoutedEventArgs e) { if (MyApp.EgwFolder == null) { await Task.Delay(1); Wizzard(); } else { Console.Text = "Loading versions..."; await Task.Delay(1); try { var version = MyApp.Runner.GetVersions(MyApp.BuilderFolder, MyApp.EgwFolder); MyApp.Runner.RetrieveInfo(MyApp.BuilderFolder, MyApp.EgwFolder); Console.Text = version + "\n\nBranches\n" + MyApp.Runner.Info.GetBranches(); var info = MyApp.Runner.Info; additionalTestModels = info.AdditionalTests.Select(test => new AdditionalTestModel(test)).ToList(); AdditionalTests.ItemsSource = additionalTestModels; AdditionalTestsContainer.SetVisible(additionalTestModels.Count > 0); if (!info.ContainsProject("IEC")) { IEC.IsEnabled = false; ForProject("IEC", ch => ch.IsEnabled = false); } if (!info.ContainsProject("AS24")) { AS24.IsEnabled = false; ForProject("AS24", ch => ch.IsEnabled = false); } foreach (var project in info.Projects) { if (!project.SupportTests && FindName("Test_" + project.CodeForComponent) != null) { (FindName("Test_" + project.CodeForComponent) as CheckBox).IsEnabled = false; } } MessageBroker.Text = info.MessageBroker; if (string.IsNullOrWhiteSpace(info.MessageBroker)) { MessageBrokerLabel.Foreground = Brushes.Red; MessageBrokerLabel.ToolTip = "Subapps have different brokers. You can set same broker for all subApps here."; } if (info.IsEnvironmentsShowable) { EnvironmentContainer.SetVisible(true); Environment.Items.Clear(); Environment.ItemsSource = info.GetEnvironments(); Environment.SelectedIndex = 0; } } catch (Exception ex) { Console.Text = "Error: " + ex.Message + "\n" + ex.StackTrace; } await Task.Delay(1); try { if (MyApp.Runner.IsDockerAddressOk()) { DockerInternalAddressWarning.SetVisible(false); DockerInternalAddressWarningIsOk.SetVisible(true); } else { DockerInternalAddressWarning.Text = "WARNING: ip address host.docker.internal is binded to " + MyApp.Runner.GetDockerAddress() + ", which is not address of this computer (ipconfig). Restart Docker Desktop from context menu of Docker Desktop icon in system tray. " + "Otherwise AsyncJob and other services will not work correctly."; } } catch (Exception ex) { Console.Text = "Error: " + ex.Message + "\n" + ex.StackTrace; } } }
/// <summary> /// Creates and starts the test duel. /// </summary> public void Start() { // Open the settings file. var settings = JObject.Parse(File.ReadAllText("game.json")); // Create the random object. If the settings file has a provided seed we use it. ManagedRandom rand; if (settings["RandomSeed"].Type == JTokenType.Null) { rand = new ManagedRandom(); } else { rand = new ManagedRandom(settings["RandomSeed"].ToObject <int>()); } EnvironmentContainer env = new EnvironmentContainer() { AnimationBlocker = new PlaybackBlockingHandler(), Content = new LoadedContent(), Lua = new LuaEnvironment(), Random = rand, Settings = new DuelSettings() }; // Provide the content loader with directory information. ContentLoader.SetContentDirectory(settings["ContentDirectory"].ToString()); // Register loading to the current environemt. ContentLoader.RegisterLoads(env.Content, env.Lua); // Tell the loader to log anything that is loaded. ContentLoader.LogLoads = true; // Get the commands stored in the json file as we will have to load them. var commands = (settings["LoadCommands"] as JArray).Values <string>(); // Apart from commands we also have to manually load the lua functions we provide to the DuelFlow. var cmds = new List <string>(commands) { settings["GameStart"].ToString(), settings["ChangeTurn"].ToString(), settings["GameEnd"].ToString(), }; // Load all the system and command actions. foreach (var cmd in cmds) { ContentLoader.LoadAction(cmd, env.Content, env.Lua); } // Tell the duel flow what we want it to do for the varaible actions. env.Settings.GameStartAction = env.Content.GetAction(settings["GameStart"].ToString()); env.Settings.ChangeTurnAction = env.Content.GetAction(settings["ChangeTurn"].ToString()); env.Settings.GameEndAction = env.Content.GetAction(settings["GameEnd"].ToString()); // Disable animations as we won't see anything on console application and it will just cause slow down. env.Settings.AnimationSpeed = DuelSettings.NO_ANIM; // Create the players. var Player1 = ConstructPlayer(settings["Player1"], env); var Player2 = ConstructPlayer(settings["Player2"], env); // Write a summary of every thing we have loaded. Console.WriteLine("------------------------------"); foreach (string s in env.Content.GetAllKeysSummary()) { Console.WriteLine(s); } // Determine who goes fist. Set as player1 to initalise and causes less lines of code. Player goesFist = Player1; switch (settings["GoesFirst"].ToString()) { case "Player2": goesFist = Player2; break; case "Random": // If the first player is random we need to use the ManagedRandom to decide. int val = env.Random.Next(0, 2); if (val == 0) { goesFist = Player2; } break; } // Create and ready the duel flow. DuelFlow flow = new DuelFlow(env, Player1, Player2, goesFist); // Add all the cards the players asked for to their hands. AddCardsToPlayer(flow, Player1, settings["Player1"], env); AddCardsToPlayer(flow, Player2, settings["Player2"], env); // Provide the callback functions with a simple console print statement. flow.OutBoundDelegate += (object sender, ClientRequest data) => { Console.WriteLine(data.RequestId + " sent to all players."); }; Player1.OutBoundDelegate += (object sender, ClientRequest data) => { Console.WriteLine(data.RequestId + " sent to " + Player1.UserId); }; Player2.OutBoundDelegate += (object sender, ClientRequest data) => { Console.WriteLine(data.RequestId + " sent to " + Player2.UserId); }; // Stop any loading from happening during gameplay as it will cause slowdown. ContentLoader.DeregisterLoads(env.Lua); // Start the duel. Thread loop = flow.Start(); while (flow.State.OnGoing) { //Delay the thread incase of ongoing logic. Thread.Sleep(50); // Get the player whose turn it currently is. var towner = flow.State.CurrentTurn.Owner; // Display information about the game. Console.WriteLine(); // Whose turn it is. Display.Turn(flow.State.CurrentTurn); // TurnOwner's stats. Display.PlayerStats(towner); // Other Player's stats. Display.PlayerStats(flow.State.GetOpposingPlayer(towner)); Console.WriteLine(); // And the field. Display.Field(flow.State.Field); Console.WriteLine(); Console.WriteLine(); // Get input from the console. string x = Console.ReadLine(); // Clear the consloe for the next command. Console.Clear(); // Split the command into its components. string[] splits = x.Split(' '); switch (splits[0].ToLower()) { case "level": flow.EnqueueCommand("CMDLevelUp", towner); break; case "levelup": flow.EnqueueCommand("CMDLevelUp", towner); break; case "disc": if (splits.Length != 2) { Console.WriteLine("Please provide a card number. example: disc 2"); break; } if (towner.Hand.Count == 0) { Console.WriteLine("Your hand is empty."); break; } if (int.TryParse(splits[1], out int index)) { if (index > towner.Hand.Count - 1) { Console.WriteLine("Card number provided is to high."); break; } if (index < 0) { Console.WriteLine("Card number cannot be negative"); break; } flow.EnqueueCommand("CMDDiscard", towner, towner.Hand.ElementAt(index)); break; } else { Console.WriteLine("Please provide a card number. example: disc 2"); break; } case "discard": if (splits.Length != 2) { Console.WriteLine("Please provide a card number. example: discard 2"); break; } if (towner.Hand.Count == 0) { Console.WriteLine("Your hand is empty."); break; } if (int.TryParse(splits[1], out int index2)) { if (index2 > towner.Hand.Count - 1) { Console.WriteLine("Card number provided is to high."); break; } if (index2 < 0) { Console.WriteLine("Card number cannot be negative"); break; } flow.EnqueueCommand("CMDDiscard", towner, towner.Hand.ElementAt(index2)); break; } else { Console.WriteLine("Please provide a card number. example: discard 2"); break; } case "hand": Display.Collection("Hand", towner.Hand); break; case "grave": Display.Collection("Grave", towner.Grave); break; case "revive": flow.EnqueueCommand("CMDRevive", towner); break; case "rev": flow.EnqueueCommand("CMDRevive", towner); break; case "play": if (splits.Length != 3) { Console.WriteLine("Please provide a card number and a position. example: play 2 4"); Console.WriteLine("This would place card 2 in position 4."); break; } if (towner.Hand.Count == 0) { Console.WriteLine("Your hand is empty."); break; } if (int.TryParse(splits[1], out int index3)) { if (index3 > towner.Hand.Count - 1) { Console.WriteLine("Card number provided is to high."); break; } if (index3 < 0) { Console.WriteLine("Card number cannot be negative"); break; } if (int.TryParse(splits[2], out int pos)) { if (pos > flow.State.Field.Count() - 1 || pos < 0) { Console.WriteLine("Position must be a spot on the field. MaxPos: " + flow.State.Field.Count()); break; } flow.EnqueueCommand("CMDPlayCard", towner, towner.Hand.ElementAt(index3), flow.State.Field[pos]); break; } else { Console.WriteLine("Please provide a card number and a position. example: play 2 4"); Console.WriteLine("This would place card 2 in position 4."); break; } } else { Console.WriteLine("Please provide a card number and a position. example: play 2 4"); Console.WriteLine("This would place card 2 in position 4."); break; } case "charge": flow.EnqueueCommand("CMDCharge", towner); break; case "end": loop.Abort(); break; case "help": Console.WriteLine("Commands: [charge, play, level(up), disc(ard), rev(ive), hand, grave, help]"); break; default: Console.WriteLine(x + " is not a valid command."); Console.WriteLine("Commands: [charge, play, level(up), disc(ard), rev(ive), hand, grave, help]"); break; } } Console.WriteLine("Game Over - Press Any Key to Terminate"); Console.ReadLine(); }
void LoadDataFiles(string folderName, uint[] fileNums) { Trace.Write("Reading data..."); EditDeserializer ed = new EditDeserializer(this); Session lastSession = null; IdManager idMan = m_MapModel.IdManager; foreach (uint fileNum in fileNums) { string editFile = Path.Combine(folderName, ProjectDatabase.GetDataFileName(fileNum)); using (TextReader tr = File.OpenText(editFile)) { TextEditReader er = new TextEditReader(tr); // Ignore any empty files altogether while (er.HasNext) { ed.SetReader(er); Change edit = Change.Deserialize(ed); if (edit is NewProjectEvent) { m_ProjectInfo = (NewProjectEvent)edit; // If the project settings don't have default entity types, initialize them with // the layer defaults. This covers a case where the settings file has been lost, and // automatically re-created by ProjectSettings.CreateInstance. var layer = EnvironmentContainer.FindLayerById(m_ProjectInfo.LayerId); m_Settings.SetEntityTypeDefaults(layer); } else if (edit is NewSessionEvent) { lastSession = new Session(this, (NewSessionEvent)edit, editFile); m_MapModel.AddSession(lastSession); } else if (edit is EndSessionEvent) { Debug.Assert(lastSession != null); lastSession.EndTime = edit.When; } else if (edit is IdAllocation) { if (idMan != null) { IdAllocation alloc = (IdAllocation)edit; IdGroup g = idMan.FindGroupById(alloc.GroupId); g.AddIdPacket(alloc); // Remember that allocations have been made in the session (bit of a hack // to ensure the session isn't later removed if no edits are actually // performed). lastSession.AddAllocation(alloc); } } else { Debug.Assert(edit is Operation); Debug.Assert(lastSession != null); lastSession.AddOperation((Operation)edit); } } } } if (m_ProjectInfo == null) { throw new ApplicationException("Could not locate the project creation event"); } // Apply any forward references ed.ApplyForwardRefs(); // Remember the highest internal ID used by the project SetLastItem(fileNums[fileNums.Length - 1]); }
/// <summary> /// Reads an entity type for a spatial feature. /// </summary> /// <param name="field">A tag associated with the value</param> /// <returns>The entity type that was read.</returns> internal IEntity ReadEntity(DataField field) { int id = m_Reader.ReadInt32(field.ToString()); return(EnvironmentContainer.FindEntityById(id)); }
public AutomationController(HttpContext context, StateMachine stateMachine, EnvironmentContainer environmentContainer) { _context = context; _stateMachine = stateMachine; _environmentContainer = environmentContainer; }