public object doMLVForPoint(GameCell gameCell) { log(); object result="Клетка пуста."; if (gameCell.FrameExample != null && gameCell.FrameExample.BaseFrame != null && gameCell.FrameExample.BaseFrame.FrameId != -1) { situations = gatherSituationsList(); situationExample = new FrameExample(); Slot slotAgent = new Slot(); slotAgent.SlotName = "agent"; slotAgent.SlotType = SlotType.Frame; slotAgent.SlotInheritance = SlotInherit.Override; slotAgent.IsSystem = false; situationExample.AddSlot(slotAgent); situationExample.SetValue("agent", gameCell.FrameExample); Frame situationToCheck = this.getNextFrameToCheck(); while (!situationExample.ContainsSlot("action") && situationToCheck != null) //пока не определили целевой слот "действие" { checkedFramesIDs.Add(situationToCheck.FrameId); if (checkSituation(situationToCheck, situationExample)) { Slot actionSlot = situationToCheck.GetSlotByName("action"); situationExample.AddSlot(actionSlot); situationExample.SetValue(actionSlot.SlotName, actionSlot.SlotDefault); } situationToCheck = this.getNextFrameToCheck(); } result = null; if (situationExample.ContainsSlot("action")) result = situationExample.Value("action"); } return result; }
public Frame() { FrameSlots = new List<Slot>(); //IsA.IsSystem = true; //Error.IsSystem = true; IsA = new Slot{SlotId = -1, IsSystem = true, SlotName = "IsA", SlotDefault = "NULL", SlotType = SlotType.Frame}; Error = new Slot { SlotId = -1, IsSystem = true, SlotName = "Error", SlotDefault = "NULL", SlotType = SlotType.Frame }; }
private void FrameDiagram_LinkCreated(object sender, LinkEventArgs e) { Frame frame = new Frame(); Frame frame1 = new Frame(); Frame frameUpper;// = ClassFactory.kBase.FrameList().Find(f => f.FrameId == (int)e.Link.Destination.Id); Frame frameLower; string str = ""; switch (cmbTypeLink.SelectedIndex) { case 0: e.Link.Text = "Is_a"; e.Link.TextColor = Color.DarkRed; e.Link.Pen.Color = Color.Red; frameUpper = ClassFactory.kBase.FrameList().Find(f => f.FrameId == (int)e.Link.Destination.Id); frameLower = ClassFactory.kBase.FrameList().Find(f => f.FrameId == (int)e.Link.Origin.Id); //foreach (DiagramNode node in FrameDiagram.Nodes) //{ // if (node.GetBounds().Contains(StartLinkPoint.X, StartLinkPoint.Y)) // { // if (cmbTypeLink.SelectedIndex == 0) // { // frame = ClassFactory.kBase.FrameList().Find(f => f.FrameId == (int)node.Id); // } // str = node.Id.ToString() + cmbTypeLink.SelectedItem.ToString(); // } // if (node.GetBounds().Contains(EndLinkPoint.X, EndLinkPoint.Y)) // { // frame1 = ClassFactory.kBase.FrameList().Find(f => f.FrameId == (int)node.Id); // } //} //frame.IsA.ParentId = frame1.FrameId; //frame.IsA.SlotDefault = frame1.FrameName; //frame.IsA.frameId = frame1.FrameId; frameLower.IsA.ParentId = frameUpper.FrameId; frameLower.IsA.SlotDefault = frameUpper.FrameName; frameLower.IsA.frameId = frameUpper.FrameId; ClassFactory.kBase.AddIsA(frame); //простор для оптимизации break; case 1: e.Link.Text = "Sub"; e.Link.TextColor = Color.DarkBlue; e.Link.Pen.Color = Color.Blue; frameUpper = ClassFactory.kBase.FrameList().Find(f => f.FrameId == (int)e.Link.Destination.Id); frameLower = ClassFactory.kBase.FrameList().Find(f => f.FrameId == (int)e.Link.Origin.Id); //foreach (DiagramNode node in FrameDiagram.Nodes) //{ // if (node.GetBounds().Contains(StartLinkPoint.X, StartLinkPoint.Y)) // { // if (cmbTypeLink.SelectedIndex == 0) // { // frame = ClassFactory.kBase.FrameList().Find(f => f.FrameId == (int)node.Id); // } // str = node.Id.ToString() + cmbTypeLink.SelectedItem.ToString(); // } // if (node.GetBounds().Contains(EndLinkPoint.X, EndLinkPoint.Y)) // { // frame1 = ClassFactory.kBase.FrameList().Find(f => f.FrameId == (int)node.Id); // } //} Slot slotSubframe = new Slot(){ IsSystem = false, frameId = frameLower.FrameId, ParentId = frameUpper.FrameId, SlotName="sub", SlotType = Classes.SlotType.Frame}; frameUpper.FrameSlots.Add(slotSubframe); break; } //MessageBox.Show(str + str1); }
/// <summary> /// Вычисляет выражение, стоящее в левой или правой части condition'а. /// </summary> /// <param name="frameContext"></param> /// <param name="expression"></param> /// <param name="expressionType"></param> /// <returns></returns> private object evaluateExpression(Frame frameContext, Slot testedSlot, FrameExample frameMemory, FrameExample testedSubFrame, string expression, out SlotType expressionType) { //object result = null; //expressionType = SlotType.String; object result = frameMemory; expressionType = SlotType.Frame; expression = expression.Trim().ToLower(); int currentIndex = 0; string currentPart=""; while (currentIndex < expression.Length) { switch (expression[currentIndex]) { case '[': while (expression[++currentIndex] != ']') currentPart += expression[currentIndex]; ++currentIndex; break; case '.': ++currentIndex; continue; break; default: currentPart = expression.Substring(currentIndex); currentPart = currentPart.Replace(" ", ""); currentIndex = expression.Length; //обработка всяких там +-1 и т.д. break; } Slot tmpSlot; int tmpInt; switch (expressionType) { case SlotType.Frame: //tmpSlot = ((FrameExample)result).BaseFrame.GetSlotByName(currentPart); //TODO: костыль ИМХО :( if (currentPart == testedSlot.SlotNameTrimmed) result = testedSubFrame; else { tmpSlot = ((FrameExample)result).GetSlotByName(currentPart); if (tmpSlot.SlotType != SlotType.FramePrototype) result = ((FrameExample)result).Value(currentPart); else result = KnowLedgeBase.getFrameByID(tmpSlot.frameId); expressionType = tmpSlot.SlotType; } break; case SlotType.FramePrototype: //sl = ((Frame)result).GetSlotByName(currentPart); //ничего не надо обрабатывать, ссылка может быть только на сам фрейм-прототип. На его слоты ссылаться мы не можем. break; case SlotType.Integer: tmpInt = Int32.Parse(currentPart); result = ((int)result) + tmpInt; break; case SlotType.Boolean: case SlotType.String: //тоже ничего не будем делать. break; } currentPart = ""; } return result; }
private bool doesFrameFitCondition(Frame frameContext, FrameExample frameToTest, FrameExample frameMemory, Slot checkedSlot, string condition) { bool result = false; string leftPart=null; string rightPart=null; Operations operation; int operationIndexInText; string[] differentOperations = { "#isa", "==", "!=", "#morethan", "#lessthan", "#moreequal", "#lessequal" }; int operationIndexInArray = -1; //foreach (string operationToLookFor in differentOperations) for (int i=0; i<differentOperations.Length; ++i) { string operationToLookFor = differentOperations[i]; if (condition.Contains(operationToLookFor)) { operationIndexInText = condition.IndexOf(operationToLookFor); operationIndexInArray = i; leftPart = condition.Substring(0, operationIndexInText); rightPart = condition.Substring(operationIndexInText + operationToLookFor.Length); break; } } switch (operationIndexInArray) { case 0: operation = Operations.isa; break; case 1: operation = Operations.equal; break; case 2: operation = Operations.notequal; break; case 3: operation = Operations.morethan; break; case 4: operation = Operations.lessthan; break; case 5: operation = Operations.moreequal; break; case 6: operation = Operations.lessequal; break; default: throw new IndexOutOfRangeException(); } SlotType leftType, rightType; object leftPartResult = evaluateExpression(frameContext, checkedSlot, frameMemory, frameToTest, leftPart, out leftType); object rightPartResult = evaluateExpression(frameContext, checkedSlot, frameMemory, frameToTest, rightPart, out rightType); Exception typeComparisonException = new Exception("Can not compare different types!"); switch (operation) { case Operations.isa: if (leftType == SlotType.Frame && rightType == SlotType.FramePrototype) { result = ((FrameExample)leftPartResult).CheckIsA((Frame)rightPartResult); } else throw new Exception("Incorrect frame types for 'is a' relation!"); break; case Operations.equal: if (leftType == rightType) { switch (leftType) { //TODO: возможно, тут стоит добавить более изящное сравнение. case SlotType.Boolean: result = leftPartResult.ToString() == rightPartResult.ToString(); break; case SlotType.Integer: result = ((int)leftPartResult) == ((int)rightPartResult); break; case SlotType.String: result = leftPartResult.ToString() == rightPartResult.ToString(); break; default: throw new Exception("Only boolean, integer and string slots can be compared."); } } else throw typeComparisonException; break; case Operations.notequal: if (leftType == rightType) { result = leftPartResult.ToString() == rightPartResult.ToString(); } else throw typeComparisonException; break; case Operations.morethan: if (leftType == rightType && rightType == SlotType.Integer) { result = ((int)leftPartResult) > ((int)rightPartResult); } else throw typeComparisonException; break; case Operations.lessthan: if (leftType == rightType && rightType == SlotType.Integer) { result = ((int)leftPartResult) < ((int)rightPartResult); } else throw typeComparisonException; break; case Operations.moreequal: if (leftType == rightType && rightType == SlotType.Integer) { result = ((int)leftPartResult) >= ((int)rightPartResult); } else throw typeComparisonException; break; case Operations.lessequal: if (leftType == rightType && rightType == SlotType.Integer) { result = ((int)leftPartResult) <= ((int)rightPartResult); } else throw typeComparisonException; break; } return result; }
/// <summary> /// Привязываем субфрейм. /// </summary> /// <param name="frameTested"></param> /// <param name="marker"></param> /// <returns></returns> private FrameExample boundSubframe(Slot slot, FrameExample situationExample) { FrameExample result = null; Frame framePrototype = KnowLedgeBase.getFrameByID(slot.frameId); List<FrameExample> framesCandidates = new List<FrameExample>(); foreach (FrameExample frame in KnowLedgeBase.FramesExamples) if (frame.CheckIsA(framePrototype)) framesCandidates.Add(frame); string[] separatorsOr = { "#or" }; string[] separatorsAnd = { "#and" }; foreach (FrameExample candidate in framesCandidates) { string[] conjuncts = slot.SlotMarker.Split(separatorsOr, StringSplitOptions.None); foreach (string conjunct in conjuncts) { string[] conditions = conjunct.Split(separatorsAnd, StringSplitOptions.None); bool fitsAllConditions = true; foreach (string condition in conditions) { if (!doesFrameFitCondition(framePrototype, candidate, situationExample, slot, condition)) { fitsAllConditions = false; break; } } if (fitsAllConditions) { result = candidate; break; } } } return result; }
/// <summary> /// Привязываем слот (проверяем на соответствие маркеру) /// </summary> /// <param name="slot">Сам слот</param> /// <param name="situationProrotype">Ситуация, которую мы сейчас привязываем (см. checkSituation).</param> /// <param name="situationExample">Текущий фрейм-экземпляр.</param> /// <returns>Если слот привязался, возвращаем его значение (в соответствие с типом слота). Иначе - null.</returns> private object boundSlot(Slot slot, Frame situationProrotype, FrameExample situationExample) { object result = null; switch (slot.SlotType) { case SlotType.Frame: FrameExample boundedSubframe = boundSubframe(slot, situationExample); result = boundedSubframe; break; //сколько тут получилось разнообразных вариантов вывода, аж обалдеть можно. } return result; }
/// <summary> /// Задает размер поля (в ячейках) по вертикали и горизонтали. !ВАЖНО: игровое поле создается заново! Все данные о ячейках стираются! /// </summary> /// <param name="rowCount">Число ячеек по вертикали (число рядов)</param> /// <param name="columnCount">Число ячеек по горизонтали (число столбцов)</param> public void setSize(int rowCount, int columnCount) { if (rowCount < 1 || columnCount < 1) throw new ArgumentException("Row and column counts have to be more than zero! size: (rc:"+rowCount.ToString()+" cc:"+columnCount.ToString()+")"); cells = new List<List<GameCell>>(rowCount); //int xCoord = 0, yCoord = 0; this.SuspendLayout(); this.Controls.Clear(); for (int i = 0; i < RowCount; ++i) { //xCoord = 0; List<GameCell> row = new List<GameCell>(columnCount); for (int j = 0; j < ColumnCount; ++j) { Frame framePrototype = new Frame(); framePrototype.FrameId = -1; Slot slotImage = new Slot(); slotImage.SlotName = "image"; slotImage.SlotInheritance = SlotInherit.Override; slotImage.SlotType = SlotType.String; slotImage.SlotDefault = "Images\\unknown.png"; slotImage.SlotId = 0; slotImage.ParentId = framePrototype.FrameId; Slot slotRow = new Slot(); slotRow.SlotName = "Row"; slotRow.SlotType = SlotType.Integer; slotRow.SlotInheritance = SlotInherit.Override; slotRow.SlotId = 1; slotRow.ParentId = framePrototype.FrameId; Slot slotColumn = new Slot(); slotColumn.SlotName = "Column"; slotColumn.SlotType = SlotType.Integer; slotColumn.SlotInheritance = SlotInherit.Override; slotColumn.SlotId = 1; slotColumn.ParentId = framePrototype.FrameId; framePrototype.FrameSlots.Add(slotImage); framePrototype.FrameSlots.Add(slotRow); framePrototype.FrameSlots.Add(slotColumn); FrameExample frameExample = new FrameExample(framePrototype); frameExample.SetValue("image", "Images\\grass.jpg"); frameExample.SetValue("Row", i); frameExample.SetValue("Column", j); GameCell cell = new GameCell(this, i, j, cellSize, frameExample); cell.GameCellClicked += new GameCellClickedEventHandler(cell_GameCellClicked); row.Add(cell); //cell.Location = new Point(xCoord, yCoord); this.Controls.Add(cell); //xCoord += cellSize+cellOffset; } cells.Add(row); //yCoord += cellSize+cellOffset; } this.rowCount = rowCount; this.columnCount = columnCount; this.ResumeLayout(); this.layoutCells(); }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void FrameDiagram_LinkCreated(object sender, LinkEventArgs e) { Frame frameUpper; //тот фрейм, к которому идет дуга Frame frameLower; //тот фрейм, от которого идет дуга switch (cmbTypeLink.SelectedIndex) { case 0: e.Link.Text = "Is_a"; e.Link.TextColor = Color.DarkRed; e.Link.Pen.Color = Color.Red; frameUpper = ClassFactory.kBase.FrameList().Find(f => f.FrameId == (int)e.Link.Destination.Id); frameLower = ClassFactory.kBase.FrameList().Find(f => f.FrameId == (int)e.Link.Origin.Id); frameLower.IsA.ParentId = frameUpper.FrameId; frameLower.IsA.SlotDefault = frameUpper.FrameName; frameLower.IsA.frameId = frameUpper.FrameId; ClassFactory.kBase.AddIsA(frameLower); //простор для оптимизации break; case 1: e.Link.Text = "Sub"; e.Link.TextColor = Color.DarkBlue; e.Link.Pen.Color = Color.Blue; frameUpper = ClassFactory.kBase.FrameList().Find(f => f.FrameId == (int)e.Link.Destination.Id); frameLower = ClassFactory.kBase.FrameList().Find(f => f.FrameId == (int)e.Link.Origin.Id); Slot slotSubframe = new Slot(){ IsSystem = false, frameId = frameLower.FrameId, ParentId = frameUpper.FrameId, SlotName="sub", SlotType = Classes.SlotType.Frame}; frameUpper.FrameSlots.Add(slotSubframe); break; } }
public void AddSlot(Slot slot) { slot.SlotId = this.getNextSlotID(); if (!this.ContainsSlot(slot.SlotName)) this.slots.Add(slot); else throw new ArgumentException("Слот с таким именем ("+slot.SlotName+") уже существует"); }