Untitled
unknown
python
3 years ago
1.6 kB
12
Indexable
import random
#宣告一個棋盤
map = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
#判斷遊戲是否結束的function->檢查有無連線
def win():
for i in range(3):
#判斷橫行
if map[i][0] == map[i][1] == map[i][2]:
return True
#判斷直行
if map[0][i] == map[1][i] == map[2][i]:
return True
#判斷右斜
if map[0][0] == map[1][1] == map[2][2]:
return True
#判斷左斜
if map[0][2] == map[1][1] == map[2][0]:
return True
return False
print("You are O, and computer is X")
while (True):
#印出當前棋盤的結果
for i in range(3):
for j in range(3):
print(map[i][j], end=' ')
print("\n")
# O(player) move
choose = int(input("Please enter number to choose step : "))
#把O畫到player選擇的位置上
choose -= 1
map[choose // 3][choose % 3] = 'O'
#判斷遊戲是否結束了
if win():
print("O is the winner!")
break
# X(computer) move
while(True):
#電腦隨機選擇一個位置
choose=random.randint(1,9)
choose-=1
#如果電腦選擇的位置沒有被畫過就代表是合法的位置
if map[choose // 3][choose % 3]!='O' and map[choose // 3][choose % 3]!='X':
break
#把X畫到電腦選擇的位置上
map[choose // 3][choose % 3]='X'
#判斷遊戲是否結束了
if win():
print("X is the winner!")
break
#印出最後棋盤的結果
for i in range(3):
for j in range(3):
print(map[i][j], end=' ')
print("\n")Editor is loading...