python實現簡單的井字棋
更新時間:2021年05月26日 08:35:52 作者:哈爾的心
這篇文章主要為大家詳細介紹了python實現簡單的井字棋,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了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常見讀寫文件操作實例總結【文本、json、csv、pdf等】
這篇文章主要介紹了Python常見讀寫文件操作,結合實例形式總結分析了Python常見的各種文件讀寫操作,包括文本、json、csv、pdf等文件的讀寫與相關注意事項,需要的朋友可以參考下2019-04-04