0

所以我正在尝试制作一个 Brainfuck 解释器,但是在我用来执行 Brainfuck 循环的 while 循环中,即使只有一个条件为真,它也会中断。

例子:

+++[>+<-]

应该导致:

[0, 3]

但是,当循环从 开始时[,它将创建一个新单元格,因此结构从[3][3, 0]。因此,当前的工作单元是0并且循环正在中断。但是,我只有在它是0并且当前字符是].

cells = [0] # Array of data cells in use
brainfuck = str(input("Input Brainfuck Code: ")) # Brainfuck code
workingCell = 0 # Data pointer position
count = 0 # Current position in code
def commands(command):
    global cells
    global workingCell
    if command == ">":
        workingCell += 1
        if workingCell > len(cells) - 1:
            cells.append(0)
    elif command == "<":
        workingCell -= 1
    elif command == "+":
        cells[workingCell] += 1
    elif command == "-":
        cells[workingCell] -= 1
    elif command == ".":
        print(chr(cells[workingCell]))
    elif command == ",":
        cells[workingCell] = int(input("Input: "))
def looper(count):
    global cells
    global workingCell
    print("START LOOP", count)
    count += 1
    looper = loopStart = count
    while brainfuck[looper] != "]" and cells[workingCell] != 0: # This line is causing trouble
        if brainfuck[looper] == "]":
            looper = loopStart
        commands(brainfuck[looper])
        count += 1
        looper += 1
    return count
while count < len(brainfuck):
    if brainfuck[count] == "[":
        count = looper(count)
        print("END LOOP", count)
    else:
        commands(brainfuck[count])
    count += 1

先感谢您。

4

1 回答 1

1

我只有在它是0并且当前角色是时才打破它]

如果这就是你想要的,那你的逻辑就while错了。它应该是:

while not (brainfuck[looper] == "]" and cells[workingCell] == 0):

并且根据德摩根定律,当您分布 时notand您将每个条件反转并更改andor,因此它应该是:

while brainfuck[looper] != "]" or cells[workingCell] != 0:

如果这令人困惑,你可以写:

while True:
    if brainfuck[looper] == "]" and cells[workingCell] == 0:
        break

这完全反映了您在描述中所说的内容。

于 2016-11-07T23:13:25.437 回答