您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關使用python怎么實現一個井字棋游戲,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
使用python實現井字棋游戲,沒有具體算法,只是用隨機下棋簡單實現:
import random board = [['+','+','+'],['+','+','+'],['+','+','+']] def ma(board): if isempty(board): a = random.randint(0, 2) b = random.randint(0, 2) if board[a][b] != 'X' and board[a][b] != 'O': print("機器走:") board[a][b] = 'O' oput(board) else: ma(board) else: print("平局") def oput(board): print(" 0 1 2") for i in range(3): print(i, end=' ') for j in range(3): print(board[i][j], end=" ") print("") def winput(i,j): if board[i][j] == 'X': print("human win") else: print("machine win") return 1 def test(board): for i in range(3): for j in range(3): if board[i][j] != '+': if j == 0: if board[i][j] == board[i][j + 1] == board[i][j + 2]: return winput(i,j) if i == 0: if board[i][j] == board[i + 1][j] == board[i + 2][j]: return winput(i,j) if i == 0 and j == 0: if board[i][j] == board[i + 1][j + 1] == board[i + 2][j + 2]: return winput(i,j) if i == 2 and j == 0: if board[i][j] == board[i - 1][j + 1] == board[i - 2][j + 2]: return winput(i,j) def isempty(board): for i in range(3): for j in range(3): if board[i][j] == '+': return True return False def main(): print("初始棋盤:") oput(board) flag = 0 t = input("human first? Y/N human for X, machine for O\n") if t == 'Y': while isempty(board): print("人走: ") a, b = map(int, input("輸入落子縱橫坐標: a,b \n").split(',')) if board[a][b] == '+': board[a][b] = 'X' oput(board) flag = test(board) if flag == 1: break else: print("落子位置不對") continue ma(board) flag = test(board) if flag == 1: break if isempty(board) == 0 and flag == 0: print("平局") break elif t == 'N': while isempty(board): ma(board) flag = test(board) if isempty(board) == 0 and flag == 0: print("平局") break if flag == 1: break print("人走: ") a, b = map(int, input("輸入落子縱橫坐標: a,b \n").split(',')) if board[a][b] == '+': board[a][b] = 'X' oput(board) flag = test(board) if flag == 1: break else: print("落子位置不對") continue if __name__ == "__main__": main()
結果:
關于使用python怎么實現一個井字棋游戲就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。