31. ? isWinner(bo, c)自訂函式用來檢查是否連線,有連線時回傳 True
? bo 井字棋對奕資料
? c 為棋子符號,'X'代表玩家,'O'代表電腦
def isWinner(bo, c):
return (bo[1]==bo[2]==bo[3]==c) or (bo[4]==bo[5]==bo[6]==c) or
(bo[7]==bo[8]==bo[9]==c) or (bo[1]==bo[4]==bo[7]==c) or
(bo[2]==bo[5]==bo[8]==c) or (bo[3]==bo[6]==bo[9]==c) or
(bo[1]==bo[5]==bo[9]==c) or (bo[3]==bo[5]==bo[7]==c)
? isBoardFull(bo)自訂函式用來檢查井字棋是否填滿了
def isBoardFull():
return board.count(' ') == 1 #只剩?個空格時(元素0),表示棋盤已填滿
? selectRandom(li)自訂函式用來自li串列中隨機挑選?個元素值
def selectRandom(li):
r = random.randrange(0, len(li))
return li[r]
應用實例:井字棋遊戲 3/8
32. ? playerTurn()自訂函式為玩家回合處理作業,若玩家輸入的棋盤位
置編號為空格則落子'X',否則重新輸入
def playerTurn():
while True:
try:
move = int(input('Select a position to place an 'X' (1-9): '))
if move > 0 and move < 10:
if (board[move] == ' '):
board[move] = 'X'
break
else:
print('Sorry, this space is occupied!')
else:
print('Please type a number within the range!')
except:
print('Please type a number!')
printBoard() #顯示棋盤目前結果
應用實例:井字棋遊戲 4/8
1 2 3
4 5 6
7 8 9
33. ? evaluateMove()自訂函式為電腦回合計算最佳落子位置
? 落子優先序:連線決勝點、阻斷對手連線點、四個角落、中間、四個邊
def evaluateMove():
candiate = tuple([x for x, c in enumerate(board) if c == ' ' and x != 0])
for let in ('O', 'X'): #檢查決勝點及阻斷對手決勝點
for i in candiate :
boardCopy = board[:] #複製棋盤以便測試
boardCopy[i] = let
if isWinner(boardCopy, let):
return i
cornersOpen = []
for i in candiate :
if i in (1, 3, 7, 9):
cornersOpen.append(i)
if len(cornersOpen) > 0: #選擇四個角落位置
return selectRandom(cornersOpen)
應用實例:井字棋遊戲 5/8
34. if 5 in candiate: #選擇中間位置
return 5
edgesOpen = []
for i in candiate:
if i in (2, 4, 6, 8):
edgesOpen.append(i)
if len(edgesOpen) > 0: #選擇四邊位置
return selectRandom(edgesOpen)
? computerTurn()自訂函式為電腦回合處理作業
def computerTurn():
move = evaluateMove()
board[move] = 'O'
print('Computer placed an 'O' in position', move)
printBoard() #顯示棋盤目前結果
應用實例:井字棋遊戲 6/8
35. ? game()自訂函式為遊戲流程控制作業
def game(turn):
while True:
if (turn):
playerTurn() #玩家回合
turn = 1 - turn #換手
if isWinner(board, 'X'):
print('You won this time!')
break;
else:
computerTurn() #電腦回合
turn = 1 - turn #換手
if isWinner(board, 'O'):
print('Computer won this time!')
break;
if isBoardFull():
print('Tie Game!')
break;
應用實例:井字棋遊戲 7/8
36. ? 程式主流程
while True:
print('Welcome to Tic Tac Toe!', end = ', ')
turn = random.randint(0, 9) % 2 #隨機決定先手,0電腦, 1玩家
if (turn == 1):
print('玩家先下')
printBoard() #畫出空棋盤
else:
print('電腦先下')
game(turn)
answer = input('Do you want to play again? (Y/N)')
if answer.lower() == 'y' or answer.lower == 'yes':
board = [' ' for x in range(10)]
print('-----------------------------------')
else:
break
應用實例:井字棋遊戲 8/8