我已经看到,通常,在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)
Bellow是代码的一部分,带有返回无限循环的循环错误(据我所知,错误在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
以某种方式,即使我什至设法解决了无限循环错误,仍然出现了另一个问题-在检查了第一对坐标(并显示它们在范围之外)之后,输入了新的坐标对,但是仍然继续检查已经检查过的一对旧坐标。
我已经看到,通常在while循环内使用while时会发生错误,但是,在这里情况并非如此,因此我正在寻求有关此“常见”错误的帮助。 。
我猜你是在使用函数move只是为了输入有效的坐标您可以将其简化如下