简体   繁体   English

如何修复 Python 中的 while 循环

[英]How to fix a while loop in Python

I've seen that usually, the mistake occurs when you use while inside of a while loop, however, it's not the case here, so I'm asking for help with this "common" mistake我已经看到通常,当您在 while 循环中使用 while 时会发生错误,但是,这里不是这种情况,所以我正在寻求有关这个“常见”错误的帮助

The following part of the code is not important, probably you can just ignore it以下部分代码并不重要,可能你可以忽略它

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)

Bellow is the part of the code with a loop that returns Infinite loop mistake (as far as I understood the mistake is in def move() part波纹管是带有返回无限循环错误的循环的代码部分(据我所知,错误在 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

Somehow, once I even managed to fix the infinite loop mistake, nevertheless, a different issue occurred - after checking the first pair of coordinates (and showing that they are out of range) It took input for new pair of coordinates but still proceed to check old pair of coordinates that were already checked.不知何故,一旦我设法修复了无限循环错误,然而,发生了一个不同的问题 - 在检查了第一对坐标(并显示它们超出范围)之后,它接受了新坐标对的输入,但仍然继续检查已经检查过的旧坐标对。

My guess is you are using function move just to input a valid coords right我的猜测是您正在使用 function 移动只是为了输入有效的坐标
you can simplify it as follows您可以将其简化如下

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

Then you write you main like this然后你像这样写你的主要

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. Try to avoid global variables,尽量避免全局变量,
  2. you also had a conflict you had string and function both with the name "move"你也有冲突,你有字符串和 function 两者的名字都是“move”
  3. you didn't need to add one more iteration ( for n in move ) in you original move() function您无需在原始 move() function 中再添加一次迭代( for n in move

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM