python實(shí)現(xiàn)簡(jiǎn)單的井字棋
本文實(shí)例為大家分享了python實(shí)現(xiàn)簡(jiǎn)單的井字棋的具體代碼,供大家參考,具體內(nèi)容如下
使用python實(shí)現(xiàn)井字棋游戲,沒(méi)有具體算法,只是用隨機(jī)下棋簡(jiǎn)單實(shí)現(xiàn):
import randomboard = [[’+’,’+’,’+’],[’+’,’+’,’+’],[’+’,’+’,’+’]]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('機(jī)器走:') 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 1def 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 Falsedef main(): print('初始棋盤:') oput(board) flag = 0 t = input('human first? Y/N human for X, machine for On') if t == ’Y’:while isempty(board): print('人走: ') a, b = map(int, input('輸入落子縱橫坐標(biāo): a,b n').split(’,’)) if board[a][b] == ’+’: board[a][b] = ’X’ oput(board) flag = test(board) if flag == 1: break else:print('落子位置不對(duì)')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('輸入落子縱橫坐標(biāo): a,b n').split(’,’)) if board[a][b] == ’+’:board[a][b] = ’X’oput(board)flag = test(board)if flag == 1: break else:print('落子位置不對(duì)')continueif __name__ == '__main__': main()
結(jié)果:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python使用ctypes庫(kù)調(diào)用DLL動(dòng)態(tài)鏈接庫(kù)2. Python 如何將integer轉(zhuǎn)化為羅馬數(shù)(3999以內(nèi))3. css進(jìn)階學(xué)習(xí) 選擇符4. 詳解Python模塊化編程與裝飾器5. html小技巧之td,div標(biāo)簽里內(nèi)容不換行6. Python下使用Trackbar實(shí)現(xiàn)繪圖板7. python web框架的總結(jié)8. 以PHP代碼為實(shí)例詳解RabbitMQ消息隊(duì)列中間件的6種模式9. 使用Python解析Chrome瀏覽器書簽的示例10. Python性能測(cè)試工具Locust安裝及使用
