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('初始棋盤(pán):') 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. 理解PHP5中static和const關(guān)鍵字2. Android table布局開(kāi)發(fā)實(shí)現(xiàn)簡(jiǎn)單計(jì)算器3. jQuery 實(shí)現(xiàn)DOM元素拖拽交換位置的實(shí)例代碼4. IntelliJ IDEA安裝插件的方法步驟5. php模擬實(shí)現(xiàn)斗地主發(fā)牌6. vue 使用localstorage實(shí)現(xiàn)面包屑的操作7. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)8. Python random庫(kù)使用方法及異常處理方案9. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟10. Vuex localStorage的具體使用

網(wǎng)公網(wǎng)安備