Execute Brain****/Python

From Rosetta Code
Revision as of 04:32, 7 January 2009 by rosettacode>Iswm (New page: {{implementation|Brainf***}}{{collection|RCBF}}Category:Python Quick implementation of a Brainfuck interpreter in Python. <python> #!/usr/bin/python from __future__ import with_...)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Execute Brain****/Python is an implementation of Brainf***. Other implementations of Brainf***.
Execute Brain****/Python is part of RCBF. You may find other members of RCBF at Category:RCBF.

Quick implementation of a Brainfuck interpreter in Python.

<python>

  1. !/usr/bin/python

from __future__ import with_statement

import sys

class BrainFuck():

   def __init__(self):
       self.instructions = []
   
   def main(self):
       if len(sys.argv[1]) > 0:
           source_file = sys.argv[1]
           with open(source_file) as source_handle:
               self.instructions = [char for char in source_handle.read()]
       else:
           print 'No source file.'
           sys.exit(2)
       
       self.match_braces()
   
   def match_braces(self):
       loops = {}
       loop_stack = {}
       lsptr = 0
       ptr = 0
       
       for instruction in self.instructions:
           if instruction == '[':
               loop_stack[lsptr] = ptr
               lsptr += 1
           elif instruction == ']':
               lsptr -= 1
               startptr = loop_stack[lsptr]
               loops[startptr] = ptr
               loops[ptr] = startptr
           
           ptr += 1
       
       self.start_interpreting(loops)
   
   def start_interpreting(self, loops):
       tape = [0 for x in range(0, 30000)]
       cell = 0
       pointer = 0
       
       while True:
           if pointer > len(self.instructions) - 1:
               break
               
           instruction = self.instructions[pointer]
           
           if instruction == '>':
               cell += 1
           elif instruction == '<':
               cell -= 1
           elif instruction == '+':
               tape[cell] += 1
           elif instruction == '-':
               tape[cell] -= 1
           elif instruction == ',':
               tape[cell] = ord(sys.stdin.read(1))
           elif instruction == '.':
               sys.stdout.write(chr(tape[cell]))
           elif instruction == '[' and tape[cell] == 0:
               pointer = loops.get(pointer)
           elif instruction == ']' and tape[cell] != 0:
               pointer = loops.get(pointer)
           
           pointer += 1
           

if __name__ == "__main__":

   interpreter = BrainFuck()
   interpreter.main()

</python>