public static void DeclareWar(DialogueContext Context) { Context.Envoy.OwnerFaction.Race.Speech.Language.SayBoo(); if (!Context.Politics.HasEvent("you declared war on us")) { Context.Politics.RecentEvents.Add(new Diplomacy.PoliticalEvent() { Change = -2.0f, Description = "you declared war on us", Duration = new TimeSpan(4, 0, 0, 0), Time = Context.World.Time.CurrentDate }); Context.Politics.WasAtWar = true; } Context.Say(Datastructures.SelectRandom(Context.Envoy.OwnerFaction.Race.Speech.WarDeclarations)); Context.ClearOptions(); Context.AddOption("Goodbye.", (context) => { Diplomacy.RecallEnvoy(context.Envoy); GameState.Game.StateManager.PopState(); }); Context.World.GoalManager.OnGameEvent(new Goals.Events.DeclareWar { PlayerFaction = Context.PlayerFaction, OtherFaction = Context.Envoy.OwnerFaction }); }
public override EnumScaffoldIterationResult firstIteration(GraphScaffoldInstanceData scaffoldInstanceData, Datastructures.TreeNode graph, int startEdgeIndex, getVertexPositionByIndexDelegate getVertexPositionByIndex) { ExtractLineScaffoldInstanceData castedInstanceData; Datastructures.Variadic variadicPositionA; Datastructures.Variadic variadicPositionB; int vertexIndexA; int vertexIndexB; castedInstanceData = (ExtractLineScaffoldInstanceData)scaffoldInstanceData; getVertexIndicesOfEdge(graph, startEdgeIndex, out vertexIndexA, out vertexIndexB); variadicPositionA = getVertexPositionByIndex(graph, vertexIndexA); variadicPositionB = getVertexPositionByIndex(graph, vertexIndexB); System.Diagnostics.Debug.Assert(variadicPositionA.type == Datastructures.Variadic.EnumType.VECTOR2FLOAT); System.Diagnostics.Debug.Assert(variadicPositionB.type == Datastructures.Variadic.EnumType.VECTOR2FLOAT); castedInstanceData.startVertexIndexA = vertexIndexA; castedInstanceData.startVertexIndexB = vertexIndexB; castedInstanceData.startVertexPositionA = variadicPositionA.valueVector2Float; castedInstanceData.startVertexPositionB = variadicPositionB.valueVector2Float; return EnumScaffoldIterationResult.FULLMATCH; }
public Microsoft.Xna.Framework.Vector3 GetSpawnLocation(WorldManager world, EntitySpawnLocation SpawnLocation) { Microsoft.Xna.Framework.Vector3 location = location = VoxelHelpers.FindFirstVoxelBelowIncludeWater(new VoxelHandle(world.ChunkManager.ChunkData, GlobalVoxelCoordinate.FromVector3(MonsterSpawner.GetRandomWorldEdge(world)))).WorldPosition + Microsoft.Xna.Framework.Vector3.Up * 1.5f; switch (SpawnLocation) { case EntitySpawnLocation.BalloonPort: { var balloonport = world.PlayerFaction.GetRooms().OfType <BalloonPort>(); if (balloonport.Any()) { location = Datastructures.SelectRandom(balloonport).GetBoundingBox().Center() + Microsoft.Xna.Framework.Vector3.Up * 1.5f; } break; } case EntitySpawnLocation.RandomZone: { var zones = world.PlayerFaction.GetRooms(); if (zones.Any()) { location = Datastructures.SelectRandom(zones).GetBoundingBox().Center() + Microsoft.Xna.Framework.Vector3.Up * 1.5f; } break; } case EntitySpawnLocation.WorldEdge: { // already computed break; } } return(location); }
// Uses depth-first search to check if the graph induced by the subgraph given as a parameter is connected // In other words, we retreive all edges from the original graph and check the subgraph for connectedness public static bool Connected(Datastructures.Graph graph, BitSet subgraph) { // Vertices that are visited Set<int> visited = new Set<int>(); // Stack of vertices yet to visit Stack<int> stack = new Stack<int>(); // Initial vertex int s = subgraph.First(); stack.Push(s); // Continue while there are vertices on the stack while (stack.Count > 0) { int v = stack.Pop(); // If we have not encountered this vertex before, then we check for all neighbors if they are part of the subgraph // If a neighbor is part of the subgraph it means that we have to push it on the stack to explore it at a later stage if (!visited.Contains(v)) { visited.Add(v); foreach (int w in graph.OpenNeighborhood(v)) if (subgraph.Contains(w)) stack.Push(w); } } // If we visited an equal number of vertices as there are vertices in the subgraph then the subgraph is connected return visited.Count == subgraph.Count; }
private void randomButton2_OnClicked() { List <List <string> > atoms = TextGenerator.GetAtoms(ContentPaths.Text.Templates.mottos); CompanyMotto = TextGenerator.GenerateRandom(Datastructures.SelectRandom(atoms).ToArray()); CompanyMottoEdit.Text = CompanyMotto; }
private void randomButton_OnClicked() { var templates = TextGenerator.GetAtoms(ContentPaths.Text.Templates.company_exploration); CompanyName = TextGenerator.GenerateRandom(Datastructures.SelectRandom(templates).ToArray()); CompanyNameEdit.Text = CompanyName; }
/*************************/ // Selecting initial vertices /*************************/ // Returns a vertex on the last level of a Breadth-first search (BFS) public static int Bfs(Datastructures.Graph graph, int init) { // BFS working queue Queue<int> queue = new Queue<int>(); // Vertices that have already been visited Set<int> visited = new Set<int>(); // Initial vertex is given as input visited.Add(init); queue.Enqueue(init); int current = init; // While there is still a vertex in the queue... while (queue.Count > 0) { //... select the first vertex and process it current = queue.Dequeue(); foreach (int w in graph.OpenNeighborhood(current)) { // Enqueue all neighbors that have not been processed yet if (!visited.Contains(w)) { visited.Add(w); queue.Enqueue(w); } } } // This is the last vertex that has been processed, thus a vertex that is on the last level of the BFS search return current; }
public static void ConversationRoot(DialogueContext Context) { RootWithPrompt(String.Format("{0} I am {1} of {2}.", Datastructures.SelectRandom(Context.Envoy.OwnerFaction.Race.Speech.Greetings), Context.EnvoyName, Context.Envoy.OwnerFaction.Name))(Context); }
private static UNSequence ComputeSequence(Datastructures.Graph graph, BitSet connectedComponent, CandidateStrategy candidateStrategy, int init, ref int max) { int n = graph.Size; List<int> sequence = new List<int>() { init }; BitSet left = new BitSet(0, n, new int[] { init }); BitSet right = connectedComponent - init; // Initially we store the empty set and the set with init as the representative, ie N(init) * right Set<BitSet> unLeft = new Set<BitSet>() { new BitSet(0, n), graph.OpenNeighborhood(init) * right }; int value = int.MinValue; while (!right.IsEmpty) { Set<BitSet> unChosen = new Set<BitSet>(); int chosen = Heuristics.TrivialCases(graph, left, right); if (chosen != -1) { unChosen = IncrementUn(graph, left, unLeft, chosen); } // If chosen has not been set it means that no trivial case was found // Depending on the criteria for the next vertex we call a different algorithm else { BitSet candidates = Heuristics.Candidates(graph, left, right, candidateStrategy); int min = int.MaxValue; foreach (int v in candidates) { Set<BitSet> unV = IncrementUn(graph, left, unLeft, v); if (unV.Count < min) { chosen = v; unChosen = unV; min = unV.Count; } } } // This should never happen if (chosen == -1) throw new Exception("No vertex is chosen for next step in the heuristic"); // Add/remove the next vertex in the appropiate sets sequence.Add(chosen); left += chosen; right -= chosen; unLeft = unChosen; value = Math.Max(unChosen.Count, value); if (value > max) { return new UNSequence() { Sequence = null, Value = int.MaxValue }; } } return new UNSequence() { Sequence = sequence, Value = value }; }
// throws TranslationException private static string getIdentifierOfElement(Datastructures.Dag<DagElementData> dag, int elementIndex) { if (!(dag.elements[elementIndex].content.type == DagElementData.EnumType.IDENTIFIERNAME)) { throw new TranslationException(); } return dag.elements[elementIndex].content.identifier; }
// throws TranslationException private static string getStringOfConstInt(Datastructures.Dag<DagElementData> dag, int elementIndex) { if (!(dag.elements[elementIndex].content.type == DagElementData.EnumType.CONSTINT)) { throw new TranslationException(); } return dag.elements[elementIndex].content.valueInt.ToString(); }
public override bool ApplyObjects(Creature self, IEnumerable <Body> objects) { var body = Datastructures.SelectRandom(objects); base.ApplyObjects(self, objects); if (body != null) { return(Attack.Perform(self, body, DwarfTime.LastTime, Bonus, body.Position, self.Faction.Name)); } return(true); }
public override void call(List<Datastructures.Variadic> parameters, List<Datastructures.Variadic> globals, out Datastructures.Variadic result, out GeneticProgramming.TypeRestrictedOperator.EnumResult resultCode) { Datastructures.TreeNode resultGraph; Datastructures.TreeNode grid0; Datastructures.TreeNode grid1; // this are arrays wih the indices of the elements in the graph from the elements in the Grid // it has the size of gridSizeX * gridsizeY // is -1 if the grid element wasn't saved allready inside the graph int[] groupsGraphElementIndicesForGrid0; int[] groupsGraphElementIndicesForGrid1; groupsGraphElementIndicesForGrid0 = null; groupsGraphElementIndicesForGrid1 = null; resultCode = GeneticProgramming.TypeRestrictedOperator.EnumResult.FAILED; result = null; // we accept at the current time only two inputs if( parameters.Count != 2 || parameters[0].type != Datastructures.Variadic.EnumType.STORAGEALGORITHMICCONCEPTTREE || parameters[1].type != Datastructures.Variadic.EnumType.STORAGEALGORITHMICCONCEPTTREE ) { return; } grid0 = parameters[0].valueTree; grid1 = parameters[1].valueTree; // initialize result graph resultGraph = new Datastructures.TreeNode(); resultGraph.childNodes.Add(new Datastructures.TreeNode()); resultGraph.childNodes.Add(new Datastructures.TreeNode()); resultGraph.childNodes.Add(new Datastructures.TreeNode()); result = new Datastructures.Variadic(Datastructures.Variadic.EnumType.STORAGEALGORITHMICCONCEPTTREE); result.valueTree = resultGraph; initializeIndicesOfGrid(ref groupsGraphElementIndicesForGrid0); initializeIndicesOfGrid(ref groupsGraphElementIndicesForGrid1); storeGridElementsIntoGraph(ref groupsGraphElementIndicesForGrid0, grid0, resultGraph.childNodes[GRAPHINDEXVERTICES]); storeGridElementsIntoGraph(ref groupsGraphElementIndicesForGrid1, grid1, resultGraph.childNodes[GRAPHINDEXVERTICES]); // go through each element in grid0 and search for new possible connections to grid1 searchForNewPossibleConnectionsBetweenGrids(ref groupsGraphElementIndicesForGrid0, ref groupsGraphElementIndicesForGrid1, grid0, grid1, resultGraph.childNodes[GRAPHINDEXEDGES], resultGraph.childNodes[GRAPHINDEXVERTICES]); // go through each element in grid1 and search for new possible connections to grid0 searchForNewPossibleConnectionsBetweenGrids(ref groupsGraphElementIndicesForGrid1, ref groupsGraphElementIndicesForGrid0, grid1, grid0, resultGraph.childNodes[GRAPHINDEXEDGES], resultGraph.childNodes[GRAPHINDEXVERTICES]); resultCode = GeneticProgramming.TypeRestrictedOperator.EnumResult.OK; }
/*************************/ // Computing Exact Linear Decompositions /*************************/ public static LinearDecomposition ExactLinearDecomposition(Datastructures.Graph graph) { Initialize(graph.Size); // Construct the table with the correct width values ConstructSequence(graph, graph.Vertices); // Retrieve a sequence that will result in our bound not being exceeded List<int> sequence = RetrieveSequence(graph, graph.Vertices); return new LinearDecomposition(graph, sequence); }
/*************************/ // Computing Exact Decompositions /*************************/ public static Decomposition Compute(Datastructures.Graph graph) { Initialize(graph.Size); // Construct the table with the correct width values ConstructTree(graph, graph.Vertices); // Retrieve a sequence that will result in our bound not being exceeded Tree tree = RetrieveTree(graph); return new Decomposition(graph, tree); }
// throws TranslationException private static string getStringOfTypeOf(Datastructures.Dag<DagElementData> dag, int elementIndex) { if (dag.elements[elementIndex].content.type == DagElementData.EnumType.CONSTINT) { return "int"; } else if (dag.elements[elementIndex].content.type == DagElementData.EnumType.CONSTFLOAT) { return "float"; } throw new TranslationException(); }
private void DrawGUI(DwarfTime gameTime, float dx) { GUI.PreRender(gameTime, DwarfGame.SpriteBatch); DwarfGame.SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null); Drawer.Render(DwarfGame.SpriteBatch, null, Game.GraphicsDevice.Viewport); GUI.Render(gameTime, DwarfGame.SpriteBatch, new Vector2(0, dx)); Progress.Message = !GenerationComplete ? LoadingMessage : ""; if (GenerationComplete) { Rectangle imageBounds = MapPanel.GetImageBounds(); float scaleX = ((float)imageBounds.Width / (float)PlayState.WorldWidth); float scaleY = ((float)imageBounds.Height / (float)PlayState.WorldHeight); Rectangle spawnRect = GetSpawnRectangle(); Rectangle spawnRectOnImage = GetSpawnRectangleOnImage(); Drawer2D.DrawRect(DwarfGame.SpriteBatch, spawnRectOnImage, Color.Yellow, 3.0f); Drawer2D.DrawStrokedText(DwarfGame.SpriteBatch, "Spawn", DefaultFont, new Vector2(spawnRectOnImage.X - 5, spawnRectOnImage.Y - 20), Color.White, Color.Black); //ImageMutex.WaitOne(); /* * DwarfGame.SpriteBatch.Draw(MapPanel.Image.Image, * new Rectangle(MapPanel.GetImageBounds().Right + 2, MapPanel.GetImageBounds().Top, spawnRect.Width * 4, spawnRect.Height * 4), * spawnRect, Color.White); */ //ImageMutex.ReleaseMutex(); CloseupPanel.Image.Image = MapPanel.Image.Image; CloseupPanel.Image.SourceRect = spawnRect; if (ViewSelectionBox.CurrentValue == "Factions") { foreach (Faction civ in NativeCivilizations) { Point start = civ.Center; Vector2 measure = Datastructures.SafeMeasure(GUI.SmallFont, civ.Name); Rectangle snapped = MathFunctions.SnapRect( new Vector2(start.X * scaleX + imageBounds.X, start.Y * scaleY + imageBounds.Y) - measure * 0.5f, measure, imageBounds); Drawer2D.DrawStrokedText(DwarfGame.SpriteBatch, civ.Name, GUI.SmallFont, new Vector2(snapped.X, snapped.Y), Color.White, Color.Black); } } } GUI.PostRender(gameTime); DwarfGame.SpriteBatch.End(); }
public static LinearDecomposition Compute(Datastructures.Graph graph, CandidateStrategy candidateStrategy, InitialVertexStrategy initialVertexStrategy) { List<BitSet> connectedComponents = DepthFirstSearch.ConnectedComponents(graph); List<int> sequence = new List<int>(); foreach (BitSet connectedComponent in connectedComponents) { switch (initialVertexStrategy) { case InitialVertexStrategy.All: { UNSequence minSequence = new UNSequence() { Value = int.MaxValue}; int max = int.MaxValue; object _lock = new object(); Parallel.ForEach(connectedComponent, vertex => { UNSequence tempSequence = ComputeSequence(graph, connectedComponent, candidateStrategy, vertex, ref max); lock (_lock) { if (tempSequence.Value < minSequence.Value) { max = minSequence.Value; minSequence = tempSequence; } } }); sequence.AddRange(minSequence.Sequence); } break; case InitialVertexStrategy.Bfs: { int init = Heuristics.Bfs(graph, connectedComponent.Last()); sequence.AddRange(ComputeSequence(graph, connectedComponent, candidateStrategy, init)); } break; case InitialVertexStrategy.DoubleBfs: { int init = Heuristics.Bfs(graph, Heuristics.Bfs(graph, connectedComponent.Last())); sequence.AddRange(ComputeSequence(graph, connectedComponent, candidateStrategy, init)); } break; } } return new LinearDecomposition(graph, sequence); }
public override void Render(DwarfTime gameTime) { TipTimer.Update(gameTime); if (TipTimer.HasTriggered) { var entry = Datastructures.SelectRandom(TutorialManager.EnumerateTutorials()); Tip.Text = entry.Value.Title + "\n" + entry.Value.Text; Tip.Invalidate(); TipTimer.Reset(10.0f); } EnableScreensaver = true; base.Render(gameTime); Runner.Render(Game.GraphicsDevice, DwarfGame.SpriteBatch, gameTime); GuiRoot.Draw(); }
// Returns all connected components in a certain subgraph, where we define a subgraph by the vertices that are contained in it // We apply multiple dfs searches to find all connected parts of the graph public static List<BitSet> ConnectedComponents(Datastructures.Graph graph, BitSet subgraph) { // Each connected component is defined as a bitset, thus the result is a list of these bitsets List<BitSet> result = new List<BitSet>(); // Working stack for the dfs algorithm Stack<int> stack = new Stack<int>(); // Each vertex of the subgraph will either be explored, or it will be the starting point of a new dfs search BitSet todo = subgraph; while (!todo.IsEmpty) { int s = todo.First(); stack.Push(s); // Start tracking the new component BitSet component = new BitSet(0, graph.Size); // Default dfs exploring part of the graph while (stack.Count > 0) { int v = stack.Pop(); // If we have not encountered this vertex before (meaning it isn't in this component), then we check for all neighbors if they are part of the subgraph // If a neighbor is part of the subgraph it means that we have to push it on the stack to explore it at a later stage for this component if (!component.Contains(v)) { component += v; // Remove this vertex from the 'todo' list, since it can never be the starting point of a new component todo -= v; foreach (int w in graph.OpenNeighborhood(v)) if (subgraph.Contains(w)) stack.Push(w); } } // The whole connected component has been found, so we can add it to the list of results result.Add(component); } return result; }
public static void ConversationRoot(DialogueContext Context) { Context.Say(String.Format("{0} I am {1} of {2}.", Datastructures.SelectRandom(Context.Envoy.OwnerFaction.Race.Speech.Greetings), Context.EnvoyName, Context.Envoy.OwnerFaction.Name)); Context.ClearOptions(); Context.AddOption("Trade", Trade); Context.AddOption("Leave", (context) => { Diplomacy.RecallEnvoy(context.Envoy); Context.Say(Datastructures.SelectRandom(context.Envoy.OwnerFaction.Race.Speech.Farewells)); Context.ClearOptions(); Context.AddOption("Goodbye.", (_) => { GameState.Game.StateManager.PopState(); }); }); }
// Constructs the actual width values // The idea is the following: If we want to know the optimal width for a certain cut A, thus Width[A], then we can obtain this by // either taking the max(Cuts[A], the minimum over all widths of Width[A - a]), which is our recurrence relation. private static void ConstructSequence(Datastructures.Graph graph, BitSet A) { // min saves the minimum size of all neighborhoods of the cut [A - a], where a can be any vertex in A long min = long.MaxValue; // v will be the optimal choice to leave out in the previous iteration in order to obtain A's full neighborhood int v = -1; foreach (int a in A) { BitSet previous = A - a; // If we have not constructed the previous step yet, then go in recursion and do so if (!_neighborhoods.ContainsKey(previous)) ConstructSequence(graph, previous); // Save the minimum value if (_width[previous] < min) { min = _width[previous]; v = a; } } // Obtain the neighborhood of v BitSet nv = graph.OpenNeighborhood(v) * (graph.Vertices - A); // We save the full set of neighborhood vertices at cut A. It does not matter that v was chosen arbitrarely; we always end up in the same collection of neighboring vertices for the set A Set<BitSet> un = new Set<BitSet>(); foreach (BitSet _base in _neighborhoods[A - v]) { un.Add(_base - v); // previous neighbor without v is a possible new neighborhood un.Add((_base - v) + nv); // previous neighbor without v, unioned with the neighborhood of v is a possible new neighborhood } // Save all entries _neighborhoods[A] = un; // List of all neighbors at cut A _cuts[A] = _neighborhoods[A].Count; // Dimension at this cut _width[A] = Math.Max(min, _cuts[A]); // Actual possible width to get to this cut }
/*************************/ // Trivial cases /*************************/ public static int TrivialCases(Datastructures.Graph graph, BitSet left, BitSet right) { int chosen = -1; // Check if any vertex in right belongs to one of the trivial cases, if yes then we can add this vertex directly to the sequence foreach (int v in right) { // Trivial case 1. If the neighbors of a vertex v in right are all contained in left, then select v // What this means is that v has an empty neighborhood, thus it will not add anything to the boolean-dimension if ((graph.OpenNeighborhood(v) - left).IsEmpty) { chosen = v; break; } bool stop = false; // 2. If there are two vertices, v in right and u in left, such that N(v) * right == (N(u)\v) * right, // then v is selected as our next vertex // What this means is that all neighbors of v are already 'represented' by u, thus making the choice for v will not add anything to the dimension foreach (int u in left) { BitSet nv = graph.OpenNeighborhood(v) * right; // N(v) * right BitSet nu = (graph.OpenNeighborhood(u) - v) * right; // (N(u)\v) * right if (nv.Equals(nu)) { chosen = v; stop = true; break; } } if (stop) break; } return chosen; }
private void executeForeach(Datastructures.Dag<ProgramRepresentation.DagElementData> dag, InterpretationState state) { int currentDagElementIndex; Datastructures.Dag<ProgramRepresentation.DagElementData>.Element currentDagElement; InterpretationState.ScopeLevel topScope; int dagIndexForIteratorScope; currentDagElementIndex = state.scopeLevels[state.scopeLevels.Count - 1].dagElementIndex; currentDagElement = dag.elements[currentDagElementIndex]; topScope = state.scopeLevels[state.currentScopeLevel]; if( topScope.foreachState == InterpretationState.ScopeLevel.EnumForeachState.INITIAL ) { // dag index for the array to iterate over or for a variable which holds the array int dagIndexForArgument; // check if number of parameters is two if( currentDagElement.childIndices.Count != 2 ) { throw new Exception("foreach: must take two arguments!"); } dagIndexForIteratorScope = currentDagElement.childIndices[0]; dagIndexForArgument = currentDagElement.childIndices[1]; // check if first parameter is a scope if( dag.elements[dagIndexForIteratorScope].content.type != DagElementData.EnumType.FSCOPE ) { throw new Exception("first parameter must be a scope!"); } // setup topScope.foreachResultArray = new List<Datastructures.Variadic>(); // check if second parameter is // * a array // * a scope // * a variable // TODO< if not, check if it is a scope, call the scope, check if it is a array > // < if it is a variable, retrive the variable and check if it is an array, if not, throw something if( dag.elements[dagIndexForArgument].content.type == DagElementData.EnumType.FARRAY ) { List<int> dagIndicesOfContentOfArray; // retrive and resolve array dagIndicesOfContentOfArray = dag.elements[dagIndexForArgument].childIndices; topScope.foreachArray = resolveVariablesAndConstants(dag, dagIndicesOfContentOfArray, state); topScope.foreachState = InterpretationState.ScopeLevel.EnumForeachState.ITERATENEXT; // no return } else if( dag.elements[dagIndexForArgument].content.type == DagElementData.EnumType.FSCOPE ) { InterpretationState.ScopeLevel createdScopeLevel; int dagIndexOfCalled; // it is a scope topScope.foreachState = InterpretationState.ScopeLevel.EnumForeachState.SCOPEFORARRAYWASINVOKED; // setup the scope createdScopeLevel = new InterpretationState.ScopeLevel(); state.scopeLevels.Add(createdScopeLevel); dagIndexOfCalled = dagIndexForArgument; createdScopeLevel.dagElementIndex = dagIndexOfCalled; // misc // do this so the next step executes the scope state.currentScopeLevel++; return; } else if( dag.elements[dagIndexForArgument].content.type == DagElementData.EnumType.IDENTIFIERNAME ) { // it is a variable System.Diagnostics.Debug.Assert(false, "TODO"); } else { throw new Exception("foreach: second parameter must be a array or a scope or a variable which holds an array!"); } } else if( topScope.foreachState == InterpretationState.ScopeLevel.EnumForeachState.SCOPEFORARRAYWASINVOKED ) { // scope for the array to iterate over was invoked // * check if result from scope is an array // * set array // * set state so it iterates over the array as usual if( topScope.calleeResult.type != Datastructures.Variadic.EnumType.ARRAY ) { throw new Exception("foreach result from scope for variable must be an array"); } topScope.foreachArray = topScope.calleeResult.valueArray; topScope.foreachState = InterpretationState.ScopeLevel.EnumForeachState.ITERATENEXT; // no return } // when w are here the state can either be // * ITERATENEXT // we need to try to fetch the next item and feed it into the scope // * ITERATESTORE // we need to retrive the result of the called scope and append it to the result array if( topScope.foreachState == InterpretationState.ScopeLevel.EnumForeachState.ITERATENEXT ) { Datastructures.Variadic currentIterationValue; InterpretationState.ScopeLevel createdScopeLevel; int dagIndexOfCalled; dagIndexForIteratorScope = currentDagElement.childIndices[0]; // * check if we are at the end of the array // if so -> return result array // * fetch value // * build scope // * set variable "element" // check if we are the end System.Diagnostics.Debug.Assert(topScope.foreachIndexInArray <= topScope.foreachArray.Count); if (topScope.foreachIndexInArray == topScope.foreachArray.Count) { Datastructures.Variadic resultValue; resultValue = new Datastructures.Variadic(Datastructures.Variadic.EnumType.ARRAY); resultValue.valueArray = topScope.foreachResultArray; returnResult(state, resultValue); // remove scope of call removeTopScope(state); return; } // fetch value currentIterationValue = topScope.foreachArray[topScope.foreachIndexInArray]; // build scope createdScopeLevel = new InterpretationState.ScopeLevel(); state.scopeLevels.Add(createdScopeLevel); dagIndexOfCalled = dagIndexForIteratorScope; createdScopeLevel.dagElementIndex = dagIndexOfCalled; // set variables createdScopeLevel.variables.Add(new InterpretationState.ScopeLevel.Variable()); createdScopeLevel.variables.Add(new InterpretationState.ScopeLevel.Variable()); createdScopeLevel.variables[0].name = "element"; createdScopeLevel.variables[0].value = currentIterationValue; createdScopeLevel.variables[1].name = "index"; createdScopeLevel.variables[1].value = new Datastructures.Variadic(Datastructures.Variadic.EnumType.INT); createdScopeLevel.variables[1].value.valueInt = topScope.foreachIndexInArray; // misc // do this so the next step executes the scope state.currentScopeLevel++; // misc topScope.foreachIndexInArray++; // state must be different topScope.foreachState = InterpretationState.ScopeLevel.EnumForeachState.ITERATESTORE; return; } else if( topScope.foreachState == InterpretationState.ScopeLevel.EnumForeachState.ITERATESTORE ) { topScope.foreachResultArray.Add(topScope.calleeResult.deepCopy()); topScope.foreachState = InterpretationState.ScopeLevel.EnumForeachState.ITERATENEXT; return; } else { throw new Exception("Internal Error!"); } System.Diagnostics.Debug.Assert(false); throw new Exception("unreachable"); }
private void executeInvoke(Datastructures.Dag<ProgramRepresentation.DagElementData> dag, InterpretationState state) { Datastructures.Variadic invokeResult; EnumInvokeDispatcherCallResult callResult; int currentDagElementIndex; Datastructures.Dag<ProgramRepresentation.DagElementData>.Element currentDagElement; InterpretationState.ScopeLevel topScope; currentDagElementIndex = state.scopeLevels[state.scopeLevels.Count-1].dagElementIndex; currentDagElement = dag.elements[currentDagElementIndex]; topScope = state.scopeLevels[state.currentScopeLevel]; if( topScope.invokeState == InterpretationState.ScopeLevel.EnumInvokeState.INITIAL ) { topScope.invokeState = InterpretationState.ScopeLevel.EnumInvokeState.RESOLVEPARAMETERS; topScope.invokeResolvedParameters = new List<Datastructures.Variadic>(); return; } else if( topScope.invokeState == InterpretationState.ScopeLevel.EnumInvokeState.RESOLVEPARAMETERS ) { int dagIndexOfArrayWithParameters; List<int> dagIndicesOfArrayContentForParameters; // retrieve and try to resolve remaining parameters dagIndexOfArrayWithParameters = currentDagElement.childIndices[1]; dagIndicesOfArrayContentForParameters = dag.elements[dagIndexOfArrayWithParameters].childIndices; for(;;) { int dagIndexOfParameter; // check if we are done with the resolving System.Diagnostics.Debug.Assert(topScope.invokeResolveParametersIndex <= dagIndicesOfArrayContentForParameters.Count); if( topScope.invokeResolveParametersIndex == dagIndicesOfArrayContentForParameters.Count ) { topScope.invokeState = InterpretationState.ScopeLevel.EnumInvokeState.INVOKE; return; } // check if the current parameter is a scope // if it is the case, we open the scope and transfer control // if its not the case we can try to resolve the parameter as usual and continue dagIndexOfParameter = dagIndicesOfArrayContentForParameters[topScope.invokeResolveParametersIndex]; if( dag.elements[dagIndexOfParameter].content.type == DagElementData.EnumType.FSCOPE ) { InterpretationState.ScopeLevel createdScopeLevel; topScope.invokeResolveParametersIndex++; topScope.invokeState = InterpretationState.ScopeLevel.EnumInvokeState.SCOPEFORPARAMETERWASINVOKED; // build new scope createdScopeLevel = new InterpretationState.ScopeLevel(); state.scopeLevels.Add(createdScopeLevel); createdScopeLevel.dagElementIndex = dagIndexOfParameter; // do this so the next step executes the scope state.currentScopeLevel++; return; } else { Datastructures.Variadic currentResolvedParameter; currentResolvedParameter = resolveVariableAndConstant(dag, dagIndexOfParameter, state); topScope.invokeResolvedParameters.Add(currentResolvedParameter); topScope.invokeResolveParametersIndex++; } } } else if( topScope.invokeState == InterpretationState.ScopeLevel.EnumInvokeState.SCOPEFORPARAMETERWASINVOKED ) { Datastructures.Variadic parameterFromScope; // the scope for an parameter was invoked and the result is on the stack // * get the result from the stack // * add it to the parameters // * go back in the state // NOTE< we just move the reference > parameterFromScope = topScope.calleeResult; topScope.invokeResolvedParameters.Add(parameterFromScope); topScope.invokeState = InterpretationState.ScopeLevel.EnumInvokeState.RESOLVEPARAMETERS; return; } else if( topScope.invokeState == InterpretationState.ScopeLevel.EnumInvokeState.INVOKE ) { int dagIndexOfArrayWithPath; List<int> dagIndicesOfArrayContentForPath; List<string> pathOfInvokedProgram; bool isInterpretableInvoke; int dagIndexOfInvokedScope; List<string> invokeVariableNames; // build the path of the invoked program dagIndexOfArrayWithPath = currentDagElement.childIndices[0]; if (dag.elements[dagIndexOfArrayWithPath].content.type != DagElementData.EnumType.FARRAY) { throw new Exception("Invoke parameter [0] was not an Array as expected!"); } // grab the indices of the array dagIndicesOfArrayContentForPath = dag.elements[dagIndexOfArrayWithPath].childIndices; // and put them into the function which executes building stuff for the path for the invoke pathOfInvokedProgram = getPathOfInvokeScopeInstruction(dag, dagIndicesOfArrayContentForPath, state); // try to lookup the path inside the list with all interpretable programs (which can be invoked) invokeVariableNames = new List<string>(); lookupInvokePath(state, pathOfInvokedProgram, out isInterpretableInvoke, out dagIndexOfInvokedScope, invokeVariableNames); if (isInterpretableInvoke) { InterpretationState.ScopeLevel createdScopeLevel; int variableI; // set state topScope.invokeState = InterpretationState.ScopeLevel.EnumInvokeState.PROGRAMINVOKED; // check if number of parameter is correct if (topScope.invokeResolvedParameters.Count != invokeVariableNames.Count) { throw new Exception("invoke parameter count is invalid!"); } // build new scope createdScopeLevel = new InterpretationState.ScopeLevel(); state.scopeLevels.Add(createdScopeLevel); createdScopeLevel.dagElementIndex = dagIndexOfInvokedScope; // set variables for (variableI = 0; variableI < invokeVariableNames.Count; variableI++) { InterpretationState.ScopeLevel.Variable createdVariable; createdVariable = new InterpretationState.ScopeLevel.Variable(); createdVariable.name = invokeVariableNames[variableI]; createdVariable.value = topScope.invokeResolvedParameters[variableI]; createdScopeLevel.variables.Add(createdVariable); } // do this so the next step executes the scope state.currentScopeLevel++; return; } else { // dispatch invoke invokeDispatcher.dispatchInvokeStart(pathOfInvokedProgram, topScope.invokeResolvedParameters, state.scopeLevels, out invokeResult, out callResult); // TODO< maybe logic for searching of callee > System.Diagnostics.Debug.Assert(state.currentScopeLevel > 0); // if we are done // return result to caller (in state stack) // if the call failed we return false if (callResult == EnumInvokeDispatcherCallResult.DONE) { state.scopeLevels[state.currentScopeLevel - 1].calleeResult = invokeResult; // remove scope of call state.scopeLevels.RemoveAt(state.scopeLevels.Count - 1); state.currentScopeLevel--; return; } else if (callResult == EnumInvokeDispatcherCallResult.PATHINVALID) { state.scopeLevels[state.currentScopeLevel - 1].calleeResult = new Datastructures.Variadic(Datastructures.Variadic.EnumType.BOOL); state.scopeLevels[state.currentScopeLevel - 1].calleeResult.valueBool = false; // remove scope of call state.scopeLevels.RemoveAt(state.scopeLevels.Count - 1); state.currentScopeLevel--; return; } else if (callResult == EnumInvokeDispatcherCallResult.SUCCEEDINGINTERNAL) { System.Diagnostics.Debug.Assert(false, "SUCCEEDINGINTERNAL not supported!"); throw new Exception("Internal Error!"); } return; } } else if( topScope.invokeState == InterpretationState.ScopeLevel.EnumInvokeState.PROGRAMINVOKED ) { // TODO< maybe logic for searching of callee > System.Diagnostics.Debug.Assert(state.currentScopeLevel > 0); state.scopeLevels[state.currentScopeLevel - 1].calleeResult = state.scopeLevels[state.currentScopeLevel].calleeResult; // remove scope of call state.scopeLevels.RemoveAt(state.scopeLevels.Count - 1); state.currentScopeLevel--; return; } else { throw new Exception("Internal Error!"); } throw new Exception("unreachable!"); }
public void interpreteStep(Datastructures.Dag<ProgramRepresentation.DagElementData> dag, InterpretationState state, out bool terminatorReached) { int currentDagElementIndex; Datastructures.Dag<ProgramRepresentation.DagElementData>.Element currentDagElement; currentDagElementIndex = state.scopeLevels[state.scopeLevels.Count-1].dagElementIndex; currentDagElement = dag.elements[currentDagElementIndex]; terminatorReached = isTopScopeATerminator(state); if( terminatorReached ) { return; } if( currentDagElement.content.type == DagElementData.EnumType.FSCOPE ) { if( currentDagElement.content.valueInt == (int)Parser.Functional.ScopeParseTreeElement.EnumType.INVOKE ) { executeInvoke(dag, state); } else if( currentDagElement.content.valueInt == (int)Parser.Functional.ScopeParseTreeElement.EnumType.FOLD ) { executeFold(dag, state); } else if( currentDagElement.content.valueInt == (int)Parser.Functional.ScopeParseTreeElement.EnumType.MATCH ) { executeMatch(dag, state); } else if( currentDagElement.content.valueInt == (int)Parser.Functional.ScopeParseTreeElement.EnumType.FOREACH ) { executeForeach(dag, state); } else if (currentDagElement.content.valueInt == (int)Parser.Functional.ScopeParseTreeElement.EnumType.PASS ) { executePass(dag, state); } else if( currentDagElement.content.valueInt == (int)Parser.Functional.ScopeParseTreeElement.EnumType.FSET ) { executeSetVariables(dag, state); } else if( currentDagElement.content.valueInt == (int)Parser.Functional.ScopeParseTreeElement.EnumType.ADD || currentDagElement.content.valueInt == (int)Parser.Functional.ScopeParseTreeElement.EnumType.SUB || currentDagElement.content.valueInt == (int)Parser.Functional.ScopeParseTreeElement.EnumType.MUL || currentDagElement.content.valueInt == (int)Parser.Functional.ScopeParseTreeElement.EnumType.DIV ) { executeSimpleMathOperation(dag, state, (Parser.Functional.ScopeParseTreeElement.EnumType)currentDagElement.content.valueInt); } else { throw new Exception("Internal Error!"); } return; } else if( currentDagElement.content.type == DagElementData.EnumType.CONSTINT || currentDagElement.content.type == DagElementData.EnumType.CONSTFLOAT || currentDagElement.content.type == DagElementData.EnumType.CONSTBOOL ) { returnValue(currentDagElement.content, state); return; } else if( currentDagElement.content.type == DagElementData.EnumType.FARRAY ) { executeReturnArray(dag, state); } else if( currentDagElement.content.type == DagElementData.EnumType.IDENTIFIERNAME ) { executeReturnVariable(dag, state); } else { throw new Exception("Tried to execute unexecutable instrution!"); } }
private void executeFold(Datastructures.Dag<ProgramRepresentation.DagElementData> dag, InterpretationState state) { int currentDagElementIndex; Datastructures.Dag<ProgramRepresentation.DagElementData>.Element currentDagElement; InterpretationState.ScopeLevel topScope; currentDagElementIndex = state.scopeLevels[state.scopeLevels.Count - 1].dagElementIndex; currentDagElement = dag.elements[currentDagElementIndex]; topScope = state.scopeLevels[state.currentScopeLevel]; if( topScope.foldState == InterpretationState.ScopeLevel.EnumFoldState.INITIAL ) { int dagIndexOfArrayWithValuesOrScope; DagElementData.EnumType arrayWithValuesOrScopeType; dagIndexOfArrayWithValuesOrScope = currentDagElement.childIndices[1]; arrayWithValuesOrScopeType = dag.elements[dagIndexOfArrayWithValuesOrScope].content.type; if (arrayWithValuesOrScopeType == DagElementData.EnumType.FARRAY) { List<int> dagIndicesOfVariablesOrConstantsOfArray; dagIndicesOfVariablesOrConstantsOfArray = dag.elements[dagIndexOfArrayWithValuesOrScope].childIndices; topScope.foldInputArray = resolveVariablesAndConstants(dag, dagIndicesOfVariablesOrConstantsOfArray, state); topScope.foldState = InterpretationState.ScopeLevel.EnumFoldState.SUCCEEDING; // not return } else if( arrayWithValuesOrScopeType == DagElementData.EnumType.FSCOPE ) { int dagIndexOfCalled; InterpretationState.ScopeLevel createdScopeLevel; topScope.foldState = InterpretationState.ScopeLevel.EnumFoldState.SCOPEFORARRAYINVOKED; // open scope ... createdScopeLevel = new InterpretationState.ScopeLevel(); state.scopeLevels.Add(createdScopeLevel); dagIndexOfCalled = dagIndexOfArrayWithValuesOrScope; createdScopeLevel.dagElementIndex = dagIndexOfCalled; // do this so the next step executes the scope state.currentScopeLevel++; return; } else { throw new Exception("Internal Error : Invalid not handable parameter for fold"); } } else if( topScope.foldState == InterpretationState.ScopeLevel.EnumFoldState.SCOPEFORARRAYINVOKED ) { // check if result is an array if( topScope.calleeResult.type != Datastructures.Variadic.EnumType.ARRAY ) { throw new Exception("fold second parameter is not an array!"); } // set array as working array topScope.foldInputArray = topScope.calleeResult.valueArray; topScope.foldState = InterpretationState.ScopeLevel.EnumFoldState.SUCCEEDING; // no return } System.Diagnostics.Debug.Assert(topScope.foldState == InterpretationState.ScopeLevel.EnumFoldState.SUCCEEDING); if (topScope.foldIterationIndex == -1) { // first iteration if (topScope.foldInputArray.Count == 0) { // no value in array, return false state.scopeLevels[state.currentScopeLevel - 1].calleeResult = new Datastructures.Variadic(Datastructures.Variadic.EnumType.BOOL); state.scopeLevels[state.currentScopeLevel - 1].calleeResult.valueBool = false; // remove scope of fold state.scopeLevels.RemoveAt(state.scopeLevels.Count - 1); return; } else if (topScope.foldInputArray.Count == 1) { // one value in array, return it Datastructures.Variadic result; result = topScope.foldInputArray[0]; returnResult(state, result); // remove scope of fold //BUG? state.scopeLevels.RemoveAt(state.scopeLevels.Count - 1); // TODO< investigate > removeTopScope(state); return; } else { Datastructures.Variadic firstValue; Datastructures.Variadic secondValue; int dagIndexOfCalled; InterpretationState.ScopeLevel createdScopeLevel; // two or more values in the array // * fetch values // * check if called is a dag-scope // * open scope and push the dag-scope for execution // * set variables // fetch values firstValue = topScope.foldInputArray[0]; secondValue = topScope.foldInputArray[1]; // check dagIndexOfCalled = currentDagElement.childIndices[0]; if (dag.elements[dagIndexOfCalled].content.type != DagElementData.EnumType.FSCOPE) { throw new Exception("fold: first parameter must be a scope!"); } // open scope ... createdScopeLevel = new InterpretationState.ScopeLevel(); state.scopeLevels.Add(createdScopeLevel); createdScopeLevel.dagElementIndex = dagIndexOfCalled; // (set variables) createdScopeLevel.variables.Add(new InterpretationState.ScopeLevel.Variable()); createdScopeLevel.variables.Add(new InterpretationState.ScopeLevel.Variable()); createdScopeLevel.variables.Add(new InterpretationState.ScopeLevel.Variable()); createdScopeLevel.variables[0].name = "accu"; createdScopeLevel.variables[0].value = firstValue; createdScopeLevel.variables[1].name = "other"; createdScopeLevel.variables[1].value = secondValue; createdScopeLevel.variables[2].name = "index"; createdScopeLevel.variables[2].value = new Datastructures.Variadic(Datastructures.Variadic.EnumType.INT); createdScopeLevel.variables[2].value.valueInt = 0; topScope.foldIterationIndex = 1; // do this so the next step executes the scope state.currentScopeLevel++; return; } } else { // following iterations // * check if array is walked // if not -> // * fetch value // * evaluate value // * open scope and push the dag-scope for execution // * set variables // if -> // * return accumulated value int valueArrayListLength; Datastructures.Variadic evaluatedValue; InterpretationState.ScopeLevel createdScopeLevel; int dagIndexOfCalled; valueArrayListLength = topScope.foldInputArray.Count; dagIndexOfCalled = currentDagElement.childIndices[0]; // check if array is walked System.Diagnostics.Debug.Assert(topScope.foldIterationIndex <= valueArrayListLength); if (topScope.foldIterationIndex == valueArrayListLength) { // it is walked // return the result returnResult(state, topScope.calleeResult); // remove scope of call removeTopScope(state); return; } // else we are here // fetch value // evaluate evaluatedValue = topScope.foldInputArray[topScope.foldIterationIndex]; // open scope and push the dag-scope for execution createdScopeLevel = new InterpretationState.ScopeLevel(); state.scopeLevels.Add(createdScopeLevel); createdScopeLevel.dagElementIndex = dagIndexOfCalled; // set variables createdScopeLevel.variables.Add(new InterpretationState.ScopeLevel.Variable()); createdScopeLevel.variables.Add(new InterpretationState.ScopeLevel.Variable()); createdScopeLevel.variables.Add(new InterpretationState.ScopeLevel.Variable()); createdScopeLevel.variables[0].name = "accu"; createdScopeLevel.variables[0].value = topScope.calleeResult; createdScopeLevel.variables[1].name = "other"; createdScopeLevel.variables[1].value = evaluatedValue; createdScopeLevel.variables[2].name = "index"; createdScopeLevel.variables[2].value = new Datastructures.Variadic(Datastructures.Variadic.EnumType.INT); createdScopeLevel.variables[2].value.valueInt = topScope.foldIterationIndex; // misc // increment the index for the next call topScope.foldIterationIndex++; // do this so the next step executes the scope state.currentScopeLevel++; return; } }
private static void returnResult(InterpretationState state, Datastructures.Variadic result) { System.Diagnostics.Debug.Assert(state.scopeLevels.Count >= 1); if (state.scopeLevels.Count == 1) { state.result = result; } else { state.scopeLevels[state.currentScopeLevel - 1].calleeResult = result; } }
private static void setVariableInScope( string variablename, EnumOverwriteExistingVariable overwriteExistingVariable, Datastructures.Variadic value, InterpretationState.ScopeLevel topScope ) { int foundVariableIndex; int i; foundVariableIndex = -1; for( i = 0; i < topScope.variables.Count; i++ ) { if( topScope.variables[i].name == variablename ) { foundVariableIndex = i; break; } } if( foundVariableIndex != -1 ) { if( overwriteExistingVariable == EnumOverwriteExistingVariable.NO ) { // variable allready existed, but can't be overwritten throw new Exception("variable " + variablename + " exists in scope but can't be overwritten!"); } topScope.variables[foundVariableIndex].value = value; } else { InterpretationState.ScopeLevel.Variable newVariable; newVariable = new InterpretationState.ScopeLevel.Variable(); newVariable.name = variablename; newVariable.value = value; topScope.variables.Add(newVariable); } }
public static Action <DialogueContext> RootWithPrompt(String Prompt) { return((Context) => { if (Context.Politics.WasAtWar) { Context.Say("We are at war."); Context.AddOption("Make peace", MakePeace); Context.AddOption("Continue the war", DeclareWar); } else { Context.Say(Prompt); Context.ClearOptions(); Context.AddOption("Trade", Trade); Context.AddOption("What is your opinion of us?", (context) => { var prompt = ""; if (context.Politics.RecentEvents.Count > 0) { prompt = String.Format("So far, our relationship has been {0}", context.Politics.GetCurrentRelationship()); if (context.Politics.RecentEvents.Count > 0) { prompt += ", because "; prompt += TextGenerator.GetListString( context.Politics.RecentEvents.Select(e => e.Description).ToList()); } prompt += "."; } else { prompt = "We know nothing about you."; } Context.Transition(RootWithPrompt(prompt)); }); Context.AddOption("What is something you have many of?", (context) => { Context.Transition(RootWithPrompt(String.Format("We have many {0}.", GetPluralForm(Datastructures.SelectRandom(context.Envoy.OwnerFaction.Race.CommonResources))))); }); Context.AddOption("What is something you have few of?", (context) => { if (context.Envoy.OwnerFaction.Race.RareResources.Count > 0) { Context.Transition(RootWithPrompt(String.Format("We have few {0}.", GetPluralForm(Datastructures.SelectRandom(context.Envoy.OwnerFaction.Race.RareResources))))); } else { Context.Transition(RootWithPrompt("Nothing in particular.")); } }); Context.AddOption("What is something you hate?", (context) => { if (context.Envoy.OwnerFaction.Race.HatedResources.Count > 0) { Context.Transition(RootWithPrompt(String.Format("We hate {0}.", GetPluralForm(Datastructures.SelectRandom(context.Envoy.OwnerFaction.Race.HatedResources))))); } else { Context.Transition(RootWithPrompt("We don't hate anything in particular.")); } }); Context.AddOption("What is something you like?", (context) => { if (context.Envoy.OwnerFaction.Race.LikedResources.Count > 0) { Context.Transition(RootWithPrompt(String.Format("We like {0}.", GetPluralForm(Datastructures.SelectRandom(context.Envoy.OwnerFaction.Race.LikedResources))))); } else { Context.Transition(RootWithPrompt("We don't like anything in particular.")); } }); Context.AddOption("Declare war", ConfirmDeclareWar); Context.AddOption("Leave", (context) => { Context.Say(Datastructures.SelectRandom(context.Envoy.OwnerFaction.Race.Speech.Farewells)); Context.ClearOptions(); Context.AddOption("Goodbye.", (_) => { Diplomacy.RecallEnvoy(context.Envoy); GameState.Game.StateManager.PopState(); }); }); } }); }
public override void OnAction(WorldManager world) { if (Resources.Count == 0) { LastEvent = String.Format("The trade party didn't have anything to trade, so they're coming home."); return; } var owner = world.Factions.Factions[OwnerFaction]; var dest = world.Factions.Factions[DestinationFaction]; var charisma = Party.Max(p => p.Stats.BuffedChar); float tradeGoodness = charisma - MathFunctions.Rand(0, 10.0f); var politics = world.Diplomacy.GetPolitics(owner, dest); List <ResourceAmount> destGoods = dest.Race.GenerateResources(world); List <ResourceAmount> tradeGoods = new List <ResourceAmount>(); bool wasBadTrade = false; int randIters = 100; for (int iter = 0; iter < randIters; iter++) { var resourceType = Datastructures.SelectRandom(Resources); if (resourceType.NumResources == 0) { continue; } var resource = ResourceLibrary.GetResourceByName(resourceType.ResourceType); bool liked = resource.Tags.Any(t => dest.Race.LikedResources.Contains(t)); bool hated = resource.Tags.Any(t => dest.Race.HatedResources.Contains(t)); if (tradeGoodness < 0 && liked) { LastEvent = String.Format("{0} gave the {1} {2}, which made them very angry!", Datastructures.SelectRandom(Party).Stats.FullName, dest.Race.Name, resourceType.ResourceType); string badTrade = "You gave us something we hate."; if (!politics.RecentEvents.Any(ev => ev.Description == badTrade)) { politics.RecentEvents.Add(new Diplomacy.PoliticalEvent() { Description = badTrade, Change = -5, Duration = new TimeSpan(4, 0, 0, 0), Time = world.Time.CurrentDate }); } wasBadTrade = true; break; } else if (tradeGoodness > 0 && liked) { string goodTrade = "You gave us something we like."; if (!politics.RecentEvents.Any(ev => ev.Description == goodTrade)) { politics.RecentEvents.Add(new Diplomacy.PoliticalEvent() { Description = goodTrade, Change = 5, Duration = new TimeSpan(4, 0, 0, 0), Time = world.Time.CurrentDate }); } } var resourceValue = GetValue(resource, dest); // Now find a resource of equal or greater value and trade for it. int randIter2 = 0; while (randIter2 < 100) { var randGood = Datastructures.SelectRandom(destGoods); if (randGood.NumResources == 0) { randIter2++; continue; } var good = ResourceLibrary.GetResourceByName(randGood.ResourceType); var randGoodValue = GetValue(good, dest); // Trade the most of this resource we possibly can. If we want to // trade an item of lesser value, try to trade 1 good for as much of it as possible. if (randGoodValue <= resourceValue) { int numToTrade = Math.Min((int)(resourceValue / randGoodValue), randGood.NumResources); if (numToTrade * randGoodValue >= 0.75f * resourceValue) { randGood.NumResources -= numToTrade; resourceType.NumResources--; tradeGoods.Add(new ResourceAmount(good, numToTrade)); break; } } // If we're trading upwards, try trading as much of our resource as possible for the valuable item. else { int numToTrade = Math.Min((int)(randGoodValue / resourceValue), resourceType.NumResources); if (numToTrade * resourceValue >= 0.75f * randGoodValue) { randGood.NumResources--; resourceType.NumResources -= numToTrade; tradeGoods.Add(new ResourceAmount(good, 1)); break; } } randIter2++; } // We failed to find a good of equal value, so let's just trade money. if (randIter2 == 100) { resourceType.NumResources--; Money += resourceValue; } } Resources.AddRange(tradeGoods); if (!wasBadTrade) { LastEvent = String.Format("The trade party is returning home with {0} goods, and {1}.", Resources.Sum(r => r.NumResources), Money); } base.OnAction(world); }
public override void OnEnter() { // Clear the input queue... cause other states aren't using it and it's been filling up. DwarfGame.GumInputMapper.GetInputQueue(); GuiRoot = new Gui.Root(DwarfGame.GuiSkin); GuiRoot.MousePointer = new Gui.MousePointer("mouse", 4, 0); Rectangle rect = GuiRoot.RenderData.VirtualScreen; rect.Inflate(-rect.Width / 3, -rect.Height / 3); var mainPanel = GuiRoot.RootItem.AddChild(new Gui.Widget { Rect = rect, MinimumSize = new Point(512, 256), AutoLayout = AutoLayout.FloatCenter, Border = "border-fancy", Padding = new Margin(4, 4, 4, 4), InteriorMargin = new Margin(2, 0, 0, 0), TextSize = 1, Font = "font10" }); mainPanel.AddChild(new Gui.Widgets.Button { Text = "Create!", Font = "font16", TextHorizontalAlign = HorizontalAlign.Center, TextVerticalAlign = VerticalAlign.Center, Border = "border-button", OnClick = (sender, args) => { // Grab string values from widgets! CompanyInformation.Name = NameField.Text; CompanyInformation.Motto = MottoField.Text; // Why are they stored as statics on this class??? StateManager.PushState(new NewGameChooseWorldState(Game, Game.StateManager)); }, AutoLayout = AutoLayout.FloatBottomRight }); mainPanel.AddChild(new Gui.Widgets.Button { Text = "< Back", TextHorizontalAlign = HorizontalAlign.Center, TextVerticalAlign = VerticalAlign.Center, Border = "border-button", Font = "font16", OnClick = (sender, args) => { StateManager.PopState(); }, AutoLayout = AutoLayout.FloatBottomLeft, }); #region Name mainPanel.AddChild(new Widget() { Text = "Create a Company", Font = "font16", AutoLayout = AutoLayout.DockTop, }); var nameRow = mainPanel.AddChild(new Widget { MinimumSize = new Point(0, 24), AutoLayout = AutoLayout.DockTop, Padding = new Margin(0, 0, 2, 2) }); nameRow.AddChild(new Gui.Widget { MinimumSize = new Point(64, 0), Text = "Name", AutoLayout = AutoLayout.DockLeft, TextHorizontalAlign = HorizontalAlign.Right, TextVerticalAlign = VerticalAlign.Center }); nameRow.AddChild(new Gui.Widgets.Button { Text = "Randomize", AutoLayout = AutoLayout.DockRight, Border = "border-button", OnClick = (sender, args) => { var templates = TextGenerator.GetAtoms(ContentPaths.Text.Templates.company_exploration); NameField.Text = TextGenerator.GenerateRandom(Datastructures.SelectRandom(templates).ToArray()); } }); NameField = nameRow.AddChild(new EditableTextField { Text = CompanyInformation.Name, AutoLayout = AutoLayout.DockFill }) as EditableTextField; #endregion #region Motto var mottoRow = mainPanel.AddChild(new Widget { MinimumSize = new Point(0, 24), AutoLayout = AutoLayout.DockTop, Padding = new Margin(0, 0, 2, 2) }); mottoRow.AddChild(new Widget { MinimumSize = new Point(64, 0), Text = "Motto", AutoLayout = AutoLayout.DockLeft, TextHorizontalAlign = HorizontalAlign.Right, TextVerticalAlign = VerticalAlign.Center }); mottoRow.AddChild(new Button { Text = "Randomize", AutoLayout = AutoLayout.DockRight, Border = "border-button", OnClick = (sender, args) => { var templates = TextGenerator.GetAtoms(ContentPaths.Text.Templates.mottos); MottoField.Text = TextGenerator.GenerateRandom(Datastructures.SelectRandom(templates).ToArray()); // Todo: Doesn't automatically invalidate when text changed?? MottoField.Invalidate(); } }); MottoField = mottoRow.AddChild(new EditableTextField { Text = CompanyInformation.Motto, AutoLayout = AutoLayout.DockFill }) as EditableTextField; #endregion #region Logo var logoRow = mainPanel.AddChild(new Widget { MinimumSize = new Point(0, 64), AutoLayout = AutoLayout.DockTop, Padding = new Margin(0, 0, 2, 2) }); CompanyLogoDisplay = logoRow.AddChild(new Gui.Widgets.CompanyLogo { AutoLayout = AutoLayout.DockLeft, MinimumSize = new Point(64, 64), MaximumSize = new Point(64, 64), CompanyInformation = CompanyInformation }) as Gui.Widgets.CompanyLogo; logoRow.AddChild(new Widget { Text = "BG:", AutoLayout = AutoLayout.DockLeft }); logoRow.AddChild(new Widget { Background = CompanyInformation.LogoBackground, MinimumSize = new Point(32, 32), MaximumSize = new Point(32, 32), AutoLayout = AutoLayout.DockLeft, OnClick = (sender, args) => { var source = GuiRoot.GetTileSheet("company-logo-background") as Gui.TileSheet; var chooser = new Gui.Widgets.GridChooser { ItemSource = Enumerable.Range(0, source.Columns * source.Rows) .Select(i => new Widget { Background = new TileReference("company-logo-background", i) }), OnClose = (s2) => { var gc = s2 as Gui.Widgets.GridChooser; if (gc.DialogResult == Gui.Widgets.GridChooser.Result.OKAY && gc.SelectedItem != null) { sender.Background = gc.SelectedItem.Background; sender.Invalidate(); CompanyInformation.LogoBackground = gc.SelectedItem.Background; CompanyLogoDisplay.Invalidate(); } }, PopupDestructionType = PopupDestructionType.DestroyOnOffClick }; GuiRoot.ShowModalPopup(chooser); } }); logoRow.AddChild(new Widget { Background = new TileReference("basic", 1), BackgroundColor = CompanyInformation.LogoBackgroundColor, MinimumSize = new Point(32, 32), MaximumSize = new Point(32, 32), AutoLayout = AutoLayout.DockLeft, OnClick = (sender, args) => { var chooser = new Gui.Widgets.GridChooser { ItemSize = new Point(16, 16), ItemSpacing = new Point(4, 4), ItemSource = EnumerateDefaultColors() .Select(c => new Widget { Background = new TileReference("basic", 1), BackgroundColor = new Vector4(c.ToVector3(), 1), }), OnClose = (s2) => { var gc = s2 as Gui.Widgets.GridChooser; if (gc.DialogResult == Gui.Widgets.GridChooser.Result.OKAY && gc.SelectedItem != null) { sender.BackgroundColor = gc.SelectedItem.BackgroundColor; sender.Invalidate(); CompanyInformation.LogoBackgroundColor = gc.SelectedItem.BackgroundColor; CompanyLogoDisplay.Invalidate(); } }, PopupDestructionType = PopupDestructionType.DestroyOnOffClick }; GuiRoot.ShowModalPopup(chooser); } }); logoRow.AddChild(new Widget { Text = "FG:", AutoLayout = AutoLayout.DockLeft }); logoRow.AddChild(new Widget { Background = CompanyInformation.LogoSymbol, MinimumSize = new Point(32, 32), MaximumSize = new Point(32, 32), AutoLayout = AutoLayout.DockLeft, OnClick = (sender, args) => { var source = GuiRoot.GetTileSheet("company-logo-symbol") as Gui.TileSheet; var chooser = new Gui.Widgets.GridChooser { ItemSource = Enumerable.Range(0, source.Columns * source.Rows) .Select(i => new Widget { Background = new TileReference("company-logo-symbol", i) }), OnClose = (s2) => { var gc = s2 as Gui.Widgets.GridChooser; if (gc.DialogResult == Gui.Widgets.GridChooser.Result.OKAY && gc.SelectedItem != null) { sender.Background = gc.SelectedItem.Background; sender.Invalidate(); CompanyInformation.LogoSymbol = gc.SelectedItem.Background; CompanyLogoDisplay.Invalidate(); } }, PopupDestructionType = PopupDestructionType.DestroyOnOffClick }; GuiRoot.ShowModalPopup(chooser); } }); logoRow.AddChild(new Widget { Background = new TileReference("basic", 1), BackgroundColor = CompanyInformation.LogoSymbolColor, MinimumSize = new Point(32, 32), MaximumSize = new Point(32, 32), AutoLayout = AutoLayout.DockLeft, OnClick = (sender, args) => { var chooser = new Gui.Widgets.GridChooser { ItemSize = new Point(16, 16), ItemSpacing = new Point(4, 4), ItemSource = EnumerateDefaultColors() .Select(c => new Widget { Background = new TileReference("basic", 1), BackgroundColor = new Vector4(c.ToVector3(), 1), }), OnClose = (s2) => { var gc = s2 as Gui.Widgets.GridChooser; if (gc.DialogResult == Gui.Widgets.GridChooser.Result.OKAY && gc.SelectedItem != null) { sender.BackgroundColor = gc.SelectedItem.BackgroundColor; sender.Invalidate(); CompanyInformation.LogoSymbolColor = gc.SelectedItem.BackgroundColor; CompanyLogoDisplay.Invalidate(); } }, PopupDestructionType = PopupDestructionType.DestroyOnOffClick }; GuiRoot.ShowModalPopup(chooser); } }); #endregion GuiRoot.RootItem.Layout(); IsInitialized = true; base.OnEnter(); }
/** * * \result are the childIndices */ private static List<int> convertListOfTreeElementsToDagElements(Datastructures.Dag<DagElementData> dag, List<Functional.ParseTreeElement> list) { List<int> childIndices; childIndices = new List<int>(); foreach (Functional.ParseTreeElement iterationParseTreeElement in list) { int childrenDagIndex; convertRecursive(dag, iterationParseTreeElement, out childrenDagIndex); childIndices.Add(childrenDagIndex); } return childIndices; }
/** * * builds the path for a invoke scope command, executes eventually called functions etc * */ private static List<string> getPathOfInvokeScopeInstruction(Datastructures.Dag<ProgramRepresentation.DagElementData> dag, List<int> dagIndicesOfPathElements, InterpretationState state) { List<string> result; result = new List<string>(); foreach( int iterationDagIndex in dagIndicesOfPathElements ) { Datastructures.Dag<ProgramRepresentation.DagElementData>.Element iterationDagElement; iterationDagElement = dag.elements[iterationDagIndex]; if( iterationDagElement.content.type == DagElementData.EnumType.CONSTSTRING ) { result.Add(iterationDagElement.content.valueString); } else { // TODO< only strings are until now implemented // later we need to support any operations > throw new Exception("Internal Error"); } } return result; }
private static void executeReturnVariable(Datastructures.Dag<ProgramRepresentation.DagElementData> dag, InterpretationState state) { int currentDagElementIndex; Datastructures.Dag<ProgramRepresentation.DagElementData>.Element currentDagElement; InterpretationState.ScopeLevel topScope; bool variableWasResolved; Datastructures.Variadic resolvedVariable; currentDagElementIndex = state.scopeLevels[state.scopeLevels.Count - 1].dagElementIndex; currentDagElement = dag.elements[currentDagElementIndex]; topScope = state.scopeLevels[state.currentScopeLevel]; if( currentDagElement.content.type != DagElementData.EnumType.IDENTIFIERNAME ) { // type must be an identifier throw new Exception("Internal Error"); } // look the identifier up resolvedVariable = resolveVariable(currentDagElement.content.identifier, state, out variableWasResolved); if( !variableWasResolved ) { throw new Exception("Variable \"" + currentDagElement.content.identifier + "\" could not be resolved."); } // return variable returnResult(state, resolvedVariable); // remove scope of call removeTopScope(state); return; }
public override void Construct() { AutoSizeColumns = true; IsRootTray = true; ItemSource = new Gui.Widget[] { new HorizontalMenuTray.MenuItem { Text = "CHEAT MODE", }, new HorizontalMenuTray.MenuItem { Text = "DEBUG", ExpansionChild = new HorizontalMenuTray.Tray { ItemSize = new Point(200, 20), ItemSource = Debugger.EnumerateSwitches().Select(s => new HorizontalMenuTray.CheckboxMenuItem { Text = Debugger.GetNicelyFormattedName(s.Name), InitialState = s.State, SetCallback = s.Set }) } }, new HorizontalMenuTray.MenuItem { Text = "DEBUG SAVE", OnClick = (sender, args) => { // Turn off binary compressed saves and save a nice straight json save for debugging purposes. // Todo: Why isn't World managing this paused state itself? bool paused = Master.World.Paused; var previousSetting = DwarfGame.COMPRESSED_BINARY_SAVES; DwarfGame.COMPRESSED_BINARY_SAVES = false; Master.World.Save( String.Format("{0}_{1}_DEBUG", Overworld.Name, Master.World.GameID), (success, exception) => { Master.World.MakeAnnouncement(success ? "Debug save created.": "Debug save failed - " + exception.Message); DwarfGame.COMPRESSED_BINARY_SAVES = previousSetting; Master.World.Paused = paused; }); } }, new HorizontalMenuTray.MenuItem { Text = "BUILD", ExpansionChild = new HorizontalMenuTray.Tray { ItemSource = RoomLibrary.GetRoomTypes().Select(r => new HorizontalMenuTray.MenuItem { Text = r, OnClick = (sender, args) => ActivateGodTool("Build/" + r) }) } }, new HorizontalMenuTray.MenuItem { Text = "SPAWN", ExpansionChild = new HorizontalMenuTray.Tray { Columns = 5, ItemSource = EntityFactory.EnumerateEntityTypes().Where(s => !s.Contains("Resource") || !ResourceLibrary.GetResourceByName(s.Substring(0, s.Length - " Resource".Length)).Generated).OrderBy(s => s).Select(s => new HorizontalMenuTray.MenuItem { Text = s, OnClick = (sender, args) => ActivateGodTool("Spawn/" + s) }) } }, new HorizontalMenuTray.MenuItem { Text = "PLACE BLOCK", ExpansionChild = new HorizontalMenuTray.Tray { Columns = 3, ItemSource = VoxelLibrary.PrimitiveMap.Keys .Where(t => t.Name != "empty" && t.Name != "water") .OrderBy(s => s.Name) .Select(s => new HorizontalMenuTray.MenuItem { Text = s.Name, OnClick = (sender, args) => ActivateGodTool("Place/" + s.Name) }) } }, new HorizontalMenuTray.MenuItem { Text = "DELETE BLOCK", OnClick = (sender, args) => ActivateGodTool("Delete Block") }, new HorizontalMenuTray.MenuItem { Text = "KILL BLOCK", OnClick = (sender, args) => ActivateGodTool("Kill Block") }, new HorizontalMenuTray.MenuItem { Text = "PLACE GRASS", ExpansionChild = new HorizontalMenuTray.Tray { Columns = 3, ItemSource = GrassLibrary.TypeList .OrderBy(s => s.Name) .Select(s => new HorizontalMenuTray.MenuItem { Text = s.Name, OnClick = (sender, args) => ActivateGodTool("Grass/" + s.Name) }) } }, new HorizontalMenuTray.MenuItem { Text = "PLACE DECAL", ExpansionChild = new HorizontalMenuTray.Tray { Columns = 3, ItemSource = DecalLibrary.TypeList .OrderBy(s => s.Name) .Select(s => new HorizontalMenuTray.MenuItem { Text = s.Name, OnClick = (sender, args) => ActivateGodTool("Decal/" + s.Name) }) } }, new HorizontalMenuTray.MenuItem { Text = "PLACE RAIL", ExpansionChild = new HorizontalMenuTray.Tray { Columns = 1, ItemSource = new HorizontalMenuTray.MenuItem[] { new HorizontalMenuTray.MenuItem { Text = "RAW PIECES", ExpansionChild = new HorizontalMenuTray.Tray { Columns = 2, ItemSize = new Point(200, 20), ItemSource = Rail.RailLibrary.EnumeratePieces().Select(p => new HorizontalMenuTray.MenuItem { Text = p.Name, OnClick = (sender, args) => ActivateGodTool("Rail/" + p.Name) }) } }, new HorizontalMenuTray.MenuItem { Text = "USING PATTERNS", ExpansionChild = new HorizontalMenuTray.Tray { Columns = 1, ItemSource = Rail.RailLibrary.EnumeratePatterns().Select(p => new HorizontalMenuTray.MenuItem { Text = p.Name, OnClick = (sender, args) => { var railTool = Master.Tools[GameMaster.ToolMode.BuildRail] as Rail.BuildRailTool; railTool.Pattern = p; Master.ChangeTool(GameMaster.ToolMode.BuildRail); railTool.GodModeSwitch = true; } }) } }, new HorizontalMenuTray.MenuItem { Text = "PAINT", OnClick = (sender, args) => { var railTool = Master.Tools[GameMaster.ToolMode.PaintRail] as Rail.PaintRailTool; railTool.SelectedResources = new List <ResourceAmount>(new ResourceAmount[] { new ResourceAmount("Rail", 1) }); Master.ChangeTool(GameMaster.ToolMode.PaintRail); railTool.GodModeSwitch = true; } } } } }, new HorizontalMenuTray.MenuItem { Text = "KILL THINGS", OnClick = (sender, args) => ActivateGodTool("Kill Things") }, new HorizontalMenuTray.MenuItem { Text = "TRAILER", ExpansionChild = new HorizontalMenuTray.Tray { ItemSource = new List <HorizontalMenuTray.MenuItem>() { new HorizontalMenuTray.MenuItem { Text = "SPIN +", OnClick = (sender, args) => this.Master.World.Camera.Trailer(Vector3.Zero, 2.0f, 0.0f), }, new HorizontalMenuTray.MenuItem { Text = "SPIN -", OnClick = (sender, args) => this.Master.World.Camera.Trailer(Vector3.Zero, -2.0f, 0.0f), }, new HorizontalMenuTray.MenuItem { Text = "ZOOM -", OnClick = (sender, args) => this.Master.World.Camera.Trailer(Vector3.Zero, 0.0f, 2.5f), }, new HorizontalMenuTray.MenuItem { Text = "ZOOM +", OnClick = (sender, args) => this.Master.World.Camera.Trailer(Vector3.Zero, 0.0f, -2.5f), }, new HorizontalMenuTray.MenuItem { Text = "FWD", OnClick = (sender, args) => this.Master.World.Camera.Trailer(Vector3.Forward * 5, 0.0f, 0.0f), }, new HorizontalMenuTray.MenuItem { Text = "BACK", OnClick = (sender, args) => this.Master.World.Camera.Trailer(Vector3.Backward * 5, 0.0f, 0.0f), }, new HorizontalMenuTray.MenuItem { Text = "LEFT", OnClick = (sender, args) => this.Master.World.Camera.Trailer(Vector3.Left * 5, 0.0f, 0.0f), }, new HorizontalMenuTray.MenuItem { Text = "RIGHT", OnClick = (sender, args) => this.Master.World.Camera.Trailer(Vector3.Right * 5, 0.0f, 0.0f), }, } } }, new HorizontalMenuTray.MenuItem { Text = "FILL WATER", OnClick = (sender, args) => ActivateGodTool("Fill Water") }, new HorizontalMenuTray.MenuItem { Text = "FILL LAVA", OnClick = (sender, args) => ActivateGodTool("Fill Lava") }, new HorizontalMenuTray.MenuItem { Text = "TRADE ENVOY", ExpansionChild = new HorizontalMenuTray.Tray { ItemSource = Master.World.Factions.Factions.Values.Where(f => f.Race.IsIntelligent && f != Master.Faction).Select(s => { return(new HorizontalMenuTray.MenuItem { Text = s.Name, OnClick = (sender, args) => Master.World.Diplomacy.SendTradeEnvoy(s, Master.World) }); }), } }, new HorizontalMenuTray.MenuItem { Text = "EVENT", ExpansionChild = new HorizontalMenuTray.Tray { ItemSource = Master.World.GoalManager.EventScheduler.Events.Events.Select(e => { return(new HorizontalMenuTray.MenuItem { Text = e.Name, OnClick = (sender, args) => Master.World.GoalManager.EventScheduler.ActivateEvent(Master.World, e) }); }), } }, new HorizontalMenuTray.MenuItem { Text = "WAR PARTY", ExpansionChild = new HorizontalMenuTray.Tray { ItemSource = Master.World.Factions.Factions.Values.Where(f => f.Race.IsIntelligent && f != Master.Faction).Select(s => { return(new HorizontalMenuTray.MenuItem { Text = s.Name, OnClick = (sender, args) => Master.World.Diplomacy.SendWarParty(s) }); }), } }, new HorizontalMenuTray.MenuItem { Text = "DWARF BUX", OnClick = (sender, args) => Master.Faction.AddMoney(100m) }, new HorizontalMenuTray.MenuItem { Text = "MINIONS", ExpansionChild = new HorizontalMenuTray.Tray { ItemSource = new HorizontalMenuTray.MenuItem[] { new HorizontalMenuTray.MenuItem { Text = "PAY", OnClick = (sender, args) => Master.PayEmployees() }, new HorizontalMenuTray.MenuItem { Text = "STARVE", OnClick = (sender, args) => { foreach (var minion in Master.Faction.Minions) { minion.Status.Hunger.CurrentValue = 0; } } }, new HorizontalMenuTray.MenuItem { Text = "XP", OnClick = (sender, args) => { foreach (var minion in Master.Faction.Minions) { minion.AddXP(100); } } }, new HorizontalMenuTray.MenuItem { Text = "DISEASE", OnClick = (sender, args) => ActivateGodTool("Disease") }, new HorizontalMenuTray.MenuItem { Text = "HAPPY", OnClick = (sender, args) => { foreach (var minion in Master.Faction.Minions) { var thoughts = minion.GetRoot().GetComponent <DwarfThoughts>(); if (thoughts != null) { thoughts.AddThought(Thought.ThoughtType.CheatedHappy); } } } }, new HorizontalMenuTray.MenuItem { Text = "PISSED", OnClick = (sender, args) => { foreach (var minion in Master.Faction.Minions) { var thoughts = minion.GetRoot().GetComponent <DwarfThoughts>(); if (thoughts != null) { thoughts.AddThought(Thought.ThoughtType.CheatedPissed); } } } }, new HorizontalMenuTray.MenuItem { Text = "GAMBLE", OnClick = (sender, args) => { foreach (var employee in Master.Faction.Minions) { employee.AssignTask(new Scripting.GambleTask() { Priority = Task.PriorityType.High }); } } }, new HorizontalMenuTray.MenuItem { Text = "PASS OUT", OnClick = (sender, args) => { var employee = Datastructures.SelectRandom(Master.Faction.Minions); if (employee != null) { employee.Creature.Heal(-employee.Status.Health.CurrentValue * employee.Creature.MaxHealth + 1); } } } } } }, new HorizontalMenuTray.MenuItem { Text = "SPAWN TEST", OnClick = (sender, args) => { // Copy is required because spawning some types results in the creation of new types. EG, snakes create snake meat. var keys = EntityFactory.EnumerateEntityTypes().ToList(); int num = keys.Count(); float gridSize = (float)Math.Ceiling(Math.Sqrt((double)num)); Vector3 gridCenter = Master.World.CursorLightPos; int i = 0; for (float dx = -gridSize / 2; dx <= gridSize / 2; dx++) { for (float dz = -gridSize / 2; dz <= gridSize / 2; dz++) { if (i >= num) { continue; } Vector3 pos = MathFunctions.Clamp(gridCenter + new Vector3(dx, VoxelConstants.ChunkSizeY, dz), Master.World.ChunkManager.Bounds); VoxelHandle handle = VoxelHelpers.FindFirstVisibleVoxelOnRay(Master.World.ChunkManager.ChunkData, pos, pos + Vector3.Down * 100); if (handle.IsValid) { EntityFactory.CreateEntity <GameComponent>(keys[i], handle.WorldPosition + Vector3.Up); } i++; } } } }, new HorizontalMenuTray.MenuItem { Text = "SPAWN CRAFTS", OnClick = (sender, args) => { // Copy is required because spawning some types results in the creation of new types. EG, snakes create snake meat. var itemTypes = CraftLibrary.EnumerateCraftables().Where(craft => craft.Type == CraftItem.CraftType.Object).ToList(); int num = itemTypes.Count(); float gridSize = (float)Math.Ceiling(Math.Sqrt((double)num)); Vector3 gridCenter = Master.World.CursorLightPos; int i = 0; for (float dx = -gridSize / 2; dx <= gridSize / 2; dx++) { for (float dz = -gridSize / 2; dz <= gridSize / 2; dz++) { if (i < num) { var item = itemTypes[i]; if (item.Name != "Explosive") { Vector3 pos = MathFunctions.Clamp(gridCenter + new Vector3(dx, VoxelConstants.ChunkSizeY, dz), Master.World.ChunkManager.Bounds); VoxelHandle handle = VoxelHelpers.FindFirstVisibleVoxelOnRay(Master.World.ChunkManager.ChunkData, pos, pos + Vector3.Down * 100); if (handle.IsValid) { var blackboard = new Blackboard(); List <ResourceAmount> resources = item.RequiredResources.Select(r => new ResourceAmount(ResourceLibrary.GetResourcesByTag(r.ResourceType).First(), r.NumResources)).ToList(); blackboard.SetData <List <ResourceAmount> >("Resources", resources); blackboard.SetData <string>("CraftType", item.Name); var entity = EntityFactory.CreateEntity <GameComponent>(item.EntityName, handle.WorldPosition + Vector3.Up + item.SpawnOffset, blackboard); if (entity != null) { if (item.AddToOwnedPool) { Master.Faction.OwnedObjects.Add(entity as Body); } if (item.Moveable) { entity.Tags.Add("Moveable"); } if (item.Deconstructable) { entity.Tags.Add("Deconstructable"); } } } } } i++; } } } }, new HorizontalMenuTray.MenuItem { Text = "+1 HOUR", OnClick = (sender, args) => { Master.World.Time.CurrentDate += new TimeSpan(1, 0, 0); } }, new HorizontalMenuTray.MenuItem { Text = "FORCE REBUILD", OnClick = (sender, args) => { foreach (var chunk in Master.World.ChunkManager.ChunkData.ChunkMap) { for (int Y = 0; Y < VoxelConstants.ChunkSizeY; ++Y) { chunk.InvalidateSlice(Y); } } } }, new HorizontalMenuTray.MenuItem { Text = "REPULSE", OnClick = (sender, args) => ActivateGodTool("Repulse") }, new HorizontalMenuTray.MenuItem { Text = "SLOWMO", OnClick = (sender, args) => GameSettings.Default.EnableSlowMotion = !GameSettings.Default.EnableSlowMotion }, new HorizontalMenuTray.MenuItem { Text = "LET IT SNOW", OnClick = (sender, args) => { var storm = Weather.CreateStorm(Vector3.One, 100.0f, Master.World); storm.TypeofStorm = StormType.SnowStorm; storm.Start(); } } }; base.Construct(); }
public override void OnAction(WorldManager world) { var owner = world.Factions.Factions[OwnerFaction]; var dest = world.Factions.Factions[DestinationFaction]; var strength = Party.Sum(p => p.Stats.BuffedStr); var politics = world.Diplomacy.GetPolitics(owner, dest); List <ResourceAmount> destGoods = dest.Race.GenerateResources(world); int turns = MathFunctions.RandInt(1, (int)strength); List <ResourceAmount> stolenGoods = new List <ResourceAmount>(); DwarfBux stolenMoney = 0.0m; int numDead = 0; for (int turn = 0; turn < turns; turn++) { numDead += Party.Count(p => p.Creature.Hp <= 0); Party.RemoveAll(p => p.Creature.Hp <= 0); if (Party.Count == 0) { break; } var randomCritter = Datastructures.SelectRandom(Party); var con = randomCritter.Stats.BuffedCon; var enemyAttack = MathFunctions.RandInt(1, 20); if (enemyAttack - con > 10 || enemyAttack == 20) { randomCritter.Creature.Hp -= MathFunctions.RandInt(5, 100); if (randomCritter.Creature.Hp <= 0) { randomCritter.GetRoot().Delete(); } var thoughts = randomCritter.Creature.GetComponent <DwarfThoughts>(); if (thoughts != null) { thoughts.AddThought(Thought.ThoughtType.TookDamage); } } else { stolenGoods.Add(new ResourceAmount(Datastructures.SelectRandom(destGoods).ResourceType, MathFunctions.RandInt(1, 5))); stolenMoney += (DwarfBux)(decimal)MathFunctions.RandInt(1, 100); } } politics.RecentEvents.Add(new Diplomacy.PoliticalEvent() { Change = -5, Description = "You attacked us!", Duration = new TimeSpan(5, 0, 0, 0, 0), Time = world.Time.CurrentDate }); politics.WasAtWar = true; politics.HasMet = true; if (Party.Count == 0) { LastEvent = "All of the raiding party members died!"; Resources.Clear(); Money = 0.0m; AdventureState = State.Done; return; } Resources.AddRange(stolenGoods); Money += stolenMoney; if (numDead == 0) { LastEvent = String.Format("The raiding party is returning home unscathed! They stole {0} goods and {1}.", stolenGoods.Sum(g => g.NumResources), stolenMoney); AdventureState = State.ComingBack; } else { LastEvent = String.Format("The raiding party is returning home. They stole {0} goods and {1}, but {2} member(s) died.", stolenGoods.Sum(g => g.NumResources), stolenMoney, numDead); AdventureState = State.ComingBack; } foreach (var creature in Party) { var thoughts = creature.Creature.GetComponent <DwarfThoughts>(); if (thoughts != null) { thoughts.AddThought(Thought.ThoughtType.KilledThing); } } base.OnAction(world); }
private static List<Datastructures.Variadic> resolveVariablesAndConstants(Datastructures.Dag<ProgramRepresentation.DagElementData> dag, List<int> dagIndicesOfVariablesOrConstants, InterpretationState state) { List<Datastructures.Variadic> result; result = new List<Datastructures.Variadic>(); foreach( int iterationDagIndexOfVariableOrConstant in dagIndicesOfVariablesOrConstants ) { result.Add(resolveVariableAndConstant(dag, iterationDagIndexOfVariableOrConstant, state)); } return result; }
private static bool isConstantOrVariable(Datastructures.Dag<ProgramRepresentation.DagElementData> dag, int dagIndex) { Datastructures.Dag<ProgramRepresentation.DagElementData>.Element dagElement; dagElement = dag.elements[dagIndex]; return dagElement.content.type == DagElementData.EnumType.IDENTIFIERNAME || dagElement.content.type == DagElementData.EnumType.CONSTSTRING || dagElement.content.type == DagElementData.EnumType.CONSTINT || dagElement.content.type == DagElementData.EnumType.CONSTFLOAT; }
public static void ProcessTrade(DialogueContext Context) { if (Context.TradePanel.Result == Gui.Widgets.TradeDialogResult.Propose) { var containsHatedItem = Context.TradePanel.Transaction.PlayerItems .Select(item => ResourceLibrary.GetResourceByName(item.ResourceType)) .SelectMany(item => item.Tags) .Any(tag => Context.Envoy.OwnerFaction.Race.HatedResources.Contains(tag)); var containsLikedItem = Context.TradePanel.Transaction.PlayerItems .Select(item => ResourceLibrary.GetResourceByName(item.ResourceType)) .SelectMany(item => item.Tags) .Any(tag => Context.Envoy.OwnerFaction.Race.LikedResources.Contains(tag)); if (containsHatedItem) { Context.Envoy.OwnerFaction.Race.Speech.Language.SayBoo(); Context.NumOffensiveTrades++; var phrase = Datastructures.SelectRandom(Context.Envoy.OwnerFaction.Race.Speech.OffensiveTrades); var action = Context.NumOffensiveTrades >= 3 ? GoodbyeWithPrompt(phrase) : RootWithPrompt(phrase); Context.Transition(action); if (!Context.Politics.HasEvent("you tried to give us something offensive")) { Context.Politics.RecentEvents.Add(new Diplomacy.PoliticalEvent() { Change = -0.25f, Description = "you tried to give us something offensive", Duration = new TimeSpan(4, 0, 0, 0), Time = Context.World.Time.CurrentDate }); } } else { if (containsLikedItem) { if (!Context.Politics.HasEvent("you gave us something we liked")) { Context.Politics.RecentEvents.Add(new Diplomacy.PoliticalEvent() { Change = 0.25f, Description = "you gave us something we liked", Duration = new TimeSpan(4, 0, 0, 0), Time = Context.World.Time.CurrentDate }); } } Context.TradePanel.Transaction.Apply(Context.World); Context.Transition(RootWithPrompt(Datastructures.SelectRandom(Context.Envoy.OwnerFaction.Race.Speech.GoodTrades))); Context.World.GoalManager.OnGameEvent(new Goals.Events.Trade { PlayerFaction = Context.PlayerFaction, PlayerGold = Context.TradePanel.Transaction.PlayerMoney, PlayerGoods = Context.TradePanel.Transaction.PlayerItems, OtherFaction = Context.Envoy.OwnerFaction, OtherGold = Context.TradePanel.Transaction.EnvoyMoney, OtherGoods = Context.TradePanel.Transaction.EnvoyItems }); if (!Context.Politics.HasEvent("we had profitable trade")) { Context.Politics.RecentEvents.Add(new Diplomacy.PoliticalEvent() { Change = 0.25f, Description = "we had profitable trade", Duration = new TimeSpan(2, 0, 0, 0), Time = Context.World.Time.CurrentDate }); } Context.Envoy.OwnerFaction.Race.Speech.Language.SayYay(); } } else if (Context.TradePanel.Result == Gui.Widgets.TradeDialogResult.RejectOffense || Context.TradePanel.Result == Gui.Widgets.TradeDialogResult.RejectProfit) { Context.Envoy.OwnerFaction.Race.Speech.Language.SayBoo(); Context.Transition(RootWithPrompt(Datastructures.SelectRandom(Context.Envoy.OwnerFaction.Race.Speech.BadTrades))); } else { Context.Transition(RootWithPrompt("Changed your mind?")); } }
public static void convertRecursive(Datastructures.Dag<DagElementData> dag, Functional.ParseTreeElement sourceTree, out int dagRootElementIndex) { DagElementData createdDagElementData; Datastructures.Dag<DagElementData>.Element createdDagElement; if( sourceTree.type == Functional.ParseTreeElement.EnumType.SCOPE ) { createdDagElementData = new DagElementData(); createdDagElementData.type = DagElementData.EnumType.FSCOPE; createdDagElementData.valueInt = (int)((Functional.ScopeParseTreeElement)sourceTree).scopeType; createdDagElement = new Datastructures.Dag<DagElementData>.Element(createdDagElementData); dag.addElement(createdDagElement); dagRootElementIndex = dag.elements.Count-1; // add all childrens to the dag createdDagElement.childIndices = convertListOfTreeElementsToDagElements(dag, sourceTree.childrens); return; } else if( sourceTree.type == Functional.ParseTreeElement.EnumType.NUMBER ) { Functional.NumberParseTreeElement numberParseTreeElement; numberParseTreeElement = (Functional.NumberParseTreeElement)sourceTree; if( numberParseTreeElement.numberType == Functional.NumberParseTreeElement.EnumNumberType.INTEGER ) { createdDagElementData = new DagElementData(); createdDagElementData.type = DagElementData.EnumType.CONSTINT; createdDagElementData.valueInt = numberParseTreeElement.valueInt; createdDagElement = new Datastructures.Dag<DagElementData>.Element(createdDagElementData); dag.addElement(createdDagElement); dagRootElementIndex = dag.elements.Count-1; return; } else if (numberParseTreeElement.numberType == Functional.NumberParseTreeElement.EnumNumberType.FLOAT) { createdDagElementData = new DagElementData(); createdDagElementData.type = DagElementData.EnumType.CONSTFLOAT; createdDagElementData.valueFloat = numberParseTreeElement.valueFloat; createdDagElement = new Datastructures.Dag<DagElementData>.Element(createdDagElementData); dag.addElement(createdDagElement); dagRootElementIndex = dag.elements.Count - 1; return; } else { System.Diagnostics.Debug.Assert(false, "Unhandled type!"); throw new Exception("Internal Error!"); } } else if( sourceTree.type == Functional.ParseTreeElement.EnumType.IDENTIFIER ) { Functional.IdentifierParseTreeElement identifierParseTreeElement; identifierParseTreeElement = (Functional.IdentifierParseTreeElement)sourceTree; createdDagElementData = new DagElementData(); createdDagElementData.type = DagElementData.EnumType.IDENTIFIERNAME; createdDagElementData.identifier = identifierParseTreeElement.identifier; createdDagElement = new Datastructures.Dag<DagElementData>.Element(createdDagElementData); dag.addElement(createdDagElement); dagRootElementIndex = dag.elements.Count-1; return; } else if( sourceTree.type == Functional.ParseTreeElement.EnumType.ARRAY ) { createdDagElementData = new DagElementData(); createdDagElementData.type = DagElementData.EnumType.FARRAY; createdDagElement = new Datastructures.Dag<DagElementData>.Element(createdDagElementData); dag.addElement(createdDagElement); dagRootElementIndex = dag.elements.Count - 1; // add all childrens to the dag createdDagElement.childIndices = convertListOfTreeElementsToDagElements(dag, sourceTree.childrens); return; } else if( sourceTree.type == Functional.ParseTreeElement.EnumType.STRING ) { Functional.StringParseTreeElement stringParseTreeElement; stringParseTreeElement = (Functional.StringParseTreeElement)sourceTree; createdDagElementData = new DagElementData(); createdDagElementData.type = DagElementData.EnumType.CONSTSTRING; createdDagElementData.valueString = stringParseTreeElement.content; createdDagElement = new Datastructures.Dag<DagElementData>.Element(createdDagElementData); dag.addElement(createdDagElement); dagRootElementIndex = dag.elements.Count - 1; return; } else if( sourceTree.type == Functional.ParseTreeElement.EnumType.BOOLEAN ) { Functional.BooleanParseTreeElement booleanParseTreeElement; booleanParseTreeElement = (Functional.BooleanParseTreeElement)sourceTree; createdDagElementData = new DagElementData(); createdDagElementData.type = DagElementData.EnumType.CONSTBOOL; createdDagElementData.valueBool = booleanParseTreeElement.booleanType == Functional.BooleanParseTreeElement.EnumBooleanType.TRUE; createdDagElement = new Datastructures.Dag<DagElementData>.Element(createdDagElementData); dag.addElement(createdDagElement); dagRootElementIndex = dag.elements.Count - 1; return; } throw new Exception("Unreachable Code"); }
/** * * checks if the Dag-Element type is the type or is convertable to it * * */ private static bool isDagElementTypeTheSameOrConvertableToType(Datastructures.Dag<ProgramRepresentation.DagElementData>.Element dagElement, Datastructures.Variadic.EnumType toType) { if( dagElement.content.type == DagElementData.EnumType.CONSTINT ) { if( toType == Datastructures.Variadic.EnumType.INT || toType == Datastructures.Variadic.EnumType.FLOAT ) { return true; } } else if( dagElement.content.type == DagElementData.EnumType.CONSTBOOL ) { if( toType == Datastructures.Variadic.EnumType.BOOL ) { return true; } // ASK< are numbers implicitly convertable ? > } // TODO< others > return false; }
public static bool Connected(Datastructures.Graph graph) { return Connected(graph, graph.Vertices); }
/** * * only resolves variables and gets the value of constants etc * doesn't execute any invokes/function calls * */ private static Datastructures.Variadic resolveVariableAndConstant(Datastructures.Dag<ProgramRepresentation.DagElementData> dag, int dagIndexOfVariablesOrConstant, InterpretationState state) { Datastructures.Dag<ProgramRepresentation.DagElementData>.Element dagElement; dagElement = dag.elements[dagIndexOfVariablesOrConstant]; if( dagElement.content.type == DagElementData.EnumType.IDENTIFIERNAME ) { bool wasResolved; Datastructures.Variadic resultVariable; // it is a identifier (variable or a placeholder) // try to search it and return the value resultVariable = resolveVariable(dagElement.content.identifier, state, out wasResolved); if( !wasResolved ) { throw new Exception("variable " + dagElement.content.identifier + " could not be resolved!"); } return resultVariable; } else if( dagElement.content.type == DagElementData.EnumType.CONSTSTRING ) { // TODO System.Diagnostics.Debug.Assert(false, "TODO"); return null; } else if( dagElement.content.type == DagElementData.EnumType.CONSTINT ) { Datastructures.Variadic resultVariadic; resultVariadic = new Datastructures.Variadic(Datastructures.Variadic.EnumType.INT); resultVariadic.valueInt = dagElement.content.valueInt; return resultVariadic; } else if( dagElement.content.type == DagElementData.EnumType.FARRAY ) { Datastructures.Variadic resultVariadic; resultVariadic = new Datastructures.Variadic(Datastructures.Variadic.EnumType.ARRAY); resultVariadic.valueArray = resolveVariablesAndConstants(dag, dagElement.childIndices, state); return resultVariadic; } // TODO< const float > else { System.Diagnostics.Debug.Assert(false, "TODO"); throw new Exception("internal error"); } }
public static List<BitSet> ConnectedComponents(Datastructures.Graph graph) { return ConnectedComponents(graph, graph.Vertices); }
public override void Construct() { AutoSizeColumns = true; IsRootTray = true; ItemSource = new Gui.Widget[] { new HorizontalMenuTray.MenuItem { Text = "DEBUG", ExpansionChild = new HorizontalMenuTray.Tray { ItemSize = new Point(200, 20), ItemSource = Debugger.EnumerateSwitches().Select(s => new HorizontalMenuTray.CheckboxMenuItem { Text = Debugger.GetNicelyFormattedName(s.Name), InitialState = s.State, SetCallback = s.Set }) } }, new HorizontalMenuTray.MenuItem { Text = "BUILD", ExpansionChild = new HorizontalMenuTray.Tray { ItemSource = Library.EnumerateZoneTypeNames().Select(r => new HorizontalMenuTray.MenuItem { Text = r, OnClick = (sender, args) => ActivateGodTool("Build/" + r) }) } }, new HorizontalMenuTray.MenuItem { Text = "SPAWN", ExpansionChild = new HorizontalMenuTray.Tray { Columns = 8, AutoSizeColumns = false, ItemSize = new Point(110, 28), ItemSource = EntityFactory.EnumerateEntityTypes() .Where(s => !s.Contains("Resource") || !Library.GetResourceType(s.Substring(0, s.Length - " Resource".Length)).Generated) .OrderBy(s => s).Select(s => new HorizontalMenuTray.MenuItem { Text = s, OnClick = (sender, args) => ActivateGodTool("Spawn/" + s), }) } }, new HorizontalMenuTray.MenuItem { Text = "PLACE BLOCK", ExpansionChild = new HorizontalMenuTray.Tray { Columns = 3, ItemSource = Library.EnumerateVoxelTypes() .Where(t => t.Name != "_empty" && t.Name != "water") .OrderBy(s => s.Name) .Select(s => new HorizontalMenuTray.MenuItem { Text = s.Name, OnClick = (sender, args) => ActivateGodTool("Place/" + s.Name) }) } }, new HorizontalMenuTray.MenuItem { Text = "DELETE BLOCK", OnClick = (sender, args) => ActivateGodTool("Delete Block") }, new HorizontalMenuTray.MenuItem { Text = "NUKE COLUMN", OnClick = (sender, args) => ActivateGodTool("Nuke Column") }, new HorizontalMenuTray.MenuItem { Text = "KILL BLOCK", OnClick = (sender, args) => ActivateGodTool("Kill Block") }, new HorizontalMenuTray.MenuItem { Text = "PLACE GRASS", ExpansionChild = new HorizontalMenuTray.Tray { Columns = 3, ItemSource = Library.EnumerateGrassTypes() .OrderBy(s => s.Name) .Select(s => new HorizontalMenuTray.MenuItem { Text = s.Name, OnClick = (sender, args) => ActivateGodTool("Grass/" + s.Name) }) } }, new HorizontalMenuTray.MenuItem { Text = "PLACE RAIL", ExpansionChild = new HorizontalMenuTray.Tray { Columns = 1, ItemSource = new HorizontalMenuTray.MenuItem[] { new HorizontalMenuTray.MenuItem { Text = "RAW PIECES", ExpansionChild = new HorizontalMenuTray.Tray { Columns = 2, ItemSize = new Point(200, 20), ItemSource = Library.EnumerateRailPieces().Select(p => new HorizontalMenuTray.MenuItem { Text = p.Name, OnClick = (sender, args) => ActivateGodTool("Rail/" + p.Name) }) } }, new HorizontalMenuTray.MenuItem { Text = "USING PATTERNS", ExpansionChild = new HorizontalMenuTray.Tray { Columns = 1, ItemSource = Library.EnumerateRailPatterns().Select(p => new HorizontalMenuTray.MenuItem { Text = p.Name, OnClick = (sender, args) => { var railTool = World.UserInterface.Tools["BuildRail"] as Rail.BuildRailTool; railTool.Pattern = p; World.UserInterface.ChangeTool("BuildRail"); railTool.GodModeSwitch = true; } }) } }, new HorizontalMenuTray.MenuItem { Text = "PAINT", OnClick = (sender, args) => { var railTool = World.UserInterface.Tools["PaintRail"] as Rail.PaintRailTool; railTool.SelectedResources = new List <ResourceAmount>(new ResourceAmount[] { new ResourceAmount("Rail", 1) }); World.UserInterface.ChangeTool("PaintRail"); railTool.GodModeSwitch = true; } } } } }, new HorizontalMenuTray.MenuItem { Text = "AUTO SAVE", OnClick = (sender, args) => { World.UserInterface.AutoSave(); } }, new HorizontalMenuTray.MenuItem { Text = "KILL THINGS", OnClick = (sender, args) => ActivateGodTool("Kill Things") }, new HorizontalMenuTray.MenuItem { Text = "TRAILER", ExpansionChild = new HorizontalMenuTray.Tray { ItemSource = new List <HorizontalMenuTray.MenuItem>() { new HorizontalMenuTray.MenuItem { Text = "SPIN +", OnClick = (sender, args) => World.Renderer.Camera.Trailer(Vector3.Zero, 2.0f, 0.0f), }, new HorizontalMenuTray.MenuItem { Text = "SPIN -", OnClick = (sender, args) => World.Renderer.Camera.Trailer(Vector3.Zero, -2.0f, 0.0f), }, new HorizontalMenuTray.MenuItem { Text = "ZOOM -", OnClick = (sender, args) => World.Renderer.Camera.Trailer(Vector3.Zero, 0.0f, 2.5f), }, new HorizontalMenuTray.MenuItem { Text = "ZOOM +", OnClick = (sender, args) => World.Renderer.Camera.Trailer(Vector3.Zero, 0.0f, -2.5f), }, new HorizontalMenuTray.MenuItem { Text = "FWD", OnClick = (sender, args) => World.Renderer.Camera.Trailer(Vector3.Forward * 5, 0.0f, 0.0f), }, new HorizontalMenuTray.MenuItem { Text = "BACK", OnClick = (sender, args) => World.Renderer.Camera.Trailer(Vector3.Backward * 5, 0.0f, 0.0f), }, new HorizontalMenuTray.MenuItem { Text = "LEFT", OnClick = (sender, args) => World.Renderer.Camera.Trailer(Vector3.Left * 5, 0.0f, 0.0f), }, new HorizontalMenuTray.MenuItem { Text = "RIGHT", OnClick = (sender, args) => World.Renderer.Camera.Trailer(Vector3.Right * 5, 0.0f, 0.0f), }, } } }, new HorizontalMenuTray.MenuItem { Text = "FILL WATER", OnClick = (sender, args) => ActivateGodTool("Fill Water") }, new HorizontalMenuTray.MenuItem { Text = "FILL LAVA", OnClick = (sender, args) => ActivateGodTool("Fill Lava") }, new HorizontalMenuTray.MenuItem { Text = "TRADE ENVOY", ExpansionChild = new HorizontalMenuTray.Tray { ItemSource = World.Factions.Factions.Values.Where(f => f.Race.IsIntelligent && f != World.PlayerFaction).Select(s => { return(new HorizontalMenuTray.MenuItem { Text = s.ParentFaction.Name, OnClick = (sender, args) => s.SendTradeEnvoy() }); }), } }, new HorizontalMenuTray.MenuItem { Text = "EVENT", ExpansionChild = new HorizontalMenuTray.Tray { ItemSource = Events.Library.Enumerate().Select(e => { return(new HorizontalMenuTray.MenuItem { Text = e.Name, OnClick = (sender, args) => World.EventScheduler.ActivateEvent(World, e) }); }), } }, new HorizontalMenuTray.MenuItem { Text = "WAR PARTY", ExpansionChild = new HorizontalMenuTray.Tray { ItemSource = World.Factions.Factions.Values.Where(f => f.Race.IsIntelligent && f != World.PlayerFaction).Select(s => { return(new HorizontalMenuTray.MenuItem { Text = s.ParentFaction.Name, OnClick = (sender, args) => s.SendWarParty() }); }), } }, new HorizontalMenuTray.MenuItem { Text = "DWARF BUX", OnClick = (sender, args) => World.PlayerFaction.AddMoney(100m) }, new HorizontalMenuTray.MenuItem { Text = "MINIONS", ExpansionChild = new HorizontalMenuTray.Tray { ItemSource = new HorizontalMenuTray.MenuItem[] { new HorizontalMenuTray.MenuItem { Text = "PAY", OnClick = (sender, args) => World.PayEmployees() }, new HorizontalMenuTray.MenuItem { Text = "STARVE", OnClick = (sender, args) => { foreach (var minion in World.PlayerFaction.Minions) { minion.Stats.Hunger.CurrentValue = 0; } } }, new HorizontalMenuTray.MenuItem { Text = "XP", OnClick = (sender, args) => { foreach (var minion in World.PlayerFaction.Minions) { minion.AddXP(100); } } }, new HorizontalMenuTray.MenuItem { Text = "DISEASE", OnClick = (sender, args) => ActivateGodTool("Disease") }, new HorizontalMenuTray.MenuItem { Text = "HAPPY", OnClick = (sender, args) => { foreach (var minion in World.PlayerFaction.Minions) { minion.Creature.AddThought("You used the god menu to make me happy.", new TimeSpan(0, 8, 0, 0), 100.0f); } } }, new HorizontalMenuTray.MenuItem { Text = "PISSED", OnClick = (sender, args) => { foreach (var minion in World.PlayerFaction.Minions) { minion.Creature.AddThought("You used the god menu to piss me off.", new TimeSpan(0, 8, 0, 0), -100.0f); } } }, new HorizontalMenuTray.MenuItem { Text = "GAMBLE", OnClick = (sender, args) => { foreach (var employee in World.PlayerFaction.Minions) { employee.Stats.Boredom.CurrentValue = employee.Stats.Boredom.MinValue; employee.AddMoney(100); employee.AssignTask(new Scripting.GambleTask() { Priority = TaskPriority.High }); } } }, new HorizontalMenuTray.MenuItem { Text = "PASS OUT", OnClick = (sender, args) => { var employee = Datastructures.SelectRandom(World.PlayerFaction.Minions); if (employee != null) { employee.Creature.Heal(-employee.Stats.Health.CurrentValue * employee.Creature.MaxHealth + 1); } } } } } }, new HorizontalMenuTray.MenuItem { Text = "SPAWN TEST", OnClick = (sender, args) => { // Copy is required because spawning some types results in the creation of new types. EG, snakes create snake meat. var keys = EntityFactory.EnumerateEntityTypes().ToList(); int num = keys.Count(); float gridSize = (float)Math.Ceiling(Math.Sqrt((double)num)); Vector3 gridCenter = World.Renderer.CursorLightPos; int i = 0; for (float dx = -gridSize / 2; dx <= gridSize / 2; dx++) { for (float dz = -gridSize / 2; dz <= gridSize / 2; dz++) { if (i >= num) { continue; } Vector3 pos = MathFunctions.Clamp(gridCenter + new Vector3(dx, World.WorldSizeInVoxels.Y, dz), World.ChunkManager.Bounds); VoxelHandle handle = VoxelHelpers.FindFirstVisibleVoxelOnRay(World.ChunkManager, pos, pos + Vector3.Down * 100); if (handle.IsValid) { EntityFactory.CreateEntity <GameComponent>(keys[i], handle.WorldPosition + Vector3.Up); } i++; } } } }, new HorizontalMenuTray.MenuItem { Text = "SPAWN CRAFTS", OnClick = (sender, args) => { // Copy is required because spawning some types results in the creation of new types. EG, snakes create snake meat. var itemTypes = Library.EnumerateCraftables().Where(craft => craft.Type == CraftItem.CraftType.Object).ToList(); int num = itemTypes.Count(); float gridSize = (float)Math.Ceiling(Math.Sqrt((double)num)); Vector3 gridCenter = World.Renderer.CursorLightPos; int i = 0; for (float dx = -gridSize / 2; dx <= gridSize / 2; dx++) { for (float dz = -gridSize / 2; dz <= gridSize / 2; dz++) { if (i < num) { var item = itemTypes[i]; if (item.Name != "Explosive") { Vector3 pos = MathFunctions.Clamp(gridCenter + new Vector3(dx, World.WorldSizeInVoxels.Y, dz), World.ChunkManager.Bounds); VoxelHandle handle = VoxelHelpers.FindFirstVisibleVoxelOnRay(World.ChunkManager, pos, pos + Vector3.Down * 100); if (handle.IsValid) { var blackboard = new Blackboard(); List <ResourceAmount> resources = item.RequiredResources.Select(r => new ResourceAmount(Library.EnumerateResourceTypesWithTag(r.Type).First(), r.Count)).ToList(); blackboard.SetData <List <ResourceAmount> >("Resources", resources); blackboard.SetData <string>("CraftType", item.Name); var entity = EntityFactory.CreateEntity <GameComponent>(item.EntityName, handle.WorldPosition + Vector3.Up + item.SpawnOffset, blackboard); if (entity != null) { if (item.AddToOwnedPool) { World.PlayerFaction.OwnedObjects.Add(entity as GameComponent); } if (item.Moveable) { entity.Tags.Add("Moveable"); } if (item.Deconstructable) { entity.Tags.Add("Deconstructable"); } } } } } i++; } } } }, new HorizontalMenuTray.MenuItem { Text = "+1 HOUR", OnClick = (sender, args) => { World.Time.CurrentDate += new TimeSpan(1, 0, 0); } }, new HorizontalMenuTray.MenuItem { Text = "FORCE REBUILD", OnClick = (sender, args) => { foreach (var chunk in World.ChunkManager.ChunkMap) { for (int Y = 0; Y < VoxelConstants.ChunkSizeY; ++Y) { chunk.InvalidateSlice(Y); } } } }, new HorizontalMenuTray.MenuItem { Text = "REPULSE", OnClick = (sender, args) => ActivateGodTool("Repulse") }, new HorizontalMenuTray.MenuItem { Text = "SLOWMO", OnClick = (sender, args) => GameSettings.Default.EnableSlowMotion = !GameSettings.Default.EnableSlowMotion }, new HorizontalMenuTray.MenuItem { Text = "LET IT SNOW", OnClick = (sender, args) => { var storm = Weather.CreateStorm(Vector3.One, 100.0f, World); storm.TypeofStorm = StormType.SnowStorm; storm.Start(); } } }; base.Construct(); }
public override void OnEnter() { // Clear the input queue... cause other states aren't using it and it's been filling up. DwarfGame.GumInputMapper.GetInputQueue(); GuiRoot = new Gui.Root(DwarfGame.GumSkin); GuiRoot.MousePointer = new Gui.MousePointer("mouse", 4, 0); GuiRoot.RootItem.Font = "font8"; int w = System.Math.Min(GuiRoot.RenderData.VirtualScreen.Width - 256, 550); int h = System.Math.Min(GuiRoot.RenderData.VirtualScreen.Height - 256, 300); int x = GuiRoot.RenderData.VirtualScreen.Width / 2 - w / 2; int y = System.Math.Max(GuiRoot.RenderData.VirtualScreen.Height / 2 - h / 2, 280); int bgx = x - 258; int bgy = y - 128; DialogueContext.SpeechBubble = GuiRoot.RootItem.AddChild(new Gui.Widget { Rect = new Rectangle(bgx + 258, bgy, w + 50, 128), Border = "speech-bubble-reverse", Font = "font16", TextColor = Color.Black.ToVector4() }); var bg = GuiRoot.RootItem.AddChild(new Widget() { Border = "border-dark", Rect = new Rectangle(bgx, bgy, 258, 258) }); DialogueContext.ChoicePanel = GuiRoot.RootItem.AddChild(new Gui.Widget { Rect = new Rectangle(x, y, w, h), Border = "border-fancy", AutoLayout = AutoLayout.DockFill }); SpeakerAnimation = AnimationLibrary.CreateAnimation(DialogueContext.Envoy.OwnerFaction.Race.TalkAnimation); SpeakerAnimationPlayer = new AnimationPlayer(SpeakerAnimation); DialogueContext.SpeakerAnimation = SpeakerAnimationPlayer; SpeakerWidget = bg.AddChild(new Widget() { Background = new TileReference(SpeakerAnimation.SpriteSheet.AssetName, 0), AutoLayout = AutoLayout.DockFill, MinimumSize = new Point(256, 256), Rect = new Rectangle(bgx, bgy - 5, 256, 256) }); DialogueContext.Politics = World.Diplomacy.GetPolitics( DialogueContext.PlayerFaction, DialogueContext.Envoy.OwnerFaction); DialogueContext.World = World; if (!DialogueContext.Politics.HasMet) { DialogueContext.Politics.HasMet = true; DialogueContext.Politics.RecentEvents.Add(new Diplomacy.PoliticalEvent() { Change = 0.0f, Description = "we just met", Duration = new TimeSpan(1, 0, 0, 0), Time = World.Time.CurrentDate }); } DialogueContext.EnvoyName = TextGenerator.GenerateRandom(Datastructures.SelectRandom(DialogueContext.Envoy.OwnerFaction.Race.NameTemplates).ToArray()); DialogueContext.Transition(DialogueTree.ConversationRoot); IsInitialized = true; base.OnEnter(); }
public override void Construct() { Padding = new Margin(2, 2, 0, 0); AddChild(new Gui.Widget { Text = "Randomize", Border = "border-button", ChangeColorOnHover = true, TextColor = new Vector4(0, 0, 0, 1), Font = "font16", AutoLayout = Gui.AutoLayout.DockTop, OnClick = (sender, args) => { DwarfGame.LogSentryBreadcrumb("WorldGenerator", "User is regenerating the world."); Settings.Seed = MathFunctions.RandInt(Int32.MinValue, Int32.MaxValue); Settings.Name = Overworld.GetRandomWorldName(); RestartGeneration(); } }); AddChild(new Gui.Widget { Text = "Save World", Border = "border-button", ChangeColorOnHover = true, TextColor = new Vector4(0, 0, 0, 1), Font = "font16", AutoLayout = Gui.AutoLayout.DockTop, OnClick = (sender, args) => { DwarfGame.LogSentryBreadcrumb("WorldGenerator", "User is saving the world."); if (Generator.CurrentState != OverworldGenerator.GenerationState.Finished) { Root.ShowTooltip(Root.MousePosition, "Generator is not finished."); } else { global::System.IO.DirectoryInfo worldDirectory = global::System.IO.Directory.CreateDirectory(DwarfGame.GetWorldDirectory() + global::System.IO.Path.DirectorySeparatorChar + Settings.Name); var file = new NewOverworldFile(Game.GraphicsDevice, Settings); file.WriteFile(worldDirectory.FullName); Root.ShowModalPopup(Root.ConstructWidget(new Gui.Widgets.Popup { Text = "File saved." })); } } }); AddChild(new Gui.Widget { Text = "Advanced", Border = "border-button", ChangeColorOnHover = true, TextColor = new Vector4(0, 0, 0, 1), Font = "font16", AutoLayout = Gui.AutoLayout.DockTop, OnClick = (sender, args) => { DwarfGame.LogSentryBreadcrumb("WorldGenerator", "User is modifying advanced settings."); var advancedSettingsEditor = Root.ConstructWidget(new Gui.Widgets.WorldGenerationSettingsDialog { Settings = Settings, OnClose = (s) => { if ((s as Gui.Widgets.WorldGenerationSettingsDialog).Result == Gui.Widgets.WorldGenerationSettingsDialog.DialogResult.Okay) { RestartGeneration(); } } }); Root.ShowModalPopup(advancedSettingsEditor); } }); StartButton = AddChild(new Gui.Widget { Text = "Launch", Border = "border-button", ChangeColorOnHover = true, TextColor = new Vector4(0, 0, 0, 1), Font = "font16", AutoLayout = Gui.AutoLayout.DockBottom, OnClick = (sender, args) => { Settings.Company.Name = NameField.Text; Settings.Company.Motto = MottoField.Text; Settings.InstanceSettings.InitalEmbarkment = new Embarkment(); Settings.PlayerCorporationFunds = 1000; Settings.Natives.FirstOrDefault(n => n.Name == "Player").PrimaryColor = new Color(Settings.Company.LogoBackgroundColor); OnVerified?.Invoke(); } }); AddChild(new Gui.Widget { Text = "Difficulty", AutoLayout = Gui.AutoLayout.DockTop, Font = "font8", TextColor = new Vector4(0, 0, 0, 1) }); var difficultySelectorCombo = AddChild(new Gui.Widgets.ComboBox { AutoLayout = Gui.AutoLayout.DockTop, Items = Library.EnumerateDifficulties().Select(e => e.Name).ToList(), TextColor = new Vector4(0, 0, 0, 1), Font = "font8", OnSelectedIndexChanged = (sender) => { Settings.Difficulty = Library.GetDifficulty((sender as Gui.Widgets.ComboBox).SelectedItem); } }) as Gui.Widgets.ComboBox; AddChild(new Gui.Widget { Text = "Caves", AutoLayout = Gui.AutoLayout.DockTop, Font = "font8", TextColor = new Vector4(0, 0, 0, 1), }); var layerSetting = AddChild(new Gui.Widgets.ComboBox { AutoLayout = AutoLayout.DockTop, Items = new List <string>(new string[] { "Barely any", "Few", "Normal", "Lots", "Way too many" }), Font = "font8", TextColor = new Vector4(0, 0, 0, 1), OnSelectedIndexChanged = (sender) => { switch ((sender as Gui.Widgets.ComboBox).SelectedItem) { case "Barely any": Settings.NumCaveLayers = 2; break; case "Few": Settings.NumCaveLayers = 3; break; case "Normal": Settings.NumCaveLayers = 4; break; case "Lots": Settings.NumCaveLayers = 6; break; case "Way too many": Settings.NumCaveLayers = 9; break; } } }) as Gui.Widgets.ComboBox; AddChild(new Gui.Widget { Text = "Z Levels", AutoLayout = Gui.AutoLayout.DockTop, Font = "font8", TextColor = new Vector4(0, 0, 0, 1), }); var zLevelSetting = AddChild(new Gui.Widgets.ComboBox { AutoLayout = AutoLayout.DockTop, Items = new List <string>(new string[] { "16", "64", "128" }), Font = "font8", TextColor = new Vector4(0, 0, 0, 1), OnSelectedIndexChanged = (sender) => { switch ((sender as Gui.Widgets.ComboBox).SelectedItem) { case "16": Settings.zLevels = 1; break; case "64": Settings.zLevels = 4; break; case "128": Settings.zLevels = 8; break; } } }) as Gui.Widgets.ComboBox; zLevelSetting.SelectedIndex = 1; difficultySelectorCombo.SelectedIndex = difficultySelectorCombo.Items.IndexOf("Normal"); layerSetting.SelectedIndex = layerSetting.Items.IndexOf("Normal"); #region Name AddChild(new Gui.Widget { MinimumSize = new Point(64, 0), Text = "Company Name", Font = "font8", AutoLayout = AutoLayout.DockTop, TextHorizontalAlign = HorizontalAlign.Left, TextVerticalAlign = VerticalAlign.Center }); var nameRow = AddChild(new Widget { MinimumSize = new Point(0, 32), AutoLayout = AutoLayout.DockTop, Padding = new Margin(0, 0, 2, 2) }); nameRow.AddChild(new Gui.Widgets.Button { Text = "?", AutoLayout = AutoLayout.DockRight, Border = "border-button", OnClick = (sender, args) => { var templates = TextGenerator.GetAtoms(ContentPaths.Text.Templates.company); NameField.Text = TextGenerator.GenerateRandom(Datastructures.SelectRandom(templates).ToArray()); } }); NameField = nameRow.AddChild(new Gui.Widgets.EditableTextField { Text = Settings.Company.Name, AutoLayout = AutoLayout.DockFill }) as Gui.Widgets.EditableTextField; #endregion #region Motto AddChild(new Widget { MinimumSize = new Point(64, 0), Text = "Company Motto", Font = "font8", AutoLayout = AutoLayout.DockTop, TextHorizontalAlign = HorizontalAlign.Left, TextVerticalAlign = VerticalAlign.Center }); var mottoRow = AddChild(new Widget { MinimumSize = new Point(0, 32), AutoLayout = AutoLayout.DockTop, Padding = new Margin(0, 0, 2, 2) }); mottoRow.AddChild(new Gui.Widgets.Button { Text = "?", AutoLayout = AutoLayout.DockRight, Border = "border-button", OnClick = (sender, args) => { var templates = TextGenerator.GetAtoms(ContentPaths.Text.Templates.mottos); MottoField.Text = TextGenerator.GenerateRandom(Datastructures.SelectRandom(templates).ToArray()); // Todo: Doesn't automatically invalidate when text changed?? MottoField.Invalidate(); } }); MottoField = mottoRow.AddChild(new Gui.Widgets.EditableTextField { Text = Settings.Company.Motto, AutoLayout = AutoLayout.DockFill }) as Gui.Widgets.EditableTextField; #endregion #region Logo AddChild(new Widget { MinimumSize = new Point(64, 0), Text = "Company Logo", Font = "font8", AutoLayout = AutoLayout.DockTop, TextHorizontalAlign = HorizontalAlign.Left, TextVerticalAlign = VerticalAlign.Center }); var logoRow = AddChild(new Widget { MinimumSize = new Point(0, 64), AutoLayout = AutoLayout.DockTop, Padding = new Margin(0, 0, 2, 2) }); CompanyLogoDisplay = logoRow.AddChild(new Gui.Widgets.CompanyLogo { AutoLayout = AutoLayout.DockLeft, MinimumSize = new Point(64, 64), MaximumSize = new Point(64, 64), CompanyInformation = Settings.Company }) as Gui.Widgets.CompanyLogo; var rightBox = logoRow.AddChild(new Widget { AutoLayout = AutoLayout.DockFill }); var bgBox = rightBox.AddChild(new Widget { AutoLayout = AutoLayout.DockTop, MinimumSize = new Point(32, 32), }); bgBox.AddChild(new Widget { Text = "BG:", AutoLayout = AutoLayout.DockLeft }); bgBox.AddChild(new Widget { Background = Settings.Company.LogoBackground, MinimumSize = new Point(32, 32), MaximumSize = new Point(32, 32), AutoLayout = AutoLayout.DockLeft, OnClick = (sender, args) => { var source = Root.GetTileSheet("company-logo-background") as Gui.TileSheet; var chooser = new Gui.Widgets.GridChooser { ItemSource = Enumerable.Range(0, source.Columns * source.Rows) .Select(i => new Widget { Background = new TileReference("company-logo-background", i) }), OnClose = (s2) => { var gc = s2 as Gui.Widgets.GridChooser; if (gc.DialogResult == Gui.Widgets.GridChooser.Result.OKAY && gc.SelectedItem != null) { sender.Background = gc.SelectedItem.Background; sender.Invalidate(); Settings.Company.LogoBackground = gc.SelectedItem.Background; CompanyLogoDisplay.Invalidate(); } }, PopupDestructionType = PopupDestructionType.DestroyOnOffClick }; Root.ShowModalPopup(chooser); } }); bgBox.AddChild(new Widget { Background = new TileReference("basic", 1), BackgroundColor = Settings.Company.LogoBackgroundColor, MinimumSize = new Point(32, 32), MaximumSize = new Point(32, 32), AutoLayout = AutoLayout.DockLeft, OnClick = (sender, args) => { var chooser = new Gui.Widgets.GridChooser { ItemSize = new Point(16, 16), ItemSpacing = new Point(4, 4), ItemSource = EnumerateDefaultColors() .Select(c => new Widget { Background = new TileReference("basic", 1), BackgroundColor = new Vector4(c.ToVector3(), 1), }), OnClose = (s2) => { var gc = s2 as Gui.Widgets.GridChooser; if (gc.DialogResult == Gui.Widgets.GridChooser.Result.OKAY && gc.SelectedItem != null) { sender.BackgroundColor = gc.SelectedItem.BackgroundColor; sender.Invalidate(); Settings.Company.LogoBackgroundColor = gc.SelectedItem.BackgroundColor; CompanyLogoDisplay.Invalidate(); } }, PopupDestructionType = PopupDestructionType.DestroyOnOffClick }; Root.ShowModalPopup(chooser); } }); var fgBox = rightBox.AddChild(new Widget { AutoLayout = AutoLayout.DockFill, MinimumSize = new Point(32, 32), }); fgBox.AddChild(new Widget { Text = "FG:", AutoLayout = AutoLayout.DockLeft }); fgBox.AddChild(new Widget { Background = Settings.Company.LogoSymbol, MinimumSize = new Point(32, 32), MaximumSize = new Point(32, 32), AutoLayout = AutoLayout.DockLeft, OnClick = (sender, args) => { var source = Root.GetTileSheet("company-logo-symbol") as Gui.TileSheet; var chooser = new Gui.Widgets.GridChooser { ItemSource = Enumerable.Range(0, source.Columns * source.Rows) .Select(i => new Widget { Background = new TileReference("company-logo-symbol", i) }), OnClose = (s2) => { var gc = s2 as Gui.Widgets.GridChooser; if (gc.DialogResult == Gui.Widgets.GridChooser.Result.OKAY && gc.SelectedItem != null) { sender.Background = gc.SelectedItem.Background; sender.Invalidate(); Settings.Company.LogoSymbol = gc.SelectedItem.Background; CompanyLogoDisplay.Invalidate(); } }, PopupDestructionType = PopupDestructionType.DestroyOnOffClick }; Root.ShowModalPopup(chooser); } }); fgBox.AddChild(new Widget { Background = new TileReference("basic", 1), BackgroundColor = Settings.Company.LogoSymbolColor, MinimumSize = new Point(32, 32), MaximumSize = new Point(32, 32), AutoLayout = AutoLayout.DockLeft, OnClick = (sender, args) => { var chooser = new Gui.Widgets.GridChooser { ItemSize = new Point(16, 16), ItemSpacing = new Point(4, 4), ItemSource = EnumerateDefaultColors() .Select(c => new Widget { Background = new TileReference("basic", 1), BackgroundColor = new Vector4(c.ToVector3(), 1), }), OnClose = (s2) => { var gc = s2 as Gui.Widgets.GridChooser; if (gc.DialogResult == Gui.Widgets.GridChooser.Result.OKAY && gc.SelectedItem != null) { sender.BackgroundColor = gc.SelectedItem.BackgroundColor; sender.Invalidate(); Settings.Company.LogoSymbolColor = gc.SelectedItem.BackgroundColor; CompanyLogoDisplay.Invalidate(); } }, PopupDestructionType = PopupDestructionType.DestroyOnOffClick }; Root.ShowModalPopup(chooser); } }); #endregion base.Construct(); }