最近编写了一个井字棋AI,命名为“洛书幻方”,用Python编的,结果有TypeError,求解决方法
代码:
def joiner(x: list, p: any):
x.append(p)
# --------------------------------------------------------------------
def win(s: list):
n: int = len(s)
if n < 3:
return False
s = sorted(s)
for i in range(n - 2):
lft = i + 1
rgt = n - 1
while lft < rgt:
total = s[i] + s[lft] + s[rgt]
if total == 15:
return True
elif total < 15:
lft = lft + 1
else:
rgt = rgt - 1
return False
WIN = 10
LOSE = -10
TIE = 0
INF = 1000
# 洛书幻方
MAGIC_SQUARE = [4, 9, 2,
3, 5, 7,
8, 1, 6]
def _eval(x, o):
if win(x):
return WIN
if win(o):
return LOSE
return TIE
def finished(x, o):
return len(x) + len(o) >= 9
def minmax(x, o, depth, maximize):
score = _eval(x, o)
if score == WIN:
return score - depth
if score == LOSE:
return score + depth
if finished(x, o):
return 0 # Draw
best = -INF if maximize else INF
for i in MAGIC_SQUARE:
if (i not in x) and (
i not in o):
if maximize:
best = max(
best,
minmax(
i + x,
o,
depth + 1,
not maximize))
else:
best = min(
best,
minmax(x,
i + o,
depth + 1,
not maximize))
def findbest(x, o, maximize):
best = -INF if maximize else INF
move = 0
for i in MAGIC_SQUARE:
if (i not in x) and (
i not in o):
if maximize:
val = minmax(
joiner(x, i), o,
0,
not maximize)
if val > best:
best = val
move = i
else:
val = minmax(
x, joiner(o, i),
0,
not maximize)
if val < best:
best = val
move = i
return move
def board(x, o):
for row in range(3):
print(" -----------")
for col in range(3):
p = MAGIC_SQUARE[
row * 3 + col]
if p in x:
print(" |X", end="")
elif p in o:
print(" |O", end="")
else:
print(" | ", end="")
print(" | ")
print(" -----------")
# Let's go!
def play():
print("A1 is 4, A2 is 9, A3 is 2, \n"
"B1 is 3, B2 is 5, B3 is 7, \n"
"C1 is 8, C2 is 1, C3 is 6. \n")
x = []
o = []
while not (win(x) or win(
o) or finished(x, o)):
board(x, o)
while True:
i = int(input("Please input your piece: "))
if (
i not in MAGIC_SQUARE) or (
MAGIC_SQUARE[i - 1] in x) or (
MAGIC_SQUARE[i - 1] in o):
print("Invalid move!!!!!!!!")
else:
x.append(MAGIC_SQUARE[i - 1])
break
o.append(findbest(x, o, False))
board(x, o)
if __name__ == '__main__':
play()
报错信息:
TypeError: object of type 'NoneType' has no len()