簡體   English   中英

如何修復 Python 中的 while 循環

[英]How to fix a while loop in Python

我已經看到通常,當您在 while 循環中使用 while 時會發生錯誤,但是,這里不是這種情況,所以我正在尋求有關這個“常見”錯誤的幫助

以下部分代碼並不重要,可能你可以忽略它

crd = ['1 3', '2 3', '3 3', '1 2', '2 2', '3 2', '1 1', '2 1', '3 1']
inp = list(input('Enter cells:'))
wins = 0
result = False


def field(val):
    print('---------')
    for i in range(0, 9, 3):
        print('| ' + '{} {} {}'.format(val[i], val[i+1], val[i+2]).replace('_', ' ') + ' |')
    print('---------')


def win(con):
    global wins
    global result
    if inp[0] == '_':
        result = 'Impossible'
    else:
        win_con = [[con[i], con[i+1], con[i+2]] for i in range(0, 9, 3)] \
                + [[con[i], con[i+3], con[i+6]] for i in range(0, 3, 1)]\
                + [[con[0], con[4], con[8]], [con[2], con[4], con[6]]]

        for i in win_con:
            if (set(i) == {'X'} or set(i) == {'O'}) and wins == 1:
                result = 'Impossible'
            elif set(i) == {'X'}:
                result = 'X wins'
                wins = 1
            elif set(i) == {'O'}:
                result = 'O wins'
                wins = 1

        if result == False:
            try:
                inp.index('_')
                result = 'Game not finished'
            except:
                result = 'Draw'
    print(result)


field(inp)

波紋管是帶有返回無限循環錯誤的循環的代碼部分(據我所知,錯誤在 def move() 部分

def move():
    move = input('Enter the coordinates:').split(' ')
    while True:
        for n in move:
            if int(n) not in range(1, 4):
                print('Coordinates should be from 1 to 3!')
                move = input('Enter the coordinates:').split(' ')
                continue
            elif int(n) in range(1, 4):
                move = ' '.join(move)
                break


while True:
    move()
    position = [p for p, x in enumerate(crd) if x == move]
    int_pos = int("".join([str(p) for p in position]))

    if inp[int_pos] == '0' or inp[int_pos] == 'X':
        print('This cell is occupied! Choose another one!')
        move()
    elif inp[int_pos] == '_':
        inp[int_pos] = 'X'
        field(inp)
        win(inp)
    if result:
        break

不知何故,一旦我設法修復了無限循環錯誤,然而,發生了一個不同的問題 - 在檢查了第一對坐標(並顯示它們超出范圍)之后,它接受了新坐標對的輸入,但仍然繼續檢查已經檢查過的舊坐標對。

我的猜測是您正在使用 function 移動只是為了輸入有效的坐標
您可以將其簡化如下

def input_coordinates():
    while True:
        x, y = [int(i) for i in input('Enter the coordinates:').split(' ')]
        if (1 <= x < 4
              and 1 <= y < 4):
           return x, y
        # this will keep looping unless you get valid coordinates

然后你像這樣寫你的主要

while True:
    x, y = input_coordinates()
    move = "{} {}".format(x, y) # formatting the way you expect it.
    position = [p for p, x in enumerate(crd) if x == move]
    int_pos = int("".join([str(p) for p in position]))

    if inp[int_pos] == '0' or inp[int_pos] == 'X':
        print('This cell is occupied! Choose another one!')
        continue
    elif inp[int_pos] == '_':
        inp[int_pos] = 'X'
        field(inp)
        win(inp)
    if result:
        break
  1. 盡量避免全局變量,
  2. 你也有沖突,你有字符串和 function 兩者的名字都是“move”
  3. 您無需在原始 move() function 中再添加一次迭代( for n in move

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM