仍在使用Connect 4,我遇到了AI问题。我一直在使用与用于胜利检查的函数相同的函数,但是我得到了无限循环或者代码根本无效。
这是函数
def AIhor(array):
global blockwin
for x in range(0, 6):
x = array[x]
for y in range(1, 5):
if x[y] in ("@", "#"):
if ((x[y] == x[y + 1]) and x[y] == x[y + 2]) and (x[y + 3] == "O"):
return True
blockwin = y + 3
break
elif ((x[y] == x[y + 1]) and (x[y] == x[y + 3]) and (x[y + 2] == "O")):
return True
blockwin = y + 2
break
elif ((x[y] == x[y + 2]) and (x[y] == x[y + 3]) and (x[y + 2] == "O")):
return True
blockwin = y + 1
break
elif ((x[y + 1] == x[y + 2]) and (x[y + 1] == x[y + 3]) and (x[y] == "O")):
return True
blockwin = y
break
else:
if (x == 5 and y == 4):
return False
break
这是函数调用:
g = ['A', 'O', 'O', 'O', 'O', 'O', 'O', 'O']
h = ['B', 'O', 'O', 'O', 'O', 'O', 'O', 'O']
i = ['C', 'O', 'O', 'O', 'O', 'O', 'O', 'O']
j = ['D', 'O', 'O', 'O', 'O', 'O', 'O', 'O']
k = ['E', 'O', 'O', 'O', 'O', 'O', 'O', 'O']
l = ['F', 'O', 'O', 'O', 'O', 'O', 'O', 'O']
m = [' ', '1', '2', '3', '4', '5', '6', '7']
a = g
b = h
c = i
d = j
e = k
f = l
n = m
afortests = [a, b, c, d, e, f]
if AIhor(afortests):
player2choice = blockwin
else:
player2choice = random.randint(1, 7)
答案 0 :(得分:0)
“代码无效”是不有用的错误报告。发生了什么不应该,或者不应该发生什么?
但我可以马上告诉你,你有大量的代码行永远不会被执行。在每个if
语句中,您有一个return
,后跟一些其他代码。但是其他代码永远不会被执行,因为返回正是它所说的并且直接返回。在同一个块中的代码根本无法访问,blockwin
将不会被修改。