Ejemplo n.º 1
0
        public void PlayerDrawCards()
        {
            game.Cards = new CardManager();
            Card c1 = new TestCard();
            Card c2 = new TestCard();
            Card c3 = new TestCard();
            Card c4 = new TestCard();

            game.Cards.Deck.AddCard(c1);
            game.Cards.Deck.AddCard(c2);
            game.Cards.Deck.AddCard(c3);
            game.Cards.Deck.AddCard(c4);

            game.Players = new PlayerManager(1);
            GamePlayer target = game.Players.GetPlayer(0);

            Assert.AreEqual(target.Hand.GetSize(), 0);
            bytes.push(InstructionFactory.Make_PlayerDrawCards(
                           LiteralFactory.CreatePlayerLiteral(target),
                           LiteralFactory.CreateIntLiteral(2)
                           ));
            game.ExecuteNext();
            Assert.AreEqual(target.Hand.GetSize(), 2);
        }
Ejemplo n.º 2
0
 public InstructionFactoryTests()
 {
     _sut = InstructionFactory.Instance;
 }
Ejemplo n.º 3
0
    public void executeNext()
    {
        Instruction next = this.next();

        try {
            switch (next)
            {
            // FUNCTIONS

            case Instruction.RANDOM_NUMBER: {
                int upperBound = ReadIntLiteral(skipToNext);
                push(LiteralFactory.CreateIntLiteral(UnityEngine.Random.Range(1, upperBound)));
                break;
            }

            case Instruction.ADD: {
                int a = ReadIntLiteral(skipToNext);
                int b = ReadIntLiteral(skipToNext);
                push(LiteralFactory.CreateIntLiteral(a + b));
                break;
            }

            case Instruction.IF: {
                int         controlID  = ReadIntLiteral(skipToNext);
                Condition   condition  = ReadConditionLiteral(skipToNext);
                List <byte> blockBytes = new List <byte>();

                while (HasBytes())
                {
                    byte b = pop();
                    if (b == (byte)Instruction.ENDIF)
                    {
                        int id = ReadIntLiteral(skipToNext);
                        if (id == controlID)
                        {
                            break;
                        }
                        else
                        {
                            blockBytes.Insert(0, (byte)Instruction.ENDIF);
                            blockBytes.InsertRange(0, LiteralFactory.CreateIntLiteral(id));
                        }
                    }
                    else
                    {
                        blockBytes.Insert(0, b);
                    }
                }
                if (condition.Evaluate())
                {
                    push(blockBytes);
                }
                break;
            }

            case Instruction.UNLESS: {
                int         controlID  = ReadIntLiteral(skipToNext);
                Condition   condition  = ReadConditionLiteral(skipToNext);
                List <byte> blockBytes = new List <byte>();

                while (HasBytes())
                {
                    byte b = pop();
                    if (b == (byte)Instruction.ENDIF)
                    {
                        int id = ReadIntLiteral(skipToNext);
                        if (id == controlID)
                        {
                            break;
                        }
                        else
                        {
                            blockBytes.Insert(0, (byte)Instruction.ENDIF);
                            blockBytes.InsertRange(0, LiteralFactory.CreateIntLiteral(id));
                        }
                    }
                    else
                    {
                        blockBytes.Insert(0, b);
                    }
                }
                if (!condition.Evaluate())
                {
                    push(blockBytes);
                }
                break;
            }

            case Instruction.LIST_LENGTH: {
                List <byte[]> list = ReadList(skipToNext);
                push(LiteralFactory.CreateIntLiteral(list.Count));
                break;
            }

            case Instruction.CARD_HAS_TAG: {
                Card   card    = GM.ReadCardFromStack();
                string tagName = ReadStringLiteral(skipToNext);
                push(LiteralFactory.CreateConditionLiteral(
                         LiteralFactory.CreateBoolLiteral(card.HasTag(tagName)),
                         LiteralFactory.CreateBoolLiteral(true),
                         ConditionType.BOOL,
                         ConditionOperator.EQUAL
                         ));
                break;
            }

            case Instruction.PLAYER_IS_WINNING: {
                GamePlayer player  = GM.ReadPlayerFromStack();
                bool       winning = true;
                foreach (GamePlayer otherPlayer in GM.Players.GetPlayers())
                {
                    if (otherPlayer.Points > player.Points)
                    {
                        winning = false;
                        break;
                    }
                }
                push(LiteralFactory.CreateConditionLiteral(
                         LiteralFactory.CreateBoolLiteral(winning),
                         LiteralFactory.CreateBoolLiteral(true),
                         ConditionType.BOOL,
                         ConditionOperator.EQUAL
                         ));
                break;
            }

            case Instruction.PLAYER_IS_LOSING: {
                GamePlayer player = GM.ReadPlayerFromStack();
                bool       losing = true;
                foreach (GamePlayer otherPlayer in GM.Players.GetPlayers())
                {
                    if (otherPlayer.Points < player.Points)
                    {
                        losing = false;
                        break;
                    }
                }
                push(LiteralFactory.CreateBoolLiteral(losing));
                break;
            }

            case Instruction.MULTIPLY: {
                int a = ReadIntLiteral(skipToNext);
                int b = ReadIntLiteral(skipToNext);
                push(LiteralFactory.CreateIntLiteral(a * b));
                break;
            }

            case Instruction.LOOP: {
                int id  = ReadIntLiteral(skipToNext);
                int num = ReadIntLiteral(skipToNext);
                List <List <byte> > instructionArrays = new List <List <byte> >();
                while (HasBytes())
                {
                    if (peek() == (byte)Instruction.ENDLOOP)
                    {
                        pop();
                        int endloopID = ReadIntLiteral(skipToNext);
                        if (endloopID == id)
                        {
                            break;
                        }
                        else
                        {
                            List <byte> endloopBytes = new List <byte>(LiteralFactory.CreateIntLiteral(endloopID));
                            endloopBytes.Add((byte)Instruction.ENDLOOP);
                            instructionArrays.Insert(0, endloopBytes);
                        }
                    }
                    else
                    {
                        List <byte> arr = popInstruction(skipToNext);
                        instructionArrays.Insert(0, arr);
                    }
                }
                for (int n = 0; n < num; n++)
                {
                    for (int m = 0; m < instructionArrays.Count; m++)
                    {
                        push(instructionArrays[m]);
                    }
                }
                break;
            }

            case Instruction.FOR_LOOP: {
                int                 ID                = ReadIntLiteral(skipToNext);
                List <byte[]>       items             = ReadList(skipToNext);
                List <List <byte> > instructionArrays = new List <List <byte> >();
                while (HasBytes())
                {
                    if (peek() == (byte)Instruction.ENDLOOP)
                    {
                        pop();
                        int endloopID = ReadIntLiteral(skipToNext);
                        if (endloopID == ID)
                        {
                            break;
                        }
                        else
                        {
                            List <byte> endloopBytes = new List <byte>(LiteralFactory.CreateIntLiteral(endloopID));
                            endloopBytes.Add((byte)Instruction.ENDLOOP);
                            instructionArrays.Insert(0, endloopBytes);
                        }
                    }
                    List <byte> arr = popInstruction(skipToNext);
                    instructionArrays.Insert(0, arr);
                }

                List <byte> idBytes = LiteralFactory.CreateIntLiteral(ID);
                for (int i = 0; i < items.Count; i++)
                {
                    List <byte> currentItem = new List <byte>(items[i]);
                    currentItem.Reverse();
                    List <byte> addToRegister = InstructionFactory.Make_AddToRegister(idBytes, currentItem);
                    for (int m = 0; m < instructionArrays.Count; m++)
                    {
                        push(instructionArrays[m]);
                    }
                    push(addToRegister);
                }
                break;
            }

            case Instruction.ADD_TO_REGISTER: {
                int         ID    = ReadIntLiteral(skipToNext);
                int         size  = ReadIntLiteral(skipToNext);
                List <byte> bytes = pop(size);
                register[ID] = bytes;
                break;
            }

            case Instruction.PLACEHOLDER: {
                int         ID    = ReadIntLiteral(skipToNext);
                List <byte> fetch = new List <byte>(register[ID]);
                fetch.Reverse();
                push(fetch);
                break;
            }

            // QUERIES

            case Instruction.GET_ACTIVE_PLAYER: {
                push(LiteralFactory.CreatePlayerLiteral(GM.Players.GetActivePlayer()));
                break;
            }

            case Instruction.GET_ALL_OPPONENTS: {
                push(LiteralFactory.CreateListLiteral(
                         new List <GamePlayer>(GM.Players.GetOpponents())
                         ));
                break;
            }

            case Instruction.GET_ALL_PLAYERS: {
                push(LiteralFactory.CreateListLiteral(
                         new List <GamePlayer>(GM.Players.GetPlayers())
                         ));
                break;
            }

            case Instruction.GET_CARDS_IN_DECK: {
                push(LiteralFactory.CreateListLiteral(
                         new List <Card>(GM.Cards.Deck.GetCards())
                         ));
                break;
            }

            case Instruction.GET_CARDS_IN_DISCARD: {
                push(LiteralFactory.CreateListLiteral(
                         new List <Card>(GM.Cards.Discard.GetCards())
                         ));
                break;
            }

            case Instruction.GET_CARDS_IN_HAND: {
                GamePlayer player = GM.ReadPlayerFromStack();
                push(LiteralFactory.CreateListLiteral(
                         new List <Card>(player.Hand.GetCards())
                         ));
                break;
            }

            case Instruction.GET_PLAYER_POINTS: {
                GamePlayer player = GM.ReadPlayerFromStack();
                int        points = player.Points;
                push(LiteralFactory.CreateIntLiteral(points));
                break;
            }

            case Instruction.READ_COUNTER: {
                string key   = ReadStringLiteral(skipToNext);
                int    count = GM.Variables.GetCounter(key);
                push(LiteralFactory.CreateIntLiteral(count));
                break;
            }

            case Instruction.BOOL_COMPARISON: {
                bool operandA     = ReadBoolLiteral(skipToNext);
                byte operatorEnum = ReadEnumLiteral();
                bool operandB     = ReadBoolLiteral(skipToNext);
                push(LiteralFactory.CreateConditionLiteral(
                         new CompareBool(operandA, operandB, (ConditionOperator)operatorEnum)
                         ));
                break;
            }

            case Instruction.NUM_COMPARISON: {
                int  operandA     = ReadIntLiteral(skipToNext);
                int  operandB     = ReadIntLiteral(skipToNext);
                byte operatorEnum = ReadEnumLiteral();
                push(LiteralFactory.CreateConditionLiteral(
                         new CompareNum(operandA, operandB, (ConditionOperator)operatorEnum)
                         ));
                break;
            }

            case Instruction.TARGET_PLAYER: {
                GM.UI.PresentChoiceOfPlayers(new List <GamePlayer>(GM.Players.GetPlayers()), this);
                break;
            }

            case Instruction.TARGET_OPPONENT: {
                GM.UI.PresentChoiceOfPlayers(new List <GamePlayer>(GM.Players.GetOpponents()), this);
                break;
            }

            case Instruction.TARGET_CARD_IN_DECK: {
                GM.UI.PresentChoiceOfCards(new List <Card>(GM.Cards.Deck.GetCards()), this);
                break;
            }

            case Instruction.TARGET_CARD_IN_DISCARD: {
                GM.UI.PresentChoiceOfCards(new List <Card>(GM.Cards.Discard.GetCards()), this);
                break;
            }

            case Instruction.TARGET_CARD_IN_HAND: {
                GamePlayer player = GM.ReadPlayerFromStack();
                GM.UI.PresentChoiceOfCards(new List <Card>(player.Hand.GetCards()), this);
                break;
            }

            case Instruction.RANDOM_PLAYER: {
                GamePlayer[] players      = GM.Players.GetPlayers();
                GamePlayer   randomPlayer = players[UnityEngine.Random.Range(0, players.Length)];
                push(LiteralFactory.CreatePlayerLiteral(randomPlayer));
                break;
            }

            case Instruction.RANDOM_OPPONENT: {
                GamePlayer[] opponents      = GM.Players.GetOpponents();
                GamePlayer   randomOpponent = opponents[UnityEngine.Random.Range(0, opponents.Length)];
                push(LiteralFactory.CreatePlayerLiteral(randomOpponent));
                break;
            }

            case Instruction.RANDOM_CARD_IN_DECK: {
                Card[] deckCards  = GM.Cards.Deck.GetCards();
                Card   randomCard = deckCards[UnityEngine.Random.Range(0, deckCards.Length)];
                push(LiteralFactory.CreateCardLiteral(randomCard));
                break;
            }

            case Instruction.RANDOM_CARD_IN_DISCARD: {
                Card[] discardCards = GM.Cards.Discard.GetCards();
                Card   randomCard   = discardCards[UnityEngine.Random.Range(0, discardCards.Length)];
                push(LiteralFactory.CreateCardLiteral(randomCard));
                break;
            }

            case Instruction.RANDOM_CARD_IN_HAND: {
                GamePlayer player     = GM.ReadPlayerFromStack();
                Card[]     handCards  = player.Hand.GetCards();
                Card       randomCard = handCards[UnityEngine.Random.Range(0, handCards.Length)];
                push(LiteralFactory.CreateCardLiteral(randomCard));
                break;
            }

            // EFFECTS

            case Instruction.INCREMENT_PLAYER_POINTS: {
                GamePlayer player    = GM.ReadPlayerFromStack();
                int        pointsNum = ReadIntLiteral(skipToNext);
                GM.SetPlayerPoints(player, player.Points + pointsNum);
                break;
            }

            case Instruction.PLAYER_DRAW_CARD: {
                GamePlayer player   = GM.ReadPlayerFromStack();
                int        numCards = ReadIntLiteral(skipToNext);
                for (int n = 0; n < numCards; n++)
                {
                    GM.PlayerDrawCard(player);
                }
                break;
            }

            case Instruction.SET_COUNTER: {
                string key   = ReadStringLiteral(skipToNext);
                int    count = ReadIntLiteral(skipToNext);
                GM.Variables.SetCounter(key, count);
                break;
            }

            case Instruction.SET_PLAYER_DRAW: {
                GamePlayer player = GM.ReadPlayerFromStack();
                int        num    = ReadIntLiteral(skipToNext);
                player.SetDrawPerTurn(num);
                break;
            }

            case Instruction.SET_PLAYER_MAX_HAND: {
                GamePlayer player = GM.ReadPlayerFromStack();
                int        num    = ReadIntLiteral(skipToNext);
                player.Hand.SetMax(num);
                break;
            }

            case Instruction.SET_PLAYER_POINTS: {
                GamePlayer player    = GM.ReadPlayerFromStack();
                int        pointsNum = ReadIntLiteral(skipToNext);
                GM.SetPlayerPoints(player, pointsNum);
                break;
            }

            case Instruction.MOVE_TO_DECK: {
                Card         card    = GM.ReadCardFromStack();
                DeckLocation posEnum = (DeckLocation)ReadEnumLiteral();
                card.Zone.MoveCard(GM.Cards.Deck, card.GetID());
                GM.Cards.Deck.MoveLastAddedCard(posEnum);
                break;
            }

            case Instruction.MOVE_TO_DISCARD: {
                Card card = GM.ReadCardFromStack();
                card.Zone.MoveCard(GM.Cards.Discard, card.GetID());
                break;
            }
            }
        } catch (UnexpectedByteException e) {
            Debug.LogError(e);
        } catch (StackFullException e) {
            Debug.LogError(e);
        } catch (StackEmptyException e) {
            Debug.LogError(e);
        }
    }
Ejemplo n.º 4
0
        private VisualInstructionUserControl InsertOutputInstructionAtRight(bool after, VisualInstructionUserControl visualInstruction, InstructionList instructions)
        {
            int index = 0;
            int autToRetornInsertedInstruction = 0;

            switch (visualOutputInstructions.Count)
            {
            case 0:
                index = 0;

                if (instructions.Count > 1)
                {
                    instructions.InsertParallelBranch(InstructionList.ParallelBranchInsertionType.ParallelBranchCompleted);
                    autToRetornInsertedInstruction = -1;
                }

                break;

            case 1:
                index = VerifyPositionToInsert(after, visualInstruction, this.visualOutputInstructions);

                if (index == 0)
                {
                    instructions.InsertParallelBranch(InstructionList.ParallelBranchInsertionType.ParallelBranchInitialized);

                    line.Outputs.Insert(0, InstructionFactory.createInstruction(OperationCode.ParallelBranchNext));
                    InsertVisualInstructionAt(0, this.visualOutputInstructions, InstructionFactory.createInstruction(OperationCode.ParallelBranchNext));
                    line.Outputs.Insert(this.visualOutputInstructions.Count, InstructionFactory.createInstruction(OperationCode.ParallelBranchEnd));
                    InsertVisualInstructionAt(this.visualOutputInstructions.Count, this.visualOutputInstructions, InstructionFactory.createInstruction(OperationCode.ParallelBranchEnd));
                }
                else
                {
                    instructions.InsertParallelBranch(InstructionList.ParallelBranchInsertionType.ParallelBranchFinalized);
                    autToRetornInsertedInstruction = -1;

                    line.Outputs.Insert(0, InstructionFactory.createInstruction(OperationCode.ParallelBranchBegin));
                    InsertVisualInstructionAt(0, this.visualOutputInstructions, InstructionFactory.createInstruction(OperationCode.ParallelBranchBegin));
                    index++;
                }

                break;

            default:
                index = VerifyPositionToInsert(false, visualInstruction, this.visualOutputInstructions);

                switch (this.visualOutputInstructions[index].OpCode)
                {
                case OperationCode.ParallelBranchBegin:
                    instructions.InsertParallelBranch(InstructionList.ParallelBranchInsertionType.ParallelBranchInitialized);

                    line.Outputs[0].OpCode = OperationCode.ParallelBranchNext;
                    this.visualOutputInstructions[0].OpCode = OperationCode.ParallelBranchNext;
                    break;

                case OperationCode.ParallelBranchNext:
                    instructions.InsertParallelBranchNext();
                    break;

                case OperationCode.ParallelBranchEnd:
                    instructions.InsertParallelBranchNext();
                    break;

                default:
                    instructions.InsertParallelBranchNext();
                    index++;
                    break;
                }
                break;
            }

            foreach (Instruction instruction in instructions)
            {
                line.Outputs.Insert(index, instruction);
                InsertVisualInstructionAt(index, this.visualOutputInstructions, instruction);
                index++;
            }

            return(this.visualOutputInstructions[index - 1 + autToRetornInsertedInstruction]);
        }
Ejemplo n.º 5
0
 public static IInstruction Parse(Token token)
 => InstructionFactory.CreateInstruction(Map[token]);
        protected List <PsudoInstruction> CompileBlock(PsudoMethod method, int startLine, int endLine)
        {
            List <PsudoInstruction> list = new List <PsudoInstruction>();

            for (int i = startLine; i <= endLine; i++)
            {
                try
                {
                    switch (this.scanner.lineTypes[i])
                    {
                    case PsudoLineType.Variable:
                        PsudoVariableInfo vInfo = this.scanner.variableInfo.Find(
                            item => item.Line == i);
                        vInfo.Processed = true;
                        list.Add(new CreateLocalVariable(i, method, vInfo.Type, vInfo.Name, vInfo.Default));
                        break;

                    case PsudoLineType.StartDecision:
                    case PsudoLineType.StartStartDecision:
                        int end;
                        list.Add(CompileDecision(method, i, out end));
                        i = end;
                        break;

                    case PsudoLineType.StartLoop:
                        int end2;
                        list.Add(CompileLoop(method, i, out end2));
                        i = end2;
                        break;

                    case PsudoLineType.Instruction:
                        list.Add(InstructionFactory.CompileInstruction(
                                     this.codeLines[i], i, method));
                        break;

                    // Nothing to do for the following
                    case PsudoLineType.StartMain:
                    case PsudoLineType.StartMethod:
                    case PsudoLineType.Whitespace:
                    case PsudoLineType.Comment:
                    case PsudoLineType.EndMethod:
                        break;

                    case PsudoLineType.EndDecision:
                        throw new Exception("Unexpected End Decision");

                    case PsudoLineType.EndLoop:
                        throw new Exception("Unexpected End Loop");

                    case PsudoLineType.EndClass:
                    case PsudoLineType.StartClass:
                        throw new Exception("Classes Not Supported Currently");

                    default:
                        throw new Exception(string.Format(
                                                "Error Compiling Method \"{0}\" on Line #{1}",
                                                method.Name, i + 1));
                    }
                }
                catch (Exception e)
                {
                    this.Errors.Add(new CompileError(e.Message, i + 1));
                }
            }

            return(list);
        }
Ejemplo n.º 7
0
        private ICollection <AddressableInstruction> ParseSource()
        {
            InstructionFactory instructionParser = new InstructionFactory();

            // We parse the source and build a list of all source
            // instructions (including comments), and a dictionary
            // of executable instructions, indexed by their source
            // starting address.
            List <Instruction> sourceList = new List <Instruction>();
            Dictionary <int, AddressableInstruction>    instructionDictionary        = new Dictionary <int, AddressableInstruction>();
            Dictionary <String, AddressableInstruction> labeledInstructionDictionary = new Dictionary <string, AddressableInstruction>();
            int instructionSourceAddress    = 0;
            int instructionSourceLineNumber = 0;

            // Loop through each line of source code and create an instruction for it.
            foreach (String sourceLine in _sourceCodeLines)
            {
                Instruction sourceInstruction = instructionParser.GenerateInstruction(sourceLine, instructionSourceLineNumber, instructionSourceAddress);

                if (sourceInstruction != null)
                {
                    AddressableInstruction addressableInstruction = sourceInstruction as AddressableInstruction;
                    if (addressableInstruction != null)
                    {
                        instructionDictionary.Add(instructionSourceAddress, addressableInstruction);

                        // If the instruction has a label, store a mapping so we can resolve labeled branches later.
                        if (!String.IsNullOrEmpty(addressableInstruction.Address.AddressLabel))
                        {
                            labeledInstructionDictionary.Add(addressableInstruction.Address.AddressLabel, addressableInstruction);
                        }

                        instructionSourceAddress += addressableInstruction.SourceLength;
                    }

                    sourceList.Add(sourceInstruction);

                    instructionSourceLineNumber++;
                }
            }

            // Loop through each instruction and map each branch address to the destination instruction.
            // This is done at the source level at this stage so we have a correctly mapped instruction
            // tree before we start generating binary and create the actual addresses.
            foreach (var instruction in instructionDictionary)
            {
                IBranchingInstruction branchingInstruction = instruction.Value as IBranchingInstruction;
                if (branchingInstruction != null)
                {
                    branchingInstruction.MapBranchAddress(instructionDictionary, labeledInstructionDictionary);
                }

                IAddressedOperands addressedOperandsInstruction = instruction.Value as IAddressedOperands;
                if (addressedOperandsInstruction != null)
                {
                    addressedOperandsInstruction.MapAddressedOperands(instructionDictionary, labeledInstructionDictionary);
                }

                AddressableMemoryInstruction memoryValue = instruction.Value as AddressableMemoryInstruction;
                if (memoryValue != null)
                {
                    memoryValue.MapMemoryValue(instructionDictionary, labeledInstructionDictionary);
                }
            }

            return(instructionDictionary.Values);
        }
Ejemplo n.º 8
0
 public void EmitTypeAs(Type type)
 {
     Emit(InstructionFactory.GetFactory(type).TypeAs());
 }
Ejemplo n.º 9
0
 private void End()
 => Instructions.Add(InstructionFactory.Halt(InstructionLine));
Ejemplo n.º 10
0
        public Instruction InsertToOutputs(Line line, InstructionList instructions)
        {
            int index = 0;
            int auxToPositionInsertedInstruciton = 0;

            switch (line.Outputs.Count)
            {
            case 0:
                /// case 0: First instruction to output, add only one
                /// instruction at output
                index = 0;

                if (instructions.Count > 1)
                {
                    instructions.InsertParallelBranch(InstructionList.ParallelBranchInsertionType.ParallelBranchCompleted);
                    auxToPositionInsertedInstruciton = -1;
                }

                break;

            case 1:
                /// case 1: If exists one output instruction, insert parallel branch
                /// automatically


                // here 0=before, 1=after
                if (index == 0)
                {
                    /// prepare to insert before the actual object
                    instructions.InsertParallelBranch(InstructionList.ParallelBranchInsertionType.ParallelBranchInitialized);

                    /// insert parallel branch next before the actual object
                    //line.Outputs.Insert(0, new Instruction(OperationCode.ParallelBranchNext));
                    line.Outputs.Insert(0, InstructionFactory.createInstruction(OperationCode.ParallelBranchNext));
                    /// insert parallel branch end after the actual object
                    //line.Outputs.Insert(line.Outputs.Count, new Instruction(OperationCode.ParallelBranchEnd));
                    line.Outputs.Insert(line.Outputs.Count, InstructionFactory.createInstruction(OperationCode.ParallelBranchEnd));
                }
                else
                {
                    instructions.InsertParallelBranch(InstructionList.ParallelBranchInsertionType.ParallelBranchFinalized);
                    auxToPositionInsertedInstruciton = -1;

                    line.Outputs.Insert(0, InstructionFactory.createInstruction(OperationCode.ParallelBranchBegin));
                    index++;
                }

                break;

            default:
                switch (line.Outputs[index].OpCode)
                {
                case OperationCode.ParallelBranchBegin:
                    instructions.InsertParallelBranch(InstructionList.ParallelBranchInsertionType.ParallelBranchInitialized);

                    line.Outputs[0].OpCode = OperationCode.ParallelBranchNext;
                    break;

                case OperationCode.ParallelBranchNext:
                    instructions.InsertParallelBranchNext();
                    break;

                case OperationCode.ParallelBranchEnd:
                    instructions.InsertParallelBranchNext();
                    break;

                default:
                    instructions.InsertParallelBranchNext();
                    index++;
                    break;
                }
                break;
            }

            foreach (Instruction instruction in instructions)
            {
                line.Outputs.Insert(index, instruction);
                index++;
            }
            return(line.Outputs[index - 1 + auxToPositionInsertedInstruciton]);
        }
 public void SetUp()
 {
     target = new InstructionFactory();
 }
        public void TestInstructionInstanciation()
        {
            List <IDefinition> empty   = new List <IDefinition>();
            List <IDefinition> one_int = new List <IDefinition> {
                Scalar.Integer
            };
            List <IDefinition> dbl_int = new List <IDefinition> {
                Scalar.Integer, Scalar.Integer
            };
            List <IDefinition> trp_int = new List <IDefinition> {
                Scalar.Integer, Scalar.Integer, Scalar.Integer
            };

            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.AND, empty).GetType() == typeof(And));
            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.OR, empty).GetType() == typeof(Or));

            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.DIFFERENT, dbl_int).GetType() == typeof(Different));
            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.EQUAL, dbl_int).GetType() == typeof(Equal));

            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.GREATER, dbl_int).GetType() == typeof(Greater));
            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.GREATER_EQUAL, dbl_int).GetType() == typeof(GreaterEqual));

            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.LOWER, dbl_int).GetType() == typeof(Less));
            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.LOWER_EQUAL, dbl_int).GetType() == typeof(LessEqual));

            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.ACCESS, trp_int).GetType() == typeof(Access));

            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.BINARY_AND, trp_int).GetType() == typeof(BinaryAnd));
            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.BINARY_OR, trp_int).GetType() == typeof(BinaryOr));
            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.XOR, trp_int).GetType() == typeof(Xor));

            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.ADD, trp_int).GetType() == typeof(Add));
            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.SUB, trp_int).GetType() == typeof(Substract));
            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.DIV, trp_int).GetType() == typeof(Divide));
            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.MUL, trp_int).GetType() == typeof(Multiplicate));
            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.MOD, trp_int).GetType() == typeof(Modulo));

            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.LEFT_SHIFT, trp_int).GetType() == typeof(LeftShift));
            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.RIGHT_SHIFT, trp_int).GetType() == typeof(RightShift));

            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.BINARY_NOT, dbl_int).GetType() == typeof(BinaryNot));
            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.NOT, one_int).GetType() == typeof(Not));
            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.INVERSE, dbl_int).GetType() == typeof(Inverse));

            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.ENUM_SPLITTER, new List <IDefinition> {
                new EnumType()
            }).GetType() == typeof(EnumSplitter));

            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.GETTER, new List <IDefinition> {
                new Variable()
            }).GetType() == typeof(Getter));
            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.SETTER, new List <IDefinition> {
                new Variable()
            }).GetType() == typeof(Setter));

            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.FUNCTION_CALL, new List <IDefinition> {
                new Function()
            }).GetType() == typeof(FunctionCall));

            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.IF, empty).GetType() == typeof(If));
            Assert.IsTrue(InstructionFactory.CreateInstruction(InstructionFactory.INSTRUCTION_ID.WHILE, empty).GetType() == typeof(While));
        }
Ejemplo n.º 13
0
 public List <byte> ExportEffect()
 {
     return(InstructionFactory.RunInstructionFactoryForNode(rootNode));
 }
Ejemplo n.º 14
0
 public void EmitNewArray(Type elementType)
 {
     Emit(InstructionFactory.GetFactory(elementType).NewArray());
 }
Ejemplo n.º 15
0
        public void Test_NormalInstructions()
        {
            var lst = new[] {
                InstructionFactory.Add(reg1, reg2),
                InstructionFactory.Add(reg1, constant),
                InstructionFactory.Sub(reg1, reg2),
                InstructionFactory.Sub(reg1, constant),
                InstructionFactory.Xor(reg1, reg2),
                InstructionFactory.Xor(reg1, constant),
                InstructionFactory.And(reg1, reg2),
                InstructionFactory.And(reg1, constant),
                InstructionFactory.Or(reg1, reg2),
                InstructionFactory.Or(reg1, constant),
                InstructionFactory.Test(reg1, reg2),
                InstructionFactory.Test(reg1, constant),

                InstructionFactory.Shl(reg1, constant),
                InstructionFactory.Shr(reg1, constant),

                InstructionFactory.Cmp(reg1, reg2),
                InstructionFactory.Cmp(reg1, constant),
                InstructionFactory.Cmp(constant, reg2),

                InstructionFactory.Mul(reg1),
                InstructionFactory.Div(reg1),
                InstructionFactory.Inc(reg1),
                InstructionFactory.Dec(reg1),
                InstructionFactory.Neg(reg1),
                InstructionFactory.Not(reg1),

                InstructionFactory.Call(fun),
                InstructionFactory.Call(reg1),
                InstructionFactory.Ret(),

                InstructionFactory.Pop(reg1),
                InstructionFactory.Push(reg1),

                InstructionFactory.Jmp(reg1),

                InstructionFactory.Cmove(reg1, reg2),
                InstructionFactory.Cmovg(reg1, reg2),
                InstructionFactory.Cmovge(reg1, reg2),
                InstructionFactory.Cmovl(reg1, reg2),
                InstructionFactory.Cmovle(reg1, reg2),
                InstructionFactory.Cmovne(reg1, reg2),

                InstructionFactory.Sete(reg1),
                InstructionFactory.Setg(reg1),
                InstructionFactory.Setge(reg1),
                InstructionFactory.Setl(reg1),
                InstructionFactory.Setle(reg1),
                InstructionFactory.Setne(reg1)
            };

            foreach (var insn in lst)
            {
                Assert.IsFalse(insn.IsCopyInstruction);
                Assert.IsFalse(insn.IsJumpInstruction);
                Assert.IsFalse(insn.IsLabel);
                Assert.IsNull(insn.Label);
            }
        }
Ejemplo n.º 16
0
 public void EmitDefaultValue(Type type)
 {
     Emit(InstructionFactory.GetFactory(type).DefaultValue());
 }
Ejemplo n.º 17
0
 public void Get_Exception_Instruction_Test()
 {
     IInstructionFactory instructionFactory = new InstructionFactory();
     var moveInstruction = instructionFactory.GetInstruction('I');
 }
        public LadderProgram ReadExecutable(string content, string projectName)
        {
            if (content.IndexOf("@laddermic.com") == -1)
            {
                throw new Exception("Executable has no Ladder content!");
            }

            OperationCode   opCode      = OperationCode.None;
            int             countOfEnds = 0;
            int             lineIndex   = 0;
            Address         address;
            AddressTypeEnum addressType;
            int             index = 0;


            LadderProgram program = new LadderProgram();

            program.Name   = projectName;
            program.device = DeviceFactory.CreateNewDevice();
            addressingServices.AlocateIOAddressing(program.device);
            addressingServices.AlocateAddressingMemoryAndTimerAndCounter(program, program.addressing.ListMemoryAddress, AddressTypeEnum.DigitalMemory, 10);
            addressingServices.AlocateAddressingMemoryAndTimerAndCounter(program, program.addressing.ListTimerAddress, AddressTypeEnum.DigitalMemoryTimer, 10);
            addressingServices.AlocateAddressingMemoryAndTimerAndCounter(program, program.addressing.ListCounterAddress, AddressTypeEnum.DigitalMemoryCounter, 10);
            lineIndex = program.InsertLineAtEnd(new Line());

            for (int position = content.IndexOf("@laddermic.com") + 15; position < content.Length; position++)
            {
                opCode = (OperationCode)Convert.ToChar(content.Substring(position, 1));

                switch (opCode)
                {
                case OperationCode.None:
                    countOfEnds++;
                    break;

                case OperationCode.LineEnd:
                    countOfEnds++;
                    if ((OperationCode)Convert.ToChar(content.Substring(position + 1, 1)) != OperationCode.None)
                    {
                        lineIndex = program.InsertLineAtEnd(new Line());
                    }
                    break;

                case OperationCode.NormallyOpenContact:
                case OperationCode.NormallyClosedContact:
                    countOfEnds = 0;
                    //Instruction instruction = new Instruction((OperationCode)opCode);
                    Instruction instruction = InstructionFactory.createInstruction(opCode);

                    addressType = (AddressTypeEnum)Convert.ToChar(content.Substring(position + 1, 1));
                    index       = (Int32)Convert.ToChar(content.Substring(position + 2, 1));
                    address     = addressingServices.Find(addressType, index);
                    if (address == null)
                    {
                        program.device.Pins[index - 1].Type = addressType;
                        addressingServices.RealocatePinAddressesByPinTypesFromDevice(program.device);
                        addressingServices.AlocateIOAddressing(program.device);
                        address = addressingServices.Find(addressType, index);
                    }
                    instruction.SetOperand(0, address);

                    position += 2;
                    program.Lines[lineIndex].Instructions.Add(instruction);
                    break;

                case OperationCode.OutputCoil:
                case OperationCode.Reset:
                    countOfEnds = 0;
                    {
                        InstructionList instructions = new InstructionList();
                        instructions.Add(InstructionFactory.createInstruction(opCode));
                        addressType = (AddressTypeEnum)Convert.ToChar(content.Substring(position + 1, 1));
                        index       = (Int32)Convert.ToChar(content.Substring(position + 2, 1));
                        address     = addressingServices.Find(addressType, index);
                        if (address == null)
                        {
                            program.device.Pins[index - 1].Type = addressType;
                            addressingServices.RealocatePinAddressesByPinTypesFromDevice(program.device);
                            addressingServices.AlocateIOAddressing(program.device);
                            address = addressingServices.Find(addressType, index);
                        }
                        instructions[instructions.Count - 1].SetOperand(0, address);
                        position += 2;
                        lineServices.InsertToOutputs(program.Lines[lineIndex], instructions);
                        instructions.Clear();
                    }
                    break;

                case OperationCode.ParallelBranchBegin:
                case OperationCode.ParallelBranchEnd:
                case OperationCode.ParallelBranchNext:
                    countOfEnds = 0;
                    program.Lines[lineIndex].Instructions.Add(InstructionFactory.createInstruction(opCode));
                    break;

                case OperationCode.Counter:
                    countOfEnds = 0;
                    {
                        InstructionList    instructions = new InstructionList();
                        CounterInstruction counter      = (CounterInstruction)InstructionFactory.createInstruction(opCode);
                        counter.SetAddress(addressingServices.Find(AddressTypeEnum.DigitalMemoryCounter, (Int32)Convert.ToChar(content.Substring(position + 1, 1))));
                        counter.setBoxType((int)Convert.ToChar(content.Substring(position + 2, 1)));
                        counter.setPreset((int)Convert.ToChar(content.Substring(position + 3, 1)));
                        instructions.Add(counter);
                        //instructions.Add(InstructionFactory.createInstruction(opCode));
                        //instructions[instructions.Count - 1].SetOperand(0, addressingServices.Find(AddressTypeEnum.DigitalMemoryCounter, (Int32)Convert.ToChar(content.Substring(position + 1, 1))));
                        //((Address)instructions[instructions.Count - 1].GetOperand(0)).Counter.Type = (Int32)Convert.ToChar(content.Substring(position + 2, 1));
                        //((Address)instructions[instructions.Count - 1].GetOperand(0)).Counter.Preset = (Int32)Convert.ToChar(content.Substring(position + 3, 1));

                        //instructions[instructions.Count - 1].SetOperand(1, ((Address)instructions[instructions.Count - 1].GetOperand(0)).Counter.Type);
                        //instructions[instructions.Count - 1].SetOperand(2, ((Address)instructions[instructions.Count - 1].GetOperand(0)).Counter.Preset);
                        position += 3;
                        lineServices.InsertToOutputs(program.Lines[lineIndex], instructions);
                        instructions.Clear();
                    }
                    break;

                case OperationCode.Timer:
                    countOfEnds = 0;
                    {
                        InstructionList instructions = new InstructionList();
                        instructions.Add(InstructionFactory.createInstruction(opCode));
                        instructions[instructions.Count - 1].SetOperand(0, addressingServices.Find(AddressTypeEnum.DigitalMemoryTimer, (Int32)Convert.ToChar(content.Substring(position + 1, 1))));
                        ((Address)instructions[instructions.Count - 1].GetOperand(0)).Timer.Type     = (Int32)Convert.ToChar(content.Substring(position + 2, 1));
                        ((Address)instructions[instructions.Count - 1].GetOperand(0)).Timer.TimeBase = (Int32)Convert.ToChar(content.Substring(position + 3, 1));
                        ((Address)instructions[instructions.Count - 1].GetOperand(0)).Timer.Preset   = (Int32)Convert.ToChar(content.Substring(position + 4, 1));

                        instructions[instructions.Count - 1].SetOperand(1, ((Address)instructions[instructions.Count - 1].GetOperand(0)).Timer.Type);
                        instructions[instructions.Count - 1].SetOperand(2, ((Address)instructions[instructions.Count - 1].GetOperand(0)).Timer.Preset);
                        instructions[instructions.Count - 1].SetOperand(4, ((Address)instructions[instructions.Count - 1].GetOperand(0)).Timer.TimeBase);

                        position += 4;
                        lineServices.InsertToOutputs(program.Lines[lineIndex], instructions);
                        instructions.Clear();
                    }
                    break;
                }

                /// end of codes
                if (countOfEnds >= 2)
                {
                    MicIntegrationServices p = new MicIntegrationServices();
                    //p.CreateFile("opcode.txt", content.Substring(content.IndexOf("@laddermic.com"), i - content.IndexOf("@laddermic.com") + 1));
                    //position = content.Length;
                    break;
                }
            }
            return(program);
        }
Ejemplo n.º 19
0
    // Start is called before the first frame update
    private void Start()
    {
        var cellBehaviorFirst = new Behavior("first");

        cellBehaviorFirst.Cycle
        .AddInstruction(
            InstructionFactory.InstanceRandomNear(cellBehaviorFirst))
        .EndCycle(false);
        Instantiator.InstantiateSim(cellBehaviorFirst, Vector3.zero);

        //PropertyTag amountTag = new PropertyTag("amount");

        //var food = new Behavior("food");

        //food.Properties.AddProperty(amountTag, 20);
        //food.Cycle
        //    .AddInstruction(InstructionFactory.PropIncrement(amountTag, 10))
        //    .AddInstruction(InstructionFactory.CtrlNextIf(
        //        (sim) =>
        //            sim.Behavior.Properties.GetPropertyValue(
        //                amountTag) < 100))
        //    .AddInstruction(InstructionFactory.CtrlCurrentToIndexRelative(3))
        //    .AddInstruction(InstructionFactory.InstanceRandomNear(food))
        //    .AddInstruction(InstructionFactory.PropIncrement(amountTag, -50))
        //    .AddInstruction(InstructionFactory.CtrlNextIf(
        //        (sim =>
        //            sim.Behavior.Properties.GetPropertyValue(
        //                amountTag) <= 0)))
        //    .AddInstruction(InstructionFactory.SelfDestruction())
        //    .EndCycle(true);


        //var eater = new Behavior("eater");
        //var healthTag = new PropertyTag("health");

        //eater.Properties.AddProperty(healthTag, 50);
        //eater.Cycle
        //    .AddInstruction((sim, cycle) =>
        //        sim.GetComponent<Rigidbody2D>()
        //            .AddForce(new Vector2(Random.Range(-1.0f, 1.0f),
        //                Random.Range(-1.0f, 1.0f)) * 50)
        //    )
        //    .AddInstruction(InstructionFactory.CtrlNextIf((sim =>
        //        sim.Behavior.Properties.GetPropertyValue(
        //            healthTag) < 100)))
        //    .AddInstruction(InstructionFactory.CtrlCurrentToIndexRelative(3))
        //    .AddInstruction(
        //        InstructionFactory.PropIncrement(healthTag, -50))
        //    .AddInstruction(InstructionFactory.InstanceRandomNear(eater))
        //    .EndCycle(true);

        //var table = new ReactionTable();
        //table.AddReaction(eater.Tag, food.Tag,
        //    new Simulation.MessageTag("collide"),
        //    (callerSim, receiverSim) =>
        //    {
        //        callerSim.Behavior.Properties.IncrementValue(healthTag, 10);
        //        receiverSim.Behavior.Properties.IncrementValue(amountTag, -20);
        //    });

        //food.Table = table;
        //eater.Table = table;

        //Instantiator.InstantiateSim(eater, Vector3.zero);
        //Instantiator.InstantiateSim(food, Vector3.zero);
    }