User:Feuermonster/Brainsembler
Jump to navigation
Jump to search
class Brainsembler { public static byte[] tape = new byte[30000]; public static int ptr = 15000; public static int i; public static System.Collections.Generic.List<int> labels_left = new System.Collections.Generic.List<int>(); public static System.Collections.Generic.List<int> labels_right = new System.Collections.Generic.List<int>(); public static void Main(string[] args) { if (args.Length < 1) { System.Console.WriteLine("brainsembler <file>"); } string code = System.IO.File.ReadAllText(args[0]); for (int j = 0; j < code.Length; j++) { switch (code[j]) { case '[': labels_left.Add(j); break; case ']': labels_right.Add(j); break; } } if (labels_left.Count != labels_right.Count) { System.Console.WriteLine("I'm pretty sure you forgot a '[' or a ']'!"); System.Environment.Exit(-1); } for(i=0;i<code.Length;i++) { switch (code[i]) { case '+': bfIncrement(); break; case '-': bfDecrement(); break; case '<': bfGoLeft(); break; case '>': bfGoRight(); break; case '[': bfBLeft(); break; case ']': bfBRight(); break; case '.': bfOut(); break; case ',': bfIn(); break; } } } public static void bfIncrement() { if (tape[ptr] == byte.MaxValue) tape[ptr] = 0; else tape[ptr]++; } public static void bfDecrement() { if (tape[ptr] == 0) tape[ptr] = byte.MaxValue; else tape[ptr]--; } public static void bfGoLeft() { if (ptr == 0) ptr = tape.Length - 1; else ptr--; } public static void bfGoRight() { if (ptr == tape.Length - 1) ptr = 0; else ptr++; } public static void bfBLeft() { if (tape[ptr] != 0) return; int f = -1; for (int q = 0; q < labels_left.Count; q++) { if (labels_left[q] == i) { f = q; break; } } i = labels_right[f]; } public static void bfBRight() { int f = -1; for (int q = 0; q < labels_right.Count; q++) { if (labels_right[q] == i) { f = q; break; } } i = labels_left[f]-1; } public static void bfOut() { System.Console.Write(((char)tape[ptr]).ToString()); } public static void bfIn() { tape[ptr] = (byte)System.Console.ReadKey().KeyChar; } }