Last active
August 29, 2015 14:26
-
-
Save veryhappythings/3a16b2ae38646f6deb24 to your computer and use it in GitHub Desktop.
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 readchar | |
tape = bytearray([0]) | |
data_pointer = 0 | |
loop_buffer = '' | |
def state(): | |
print ''.join(['{0:03} '.format(i) for i in tape]) | |
for i in range(data_pointer): | |
print ' '*3, | |
print '^' | |
if loop_buffer: | |
print loop_buffer | |
def lookahead(program, instruction_pointer): | |
lookahead = instruction_pointer + 1 | |
depth = 1 | |
while True: | |
if program[lookahead] == '[': | |
depth += 1 | |
elif program[lookahead] == ']': | |
depth -= 1 | |
if depth == 0: | |
return lookahead | |
lookahead += 1 | |
if lookahead == len(program) + 1: | |
raise SyntaxError('Matching ] not found') | |
def lookback(program, instruction_pointer): | |
lookback = instruction_pointer - 1 | |
depth = 1 | |
while True: | |
if program[lookback] == '[': | |
depth -= 1 | |
elif program[lookback] == ']': | |
depth += 1 | |
if depth == 0: | |
return lookback | |
lookback -= 1 | |
if lookback < 0: | |
raise SyntaxError('Matching [ not found') | |
def interpret(program): | |
global data_pointer | |
instruction_pointer = 0 | |
while True: | |
char = program[instruction_pointer] | |
if char == '>': | |
data_pointer += 1 | |
if len(tape) == data_pointer: | |
tape.append(0) | |
if char == '<': | |
if data_pointer > 0: | |
data_pointer -= 1 | |
if char == '+': | |
tape[data_pointer] += 1 | |
if char == '-': | |
if tape[data_pointer] > 0: | |
tape[data_pointer] -= 1 | |
if char == '.': | |
print '{0:c}'.format(tape[data_pointer]) | |
if char == ',': | |
tape[data_pointer] = readchar.readchar() | |
if char == '[': | |
if tape[data_pointer] == 0: | |
instruction_pointer = lookahead(program, instruction_pointer) | |
if char == ']': | |
if tape[data_pointer] != 0: | |
instruction_pointer = lookback(program, instruction_pointer) | |
instruction_pointer += 1 | |
if len(program) == instruction_pointer: | |
break | |
def main(): | |
global loop_buffer | |
while True: | |
state() | |
char = readchar.readchar() | |
if char == 'q': | |
break | |
elif loop_buffer: | |
loop_buffer += char | |
opens = loop_buffer.count('[') | |
closes = loop_buffer.count(']') | |
if opens == closes: | |
print 'Loop:', loop_buffer | |
interpret(loop_buffer) | |
loop_buffer = '' | |
elif char == '[': | |
loop_buffer = char | |
else: | |
interpret(str(char)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment