抱歉我的英语不好......
我想在python中创建brainfuck解释器 - 我有这个:
defaulttyp, defaultval = False, ""
def split_word(word):
word_split = []
word2 = word.split()
for x in word2:
word_split.extend(x)
return word_split
def Brainfuck(inputlist, is_it_loop, value):
in_loop = []
output = []
values = []
pos = 0
selected = 0
for char in inputlist:
if char == "+":
if (len(values) - 1) < selected:
values.append(0)
values[selected] += 1
elif char == "-":
if (len(values) - 1) < selected:
values.append(0)
values[selected] -= 1
elif char == ">":
selected += 1
if len(values) < selected:
values.append(0)
elif char == "<":
selected -= 1
elif char == ".":
print(''.join(chr(values[selected])))
elif char == "[":
while char != "]":
if char == "+":
in_loop.append("+")
elif char == "-":
in_loop.append("-")
elif char == ">":
in_loop.append(">")
elif char == "<":
in_loop.append("<")
elif char == ".":
in_loop.append(".")
elif char == "[":
in_loop.append("[")
elif char == "]":
in_loop.append("]")
elif char == ",":
in_loop.append(",")
while value != 0:
Brainfuck(in_loop, True, value)
elif char == ",":
inp = input("")
input1 = split_word(inp)
if len(input1) > 1:
continue
else:
values[selected] = ord(inp)
if ((is_it_loop == True) and (values[selected] == 0)):
value = 0
pos += 1
#################################################################################################################
code = split_word('''
++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.
''')
Brainfuck(code, defaulttyp, defaultval)
但是有些不对劲或者idk和程序让我写下我想要的东西(作为输入)并且它没有做任何事情 - 如果我停止它,它给了我这个:
Traceback (most recent call last):
File "/Users/jan/PycharmProjects/BrainfuckInPython/Brainfuck.py", line 79, in <module>
Brainfuck(code, defaulttyp, defaultval)
File "/Users/jan/PycharmProjects/BrainfuckInPython/Brainfuck.py", line 52, in Brainfuck
in_loop.append("[")
KeyboardInterrupt
Process finished with exit code 1
谁能告诉我,什么是错的以及如何解决这个问题?谢谢 - 希望这不是像以前那样的愚蠢问题......
好的,这是该程序的正常版本:
def UBF(code):
SBF(code, 0, 0, [0])
def SBF(code, start, memoryStart, memory):
position_in_memory = memoryStart
position_in_code = start
while position_in_code < len(code):
char = code[position_in_code]
if char == '.':
print(chr(memory[position_in_memory]), end='')
elif char == ',':
inp = input('Zadejte znak: ')
memory[position_in_memory] = ord(inp)
elif char == '+':
memory[position_in_memory] += 1
elif char == '-':
memory[position_in_memory] -= 1
elif char == '>':
position_in_memory += 1
if len(memory) <= position_in_memory:
memory.append(0)
elif char == '<':
position_in_memory -= 1
elif char == '[':
position_in_code = SBF(code, position_in_code + 1, position_in_memory, memory)
elif char == ']':
if memory[position_in_memory] == 0:
return position_in_code
else:
position_in_code = start
continue
position_in_code += 1