Execute Brain****/Python: Difference between revisions
Content added Content deleted
(New page: {{implementation|Brainf***}}{{collection|RCBF}}Category:Python Quick implementation of a Brainfuck interpreter in Python. <python> #!/usr/bin/python from __future__ import with_...) |
No edit summary |
||
Line 12: | Line 12: | ||
class BrainFuck(): |
class BrainFuck(): |
||
def __init__(self): |
def __init__(self): |
||
self.instructions = |
self.instructions = '' |
||
def main(self): |
def main(self): |
||
if len(sys.argv[1]) > 0: |
if len(sys.argv[1:]) > 0: |
||
source_file = sys.argv[1] |
source_file = sys.argv[1] |
||
with open(source_file) as source_handle: |
with open(source_file) as source_handle: |
||
self.instructions = |
self.instructions = source_handle.read() |
||
else: |
else: |
||
print 'No source file.' |
print >> sys.stderr, 'No source file.' |
||
sys.exit(2) |
sys.exit(2) |
||
Line 27: | Line 27: | ||
def match_braces(self): |
def match_braces(self): |
||
loops = {} |
loops = {} |
||
loop_stack = |
loop_stack = [] |
||
lsptr = 0 |
|||
ptr = 0 |
|||
for instruction in self.instructions: |
for ptr, instruction in enumerate(self.instructions): |
||
if instruction == '[': |
if instruction == '[': |
||
loop_stack |
loop_stack.append(ptr) |
||
lsptr += 1 |
|||
elif instruction == ']': |
elif instruction == ']': |
||
startptr = loop_stack.pop() |
|||
startptr = loop_stack[lsptr] |
|||
loops[startptr] = ptr |
loops[startptr] = ptr |
||
loops[ptr] = startptr |
loops[ptr] = startptr |
||
ptr += 1 |
|||
self.start_interpreting(loops) |
self.start_interpreting(loops) |
||
def start_interpreting(self, loops): |
def start_interpreting(self, loops): |
||
tape = [0 |
tape = [0] * 30000 |
||
cell = 0 |
cell = 0 |
||
pointer = 0 |
pointer = 0 |
||
while |
while pointer < len(self.instructions): |
||
if pointer > len(self.instructions) - 1: |
|||
break |
|||
instruction = self.instructions[pointer] |
instruction = self.instructions[pointer] |
||
Line 69: | Line 60: | ||
sys.stdout.write(chr(tape[cell])) |
sys.stdout.write(chr(tape[cell])) |
||
elif instruction == '[' and tape[cell] == 0: |
elif instruction == '[' and tape[cell] == 0: |
||
pointer = loops |
pointer = loops[pointer] |
||
elif instruction == ']' and tape[cell] != 0: |
elif instruction == ']' and tape[cell] != 0: |
||
pointer = loops |
pointer = loops[pointer] |
||
pointer += 1 |
pointer += 1 |