python實(shí)現(xiàn)簡單的井字棋
發(fā)布日期:2022-04-07 12:32 | 文章來源:源碼之家
本文實(shí)例為大家分享了python實(shí)現(xiàn)簡單的井字棋的具體代碼,供大家參考,具體內(nèi)容如下
使用python實(shí)現(xiàn)井字棋游戲,沒有具體算法,只是用隨機(jī)下棋簡單實(shí)現(xiàn):
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("機(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 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("輸入落子縱橫坐標(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("落子位置不對")
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("落子位置不對")
continue
if __name__ == "__main__":
main()
結(jié)果:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持本站。
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
相關(guān)文章
關(guān)注官方微信