2016-11-07 55 views
0

所以我試圖做一個Brainfuck解釋器,但是在我用來執行Brainfuck循環的while循環中,即使只有一個條件是真正。即使只有1個變量爲真,循環也會停止

實施例:

+++[>+<-] 

應導致:

[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 

在此先感謝您。

+0

+++ [> + <-]' ->'[0,3]'背後的邏輯是什麼? –

+5

*「不要打印所有的打印報告」* - 不,它的作用之一就是將代碼縮小到[mcve],而不是像現在這樣將其轉儲到我們的上面。 – jonrsharpe

+2

你正在爲一個函數和一個變量使用同一個名字?!? –

回答

1

我如果是0和當前字符是]

如果這是你想要的,你有你的while錯誤的邏輯,只有打破。它應該是:

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

而且根據deMorgan's Laws,當你發佈notand,您反轉每個條件,改變andor,所以它應該是:

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

如果這是令人困惑的,你可以寫:

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

這反映了你在說明中說的正好。

相關問題