自己写的控制台可视化
'''Custom'''
VISUALIZE=True #It will be much slower if U visualize the process
bfcode='''
>>>>>>>>>>>>>.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++.[-,<+.]
'''
from array import array
import sys,os
def cmd_filter(bfcode):
executable_cmd=''
for c in bfcode:
if c in '+-<>,.[]':
executable_cmd+=c
return executable_cmd
def get_loops(command):
d={}
loop_heap=[]
for i in range(len(command)):
if command[i]=='[':
loop_heap.append(i)
elif command[i]==']':
start=loop_heap.pop()
d[start]=i
d[i]=start
return d
def extend(tape):
for i in range(256):
tape.append(0)
command=cmd_filter(bfcode)
tape=array('H')
extend(tape)
cmd_pointer=0
tape_pointer=0
loop_dict=get_loops(command)
output_stream=''
input_stream=''
input_at=0
def run():
global cmd_pointer,tape_pointer,input_stream,output_stream,input_at
cmd=command[cmd_pointer]
if cmd=='+':
tape[tape_pointer]+=(1 if tape[tape_pointer]!=255 else -255)
elif cmd=='-':
tape[tape_pointer]-=(1 if tape[tape_pointer]!=0 else -255)
elif cmd=='<':
tape_pointer-=1
if tape_pointer<0:
return True
elif cmd=='>':
tape_pointer+=1
if tape_pointer>=len(tape):
extend(tape)
elif cmd==',':
if len(input_stream)<=input_at:
temp=''
while not temp:
temp=input('Too Short Input Stream! Extends(~~Number or string):')
if temp[:2]=='~~':
input_stream+=chr(int(temp[2:]))
else:
input_stream+=temp
tape[tape_pointer]=ord(input_stream[input_at])
input_at+=1
elif cmd=='.':
output_stream+=chr(tape[tape_pointer])
elif cmd=='[':
if not tape[tape_pointer]:
cmd_pointer=loop_dict[cmd_pointer]
elif cmd==']':
if tape[tape_pointer]:
cmd_pointer=loop_dict[cmd_pointer]
watch_pointer=0
def visualize():
global watch_pointer
os.system('cls')
print('MEMORY:',end=' ')
if watch_pointer+32>=len(tape):
extend(tape)
for i in range(watch_pointer,watch_pointer+32):
if i==tape_pointer:
print('\033[4m%d\033[0m'%tape[i],end=' ')
else:
print(tape[i],end=' ')
print(' watching:%i pointer:%i\n'%(watch_pointer,tape_pointer))
print('COMMANDS:',end=' ')
if cmd_pointer<32:
for i in range(64):
if i>=len(command):
break
if i==cmd_pointer:
print('\033[4m%c\033[0m'%command[i],end='')
else:
print(command[i],end='')
else:
for i in range(cmd_pointer-32,cmd_pointer+32):
if i>=len(command):
break
if i==cmd_pointer:
print('\033[4m%c\033[0m'%command[i],end='')
else:
print(command[i],end='')
print(' excuting:%i\n'%cmd_pointer)
print('Input Stream:',end=' ')
for i in range(len(input_stream)):
if i==input_at:
print('\033[4m%c\033[0m'%input_stream[i],end='')
else:
print(input_stream[i],end='')
print()
print('OutPut Stream:',output_stream)
help=input('--next->')
if help=='>':
watch_pointer+=16
elif help=='<':
watch_pointer-=16
if watch_pointer<0:
watch_pointer=0
stop=False
while not stop:
stop=run()
if VISUALIZE:
visualize()
cmd_pointer+=1
if cmd_pointer>=len(command):
break