Esempio n. 1
0
        public interpreter(string file)
        {
            if (file != "")
            {
                try
                {
                    string   pCode  = File.ReadAllText(file);
                    string[] pCodes = pCode.Split('\n');


                    for (int i = 0; i < pCodes.Length - 1; i++)
                    {
                        string      cl  = pCodes[i].Remove(pCodes[i].Length - 1);
                        string[]    ops = cl.Split(' ');
                        instruction ins = new instruction();
                        ins.oprc = (oprCode)Convert.ToInt32(ops[0]);
                        ins.fa   = Convert.ToInt32(ops[1]);
                        ins.la   = Convert.ToInt32(ops[2]);
                        code.Add(ins);
                    }
                }
                catch (IOException ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
Esempio n. 2
0
        private string pCodeFile()
        {
            try
            {
                FileInfo     fi       = new FileInfo(FilePath);
                int          lp       = fi.Name.LastIndexOf('.');
                string       CodeFile = fi.DirectoryName + "\\" + fi.Name.Substring(0, lp) + ".pCode";
                StreamWriter cwr      = File.CreateText(CodeFile);

                instruction ins = new instruction();
                for (int i = 0; i < Compiler.PCG.code.Count; i++)
                {
                    ins = Compiler.PCG.code[i];
                    string temp = ((int)ins.oprc).ToString() + " " + ins.fa.ToString() + " " + ins.la.ToString();
                    cwr.WriteLine(temp);
                }
                cwr.Close();
                return(CodeFile);
            }
            catch (IOException ex)
            {
                MessageBox.Show(ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return("");
            }
            finally
            {
            }
        }
    void find()
    {
        clothused = GameObject.FindWithTag("cloth");
        ObiCloth clothes = clothused.GetComponent <ObiCloth>();

        nowuse = clothused.GetComponent <instruction>();
        if (nowuse != null && clothes != null)
        {
            findflag = 1;
        }
    }
Esempio n. 4
0
        public void Read()
        {
            sr = new StreamReader(System.Environment.CurrentDirectory + "/bin/p_code.txt", Encoding.Default);
            string line = sr.ReadLine();

            while (line != null)
            {
                string[]    temp = line.Split(' ');
                instruction i    = new instruction();
                i.f = temp[0];
                i.l = int.Parse(temp[1]);
                i.a = int.Parse(temp[2]);
                code.Add(i);
                line = sr.ReadLine();
            }
        }
Esempio n. 5
0
 private void but_help_ItemClick(object sender, ItemClickEventArgs e)
 {
     if (uc_dp_di.Tag.ToString() == "wp")
     {
         instruction ins = new instruction();
         ins.navBarWp.IsExpanded  = true;
         ins.navBarWp2.IsSelected = true;
         ins.Show();
     }
     else
     {
         instruction ins = new instruction();
         ins.navBarDi.IsExpanded   = true;
         ins.navBarDer2.IsSelected = true;
         ins.Show();
     }
 }
Esempio n. 6
0
        public async Task Run()
        {
            List <instruction> input = (await File.ReadAllLinesAsync("inputs\\8.txt")).Select(x => new instruction(x)).ToList();

            cls_gameboy gmb = new cls_gameboy(input);

            Part1Answer = gmb.run_sim(true).ToString();

            for (int i = 0; i < input.Count(); i++)
            {
                instruction old = input[i];

                if (input[i].Command == Command.jmp)
                {
                    input[i] = new instruction(Command.nop, input[i].Value);
                }
                else if (input[i].Command == Command.nop)
                {
                    input[i] = new instruction(Command.jmp, input[i].Value);
                }
                else
                {
                    continue;
                }

                var acc = gmb.run_sim(false);
                if (acc != -1)
                {
                    Part2Answer = acc.ToString();
                    return;
                }
                else
                {
                    input[i] = old;
                    continue;
                }
            }
        }
Esempio n. 7
0
 _ => throw new WrongInstructionPassedException(instruction, nameof(ComparisonOperationInstruction)),
Esempio n. 8
0
 FormatMnemonic(instruction, output, FormatMnemonicOptions.None);
Esempio n. 9
0
 _ => throw new WrongInstructionPassedException(instruction, nameof(VariableInstruction)),
Esempio n. 10
0
 if (InstructionFullyContained(instruction, onCubes))
 {
     return(onCubes);
Esempio n. 11
0
        static void Main(string[] args)
        {
            Directory.SetCurrentDirectory(@"D:\projects\adventofcode\2020");

            var contents = System.IO.File.ReadAllLines("input/day08.data");

            instruction [] data = new instruction[contents.Length];
            int            i    = 0;

            foreach (var line in contents)
            {
                data[i] = new instruction(line);
                i++;
            }

            int  run = 0;
            int  ix  = 0;
            bool loop;
            int  acc;

            do
            {
                acc  = 0;
                loop = false;
                i    = 0;
                ix++;

                while (data[ix].op == "acc" && ix < data.Length ||
                       (data[ix].op == "nop" && data[ix].arg == 0))
                {
                    ix++;
                }

                if (data[ix].op != "nop")
                {
                    data[ix].op = "nop";
                }
                else
                {
                    data[ix].op = "jmp";
                }

                Console.WriteLine("Run: " + run + " ix: " + ix);
                do
                {
                    var ins = data[i];
                    if (ins.run > run)
                    {
                        loop = true;
                        break;
                    }

                    ins.run++;

                    switch (ins.op)
                    {
                    case "acc":
                        acc += ins.arg;
                        i++;
                        break;

                    case "jmp":
                        i += ins.arg;
                        break;

                    case "nop":
                        i++;
                        break;
                    }
                }while (i < contents.Length);

                if (data[ix].op != "nop")
                {
                    data[ix].op = "nop";
                }
                else
                {
                    data[ix].op = "jmp";
                }

                run++;
            }while (loop);

            Console.WriteLine("Answer: " + acc);
        }
Esempio n. 12
0
 var(instruction, instructionOffset) = pairs[i];
Esempio n. 13
0
        /// <summary>
        /// Get next instruction from list of bytes and extract push arguments if there are some.
        /// </summary>
        /// <param name="codeBytes">ByteQueue reference.</param>
        /// <param name="opcodeRet">Found instruction.</param>
        /// <param name="bytesRet">IEnumerable out param which is used to get the push arguments.</param>
        /// <returns>Result of operation</returns>
        public static bool GetOp(ref InstructionQueue codeBytes, out instruction opcodeRet, out byte[] bytesRet)
        {
            bytesRet = new byte[0];
            instruction opcode = opcodeRet = instruction.OP_INVALIDOPCODE;

            // Read instruction
            byte opVal = 0xff;
            if (!codeBytes.TryGet(ref opVal))
            {
                return false;
            }
            opcode = (instruction)opVal;

            // Immediate operand
            if (opcode <= instruction.OP_PUSHDATA4)
            {
                var szBytes = new byte[4] { 0, 0, 0, 0 }; // Zero length
                int nSize = 0;

                try
                {
                    if (opcode < instruction.OP_PUSHDATA1)
                    {
                        // Zero value instructions (OP_0, OP_FALSE)
                        nSize = (int) opcode;
                    }
                    else if (opcode == instruction.OP_PUSHDATA1)
                    {
                        // The next byte contains the number of bytes to be pushed onto the stack,
                        //    i.e. you have something like OP_PUSHDATA1 0x01 [0x5a]
                        nSize = codeBytes.Get();
                    }
                    else if (opcode == instruction.OP_PUSHDATA2)
                    {
                        // The next two bytes contain the number of bytes to be pushed onto the stack,
                        //    i.e. now your operation will seem like this: OP_PUSHDATA2 0x01 0x00 [0x5a]
                        nSize = BitConverter.ToInt16(codeBytes.Get(2), 0);
                    }
                    else if (opcode == instruction.OP_PUSHDATA4)
                    {
                        // The next four bytes contain the number of bytes to be pushed onto the stack,
                        //   OP_PUSHDATA4 0x01 0x00 0x00 0x00 [0x5a]
                        nSize = BitConverter.ToInt32(codeBytes.Get(4), 0);
                    }
                }
                catch (InstructionQueueException)
                {
                    // Unable to read operand length
                    return false;
                }

                if (nSize > 0)
                {
                    // Trying to read found number of bytes into list of OP_PUSHDATAn arguments.
                    if (!codeBytes.TryGet(nSize, ref bytesRet))
                    {
                        // Unable to read data
                        return false;
                    }
                }
            }

            opcodeRet = opcode;

            return true;
        }
Esempio n. 14
0
    public static void Main()
    {
        string line;

        Dictionary <char, int> register = new Dictionary <char, int>();

        register.Add('a', 0);
        register.Add('b', 0);
        register.Add('c', 0);
        register.Add('d', 0);
        register.Add('e', 0);
        register.Add('f', 0);
        register.Add('g', 0);
        register.Add('h', 0);

        instruction[] instructions = new instruction[32];
        int           i            = 0;

        System.IO.StreamReader file = new System.IO.StreamReader("input.txt");
        while ((line = file.ReadLine()) != null)
        {
            var splitLine = line.Split();
            instructions[i].command  = splitLine[0].ToString();
            instructions[i].register = splitLine[1].ToString();
            instructions[i].amount   = splitLine[2].ToString();
            i++;
        }

        int         currentNumber      = 0;
        instruction currentInstruction = instructions[currentNumber];
        int         currentAmount      = 0;
        int         multiplications    = 0;

        while (true)
        {
            if (currentNumber >= 32 || currentNumber < 0)
            {
                break;
            }

            currentInstruction = instructions[currentNumber];
            if (!Int32.TryParse(currentInstruction.amount, out currentAmount))
            {
                currentAmount = register[currentInstruction.amount[0]];
            }

            if (currentInstruction.command == "set")
            {
                register[currentInstruction.register[0]] = currentAmount;
            }
            else if (currentInstruction.command == "sub")
            {
                register[currentInstruction.register[0]] -= currentAmount;
            }
            else if (currentInstruction.command == "mul")
            {
                register[currentInstruction.register[0]] *= currentAmount;
                multiplications++;
            }
            else if (currentInstruction.command == "jnz")
            {
                if (currentInstruction.register == "1" || register[currentInstruction.register[0]] != 0)
                {
                    currentNumber += currentAmount - 1;
                }
            }
            else
            {
                Console.WriteLine("Unknown instruction {0}", currentInstruction.command);
                break;
            }

            currentNumber++;
        }

        Console.WriteLine(multiplications);
    }
        public async Task LoadSteps(string routineID, string taskID, int routineIdx, int taskIdx, string routineType)
        {
            var request = new HttpRequestMessage
            {
                RequestUri = new Uri("https://firestore.googleapis.com/v1/projects/project-caitlin-c71a9/databases/(default)/documents/users/" + uid + "/goals&routines/" + routineID + "/actions&tasks/" + taskID),
                Method     = HttpMethod.Get
            };
            var client = new HttpClient();
            HttpResponseMessage response = await client.SendAsync(request);

            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                HttpContent content         = response.Content;
                var         routineResponse = await content.ReadAsStringAsync();

                JObject stepJson = JObject.Parse(routineResponse);

                JToken jsonInstructionsAndSteps;
                try
                {
                    jsonInstructionsAndSteps = stepJson["fields"]["instructions&steps"]["arrayValue"]["values"];
                    if (jsonInstructionsAndSteps == null)
                    {
                        if (routineType == "routine")
                        {
                            App.User.routines[routineIdx].tasks[taskIdx].isSublistAvailable = false;
                        }
                        else
                        {
                            App.User.goals[routineIdx].actions[taskIdx].isSublistAvailable = false;
                        }
                        return;
                    }
                }
                catch
                {
                    //Console.WriteLine("Error with json action/task token:");
                    //Console.WriteLine(stepJson);
                    return;
                }

                int dbIdx_ = 0;
                foreach (JToken jsonIorS in jsonInstructionsAndSteps)
                {
                    try
                    {
                        JToken jsonMapIorS = jsonIorS["mapValue"]["fields"];

                        var isDeleted = false;
                        if (jsonMapIorS["deleted"] != null)
                        {
                            if ((bool)jsonMapIorS["deleted"]["booleanValue"])
                            {
                                isDeleted = true;
                            }
                        }

                        if ((bool)jsonMapIorS["is_available"]["booleanValue"] && !isDeleted)
                        {
                            bool isInProgressCheck = (jsonMapIorS["is_in_progress"] == null) ? false : (bool)jsonMapIorS["is_in_progress"]["booleanValue"];

                            if (routineType == "routine")
                            {
                                DateTime duration = DateTime.Parse(jsonMapIorS["expected_completion_time"]["stringValue"].ToString());

                                step step = new step
                                {
                                    title        = jsonMapIorS["title"]["stringValue"].ToString(),
                                    photo        = jsonMapIorS["photo"]["stringValue"].ToString(),
                                    isInProgress = isInProgressCheck &&
                                                   IsDateToday(jsonMapIorS["datetime_started"]["stringValue"].ToString()),
                                    isComplete = (bool)jsonMapIorS["is_complete"]["booleanValue"] &&
                                                 IsDateToday(jsonMapIorS["datetime_completed"]["stringValue"].ToString()) &&
                                                 !isInProgressCheck,
                                    dbIdx = dbIdx_,
                                    expectedCompletionTime = TimeSpan.Parse(jsonMapIorS["expected_completion_time"]["stringValue"].ToString()),
                                    dateTimeCompleted      = DateTime.Parse(jsonMapIorS["datetime_completed"]["stringValue"].ToString()).ToLocalTime(),
                                    availableStartTime     = TimeSpan.Parse(jsonMapIorS["available_start_time"]["stringValue"].ToString()),
                                    availableEndTime       = TimeSpan.Parse(jsonMapIorS["available_end_time"]["stringValue"].ToString())
                                };

                                ////Console.WriteLine("on Step: " + step.isComplete);

                                App.User.routines[routineIdx].tasks[taskIdx].steps.Add(step);
                            }
                            else if (routineType == "goal")
                            {
                                instruction instruction = new instruction
                                {
                                    title        = jsonMapIorS["title"]["stringValue"].ToString(),
                                    photo        = jsonMapIorS["photo"]["stringValue"].ToString(),
                                    isInProgress = isInProgressCheck &&
                                                   IsDateToday(jsonMapIorS["datetime_started"]["stringValue"].ToString()),
                                    isComplete = (bool)jsonMapIorS["is_complete"]["booleanValue"] &&
                                                 IsDateToday(jsonMapIorS["datetime_completed"]["stringValue"].ToString()) &&
                                                 !isInProgressCheck,

                                    dbIdx = dbIdx_,
                                    expectedCompletionTime = TimeSpan.Parse(jsonMapIorS["expected_completion_time"]["stringValue"].ToString()),
                                    dateTimeCompleted      = DateTime.Parse(jsonMapIorS["datetime_completed"]["stringValue"].ToString()).ToLocalTime(),
                                    availableStartTime     = TimeSpan.Parse(jsonMapIorS["available_start_time"]["stringValue"].ToString()),
                                    availableEndTime       = TimeSpan.Parse(jsonMapIorS["available_end_time"]["stringValue"].ToString())
                                };



                                App.User.goals[routineIdx].actions[taskIdx].instructions.Add(instruction);

                                ////Console.WriteLine("on Instruction: " + instruction.isComplete);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("{0} Exception caught.", e);
                    }
                    dbIdx_++;
                }
                if (routineType == "routine")
                {
                    if (App.User.routines[routineIdx].tasks[taskIdx].steps.Count == 0)
                    {
                        App.User.routines[routineIdx].tasks[taskIdx].isSublistAvailable = false;
                    }
                }
                else
                {
                    if (App.User.goals[routineIdx].actions[taskIdx].instructions.Count == 0)
                    {
                        App.User.goals[routineIdx].actions[taskIdx].isSublistAvailable = false;
                    }
                }
            }
        }
Esempio n. 16
0
 _ => throw new WrongInstructionPassedException(instruction, nameof(MemorySizeInstruction)),
Esempio n. 17
0
 _ => throw new WrongInstructionPassedException(instruction, nameof(UnaryOperationInstruction)),
Esempio n. 18
0
        /// <summary>
        /// Get the name of instruction
        /// </summary>
        /// <param name="opcode">Instruction</param>
        /// <returns>Instruction name</returns>
        public static string GetOpName(instruction opcode)
        {
            if (opcode == instruction.OP_0) // OP_0 and OP_FALSE are synonyms
                return "OP_0";
            if (opcode == instruction.OP_1) // OP_1 and OP_TRUE are synonyms
                return "OP_1";

            return Enum.GetName(typeof(instruction), opcode);
        }
Esempio n. 19
0
        /// <summary>
        /// Decode instruction to integer value
        /// </summary>
        /// <param name="opcode">Small integer instruction (OP_1_NEGATE and OP_0 - OP_16)</param>
        /// <returns>Small integer</returns>
        public static int DecodeOP_N(instruction opcode, bool AllowNegate = false)
        {
            // Only OP_n instructions are supported, throw exception otherwise.
            Contract.Requires<ArgumentException>((opcode == instruction.OP_1NEGATE && AllowNegate) || (opcode >= instruction.OP_0 && opcode <= instruction.OP_16), "Invalid integer instruction.");

            switch (opcode)
            {
                case instruction.OP_1NEGATE:
                    return -1;
                case instruction.OP_0:
                    return 0;
                default:
                    return (int)opcode - (int)(instruction.OP_1 - 1);
            }
        }
Esempio n. 20
0
        /// <summary>
        /// 解释器程序
        /// </summary>
        public void interpret()
        {
            int         p = 0;              //程序寄存器
            int         b = 1;              //基本寄存器
            int         t = 0;              //栈顶寄存器
            instruction i = new instruction();

            int [] s = new int [STACKSIZE];

            Console.WriteLine("Begin PL0");

            s[0] = s[1] = s[2] = s[3] = 0;
            do
            {
                i = code[p];
                p++;
                switch (i.f)
                {
                case fct.lit:
                    t    = t + 1;
                    s[t] = i.a;
                    break;

                case fct.opr:
                    switch (i.a)
                    {
                    case 0:
                        t = b - 1;                //返回
                        p = s[t + 3];
                        b = s[t + 2];
                        break;

                    case 1:
                        s[t] = -s[t];              //取反
                        break;

                    case 2:
                        t    = t - 1;                //加法
                        s[t] = s[t] + s[t + 1];
                        break;

                    case 3:
                        t    = t - 1;                //减法
                        s[t] = s[t] - s[t + 1];
                        break;

                    case 4:
                        t    = t - 1;                //乘法
                        s[t] = s[t] * s[t + 1];
                        break;

                    case 5:
                        t    = t - 1;                //除法
                        s[t] = s[t] / s[t + 1];
                        break;

                    case 6:
                        if (s[t] % 2 == 0)
                        {
                            s[t] = 0;
                        }
                        else
                        {
                            s[t] = 1;
                        }
                        break;

                    case 8:
                        t = t - 1;                   //下面都是判断
                        if (s[t] == s[t + 1])
                        {
                            s[t] = 1;
                        }
                        else
                        {
                            s[t] = 0;
                        }
                        break;

                    case 9:
                        t = t - 1;
                        if (s[t] == s[t + 1])
                        {
                            s[t] = 0;
                        }
                        else
                        {
                            s[t] = 1;
                        }
                        break;

                    case 10:
                        t = t - 1;
                        if (s[t] < s[t + 1])
                        {
                            s[t] = 1;
                        }
                        else
                        {
                            s[t] = 0;
                        }
                        break;

                    case 11:
                        t = t - 1;
                        if (s[t] >= s[t + 1])
                        {
                            s[t] = 1;
                        }
                        else
                        {
                            s[t] = 0;
                        }
                        break;

                    case 12:
                        t = t - 1;
                        if (s[t] > s[t + 1])
                        {
                            s[t] = 1;
                        }
                        else
                        {
                            s[t] = 0;
                        }
                        break;

                    case 13:
                        t = t - 1;
                        if (s[t] <= s[t + 1])
                        {
                            s[t] = 1;
                        }
                        else
                        {
                            s[t] = 0;
                        }
                        break;

                    case 14:

                        Console.WriteLine(s[t]);               //输出
                        t = t - 1;
                        break;

                    case 15:
                        Console.WriteLine();
                        break;

                    case 16:
                        t = t + 1;                          //输入
                        Console.Write("?");
                        string s_temp = Console.ReadLine();
                        s[t] = int.Parse(s_temp);
                        break;
                    }
                    break;

                case fct.lod:
                    t    = t + 1;
                    s[t] = s[Base(i.l, b, s) + i.a];
                    break;

                case fct.sto:
                    s[Base(i.l, b, s) + i.a] = s[t];
                    t = t - 1;
                    break;

                case fct.cal:
                    s[t + 1] = Base(i.l, b, s);
                    s[t + 2] = b;
                    s[t + 3] = p;
                    b        = t + 1;
                    p        = i.a;
                    break;

                case fct.ini:
                    t = t + i.a;
                    break;

                case fct.jmp:
                    p = i.a;
                    break;

                case fct.jpc:

                    if (s[t] == 0)
                    {
                        p = i.a;
                    }
                    t = t - 1;

                    break;
                }
            } while (p != 0);
            Console.WriteLine("PL0 END");
        }
Esempio n. 21
0
 encoder.AddModRMRegister(instruction, operand, regLo + 8, regLo + 8);
 _ => throw new WrongInstructionPassedException(instruction, nameof(ConversionOperatorInstruction)),
Esempio n. 23
0
 Write(ref instruction, operand, instructionOperand, numberFormatter, numberOptions, address, symbol, showSymbolAddress, true, false);