Created
April 21, 2015 07:34
-
-
Save kdelwat/db2d6c036f95c33a4b28 to your computer and use it in GitHub Desktop.
BF interpreter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
#read Brainfuck from file and filter | |
filename = sys.argv[1] | |
with open(filename) as f: | |
bf = f.read() | |
legal = set('><+-.,[]') | |
bf = ''.join(c for c in bf if c in legal) | |
print(bf) | |
#set index (current cell), array (memory), and ipointer(command pointer) | |
index = 0 | |
array = [0] * 100 | |
ipointer = 0 | |
def right(): | |
global index | |
global ipointer | |
index += 1 | |
ipointer += 1 | |
def left(): | |
global index | |
global ipointer | |
index -= 1 | |
ipointer += 1 | |
def increment(): | |
global array | |
global index | |
global ipointer | |
array[index] += 1 | |
ipointer += 1 | |
def decrement(): | |
global array | |
global index | |
global ipointer | |
if array[index] == 0: | |
array[index] = 255 | |
else: | |
array[index] -= 1 | |
ipointer += 1 | |
def output(): | |
global array | |
global index | |
global ipointer | |
sys.stdout.write(chr(array[index])) | |
ipointer += 1 | |
def accept(): | |
global array | |
global index | |
global ipointer | |
inv = ord(sys.stdin.read(1)) | |
print(inv) | |
array[index] = inv | |
ipointer += 1 | |
def openloop(): | |
global array | |
global index | |
global ipointer | |
global bf | |
if array[index] == 0: | |
nest = 1 | |
while nest != 0: | |
ipointer += 1 | |
if bf[ipointer] == "]": | |
nest -= 1 | |
elif bf[ipointer] == "[": | |
nest += 1 | |
ipointer += 1 | |
else: | |
ipointer += 1 | |
def closeloop(): | |
global array | |
global index | |
global ipointer | |
global bf | |
if array[index] != 0: | |
nest = 1 | |
while nest != 0: | |
ipointer -= 1 | |
if bf[ipointer] == "[": | |
nest -= 1 | |
elif bf[ipointer] == "]": | |
nest += 1 | |
else: | |
ipointer += 1 | |
commandmap = {'<':left, | |
'>':right, | |
'+':increment, | |
'-':decrement, | |
'.':output, | |
',':accept, | |
'[':openloop, | |
']':closeloop | |
} | |
counter = 0 | |
while ipointer < len(bf) and counter < 1000: | |
commandmap[bf[ipointer]]() | |
counter += 1 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment