留给机器学习的接口
"""
井字棋 Demo
无 Frame 版本
2021.11.8
"""
checkerboard = []
def ChangeCheckerBoard(movement, agent):
if checkerboard[movement] is not None:
raise ValueError("Movement must be empty!")
else:
checkerboard[movement] = agent
def isWin():
states = [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]
for state in states:
if checkerboard[state[0]] == checkerboard[state[1]] and checkerboard[state[1]] == checkerboard[state[2]] \
and checkerboard[state[0]] in ('O', 'X'):
return True
return False
def printCheckerBoard():
for i in range(9):
if checkerboard[i] is None:
print('■', end='\t')
else:
print(checkerboard[i], end='\t')
if (i + 1) % 3 == 0:
print('\n')
def renewTurn(turn):
if turn == 'O':
return 'X'
return 'O'
def ensureInput(section, remind, warning):
while True:
tem = input(remind)
if tem in section:
return tem
else:
print(warning)
def TrainAPI(board, movement, Turn):
"""
在训练代码中
记得调用isWin判断是否获胜
未获胜要调用renewTurn更新回合
"""
global checkerboard
checkerboard = board
new_move = movement
ChangeCheckerBoard(new_move, Turn)
def isEqual():
if None not in checkerboard:
return True
return False
if __name__ == '__main__':
while True:
checkerboard = [None for i in range(9)]
Turn = 'O'
while True:
new_move = ensureInput(('0', '1', '2', '3', '4', '5', '6', '7', '8'),
'请输入{}本次的移动坐标(0~8):'.format(Turn),
'移动坐标不规范!请重新输入!')
new_move = int(new_move)
ChangeCheckerBoard(new_move, Turn)
printCheckerBoard()
if isWin():
print('{}赢了!'.format(Turn))
break
if isEqual():
print('平局!')
break
Turn = renewTurn(Turn)
selection = ensureInput(('Yes', 'No'),
'想要再玩一盘吗?(Yes/No)',
'请输入Yes或No!')
if selection == 'No':
break
|