1. 程式人生 > >python井字棋算法及代碼

python井字棋算法及代碼

one 鍵盤輸入 有一個 通過 數字鍵盤 boa 簡便 oss range

井字棋盤看起來像一個大的井字符號(#),有9 個空格,可以包含X、O 或
關於落子問題
由於只能采用鍵盤輸入,所以需要對棋盤進行坐標表示;
即直接用1-9個9個數字來表示位置,
7|8|9
-+-+-
4|5|6
-+-+-
1|2|3
其索引順序與數字鍵盤上的數字鍵排列一致,下棋時看著數字鍵下,較為簡便。
計算機的算法--尋找最佳落子位置
首先簡單的將棋盤劃分為三個部分——中心(1),角(4),邊(4)。
中心雖然只有一個但卻不是最重要的,三個部分落子的優先順序依次為:角、中心、邊。
因此,井字棋的計算機算法計算最佳落子位置的順序如下:
1 直接落子獲勝
2 阻止玩家獲勝
3 在角上落子
4 在中心落子
5 在邊上落子

遊戲流程
1、開始
2、選子 X或者O
3、隨機先手
4、輪流下棋
5、是否分出勝負
5.1 分出勝負 跳到6
5.2 未分出勝負 跳到4
6、再來一局
6.1是, 跳到2
6.2否, 退出

遊戲代碼:
import random

def printBoard(borad):
print(borad[7] + ‘|‘ + borad[8] + ‘|‘ + borad[9])
print(‘-+-+-‘)
print(borad[4] + ‘|‘ + borad[5] + ‘|‘ + borad[6])
print(‘-+-+-‘)
print(borad[1] + ‘|‘ + borad[2] + ‘|‘ + borad[3])

‘‘‘printBoard 定義了棋盤打印輸出函數
與數字鍵盤排列一致‘‘‘

def inputPlayerLetter():
‘‘‘#讓玩家選擇棋子
返回一個列表,顯示玩家和電腦的棋子類型
‘‘‘
letter = ‘‘
while not (letter == ‘X‘ or letter == ‘O‘):
print(‘Do you want to be X or O?‘)
letter = input().upper()

if letter == ‘X‘:
    return [‘X‘, ‘O‘]
else:
    return [‘O‘, ‘X‘]

def whoGoesFirst():
‘‘‘隨機先手‘‘‘

if random.randint(0, 1) == 0:
return ‘Computer‘
else:
return ‘Player‘

def playAgain():
‘‘‘再玩一次?‘‘‘
print(‘Do you want to play again?(yes or no)‘)
return input().lower().startswith(‘y‘)

def makeMove(board, letter, move):
‘‘‘落子‘‘‘
board[move] = letter

def isWinner(board, occupy):

判斷是否獲勝

return ((board[1] == occupy and board[2] == occupy and board[3] == occupy) or
        (board[4] == occupy and board[5] == occupy and board[6] == occupy) or
        (board[7] == occupy and board[8] == occupy and board[9] == occupy) or
        (board[1] == occupy and board[4] == occupy and board[7] == occupy) or
        (board[2] == occupy and board[5] == occupy and board[8] == occupy) or
        (board[3] == occupy and board[6] == occupy and board[9] == occupy) or
        (board[1] == occupy and board[5] == occupy and board[9] == occupy) or
        (board[3] == occupy and board[5] == occupy and board[7] == occupy))

def getBoardCopy(board):

復制一份棋盤給電腦落子使用

depuBoard = []

for i in board:
    depuBoard.append(i)

return depuBoard

def isSpaceFree(board, move):

判斷這個位置是否有子,無子返回True

return board[move] == ‘ ‘

def getPlayerMove(board):
move = ‘ ‘
while move not in ‘1 2 3 4 5 6 7 8 9‘.split() or not isSpaceFree(board, int(move)):
print(‘What is your next move?(1-9)‘)
move = input()
return int(move)

def choosePossibleMoverFromList(board, moveList):

隨機返回一個可以落子的坐標,若無子可下,則返回None

possibleMoves = []
for i in moveList:
    if isSpaceFree(board, i):
        possibleMoves.append(i)

if len(possibleMoves) != 0:
    return random.choice(possibleMoves)
else:
    return None

def getComputerMove(board, computerLetter):

確定電腦的落子位置

if computerLetter == ‘X‘:
    playerLetter == ‘O‘
else:
    playerLetter == ‘X‘

‘‘‘先判斷電腦方能否通過一次落子直接獲得遊戲勝利‘‘‘
for i in range(1, 10):
    copy = getBoardCopy(board)
    if isSpaceFree(copy, i):
        makeMove(copy, computerLetter, i)
        if isWinner(copy, computerLetter):
            return i

‘‘‘判斷玩家下一次落子是否獲勝,若能,則再該點落子‘‘‘
for i in range(1, 10):
    copy = getBoardCopy(board)
    if isSpaceFree(copy, i):
        makeMove(copy, playerLetter, i)
        if isWinner(copy, playerLetter):
            return i

‘‘‘若角上能落子,則在角上落子‘‘‘
move = choosePossibleMoverFromList(board, [1, 3, 5, 7])

if move != None:
    return move

‘‘‘若中心能落子,則在中心落子‘‘‘
if isSpaceFree(board, 5):
    return 5

‘‘‘若邊上能落子,則在邊上落子‘‘‘
return choosePossibleMoverFromList(board, [2, 4, 6, 8])

def isBoardFull(board):
‘‘‘ 如果棋盤滿了,返回True‘‘‘
for i in range(1, 10):
if isSpaceFree(board, i):
return False
return True

print(‘Welcome to the TicTacToe game!‘)

while True:

update board

theBoard = [‘ ‘] * 10
playerLetter, computerLetter = inputPlayerLetter()

turn = whoGoesFirst()

print(‘The ‘ + turn + ‘ will go first.‘)

gameIsPlaying = True

while gameIsPlaying:
    if turn == ‘Player‘:
        # 玩家回合
        printBoard(theBoard)
        move = getPlayerMove(theBoard)
        makeMove(theBoard, playerLetter, move)

        if isWinner(theBoard, playerLetter):
            printBoard(theBoard)
            print(‘Wow!!!You win the game!!!‘)
            gameIsPlaying = False
        else:
            if isBoardFull(theBoard):
                printBoard(theBoard)
                print(‘The game is tie‘)
                break
            else:
                turn = ‘Computer‘

    else:
        # 電腦回合
        move = getComputerMove(theBoard, computerLetter)
        makeMove(theBoard, computerLetter, move)

        if isWinner(theBoard, computerLetter):
            printBoard(theBoard)
            print(‘Oh!,The computer win!,You lose.‘)
            gameIsPlaying = False
        else:
            if isBoardFull(theBoard):
                printBoard(theBoard)
                print(‘The game is tie‘)
                break
            else:
                turn = ‘Player‘

if not playAgain():
    break

python井字棋算法及代碼