井字棋遊戲(P88)

2021-10-14 14:24:49 字數 3098 閱讀 5653

x="x"

o="o"

empty=" "

def ask_yes_no(question):

response=none

while response not in("y","n"):

response=input(question).lower()

return response

def ask_number(question,low,high):

response=none

while response not in range(low,high):

response=int(input(question))

return response

def pieces():

go_first=ask_yes_no("玩家是否先走(y/n):")

if go_first=="y":

print("\n玩家先走")

human=x

computer=o

else:

print("\n計算機先走")

computer=x

human=o

return computer,human

def new_board():

board=

for square in range(9):

return board

def display_board(board):

board2=board[:]

for i in range(len(board)):

if board[i]==empty:

board2[i]=i

print("\t",board2[0],"|",board2[1],"|",board2[2])

print("\t","---------")

print("\t",board2[3],"|",board2[4],"|",board2[5])

print("\t","---------")

print("\t",board2[6],"|",board2[7],"|",board2[8],"\n")

def legal_moves(board):

moves=

for square in range(9):

if board[square]==empty:

return moves

def winner(board):

ways_to_win=((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6))

for row in ways_to_win:

if board[row[0]]==board[row[1]]==board[row[2]]!=empty:

winner=board[row[0]]

return winner

if empty not in board:

return "tie"

return false

def human_move(board,human):

legal=legal_moves(board)

move=none

while move not in legal:

move=ask_number("你走哪個位置?",0,9)

if move not in legal:

print("\n此位置已經落過子了")

return move

def computer_move(board,computer,human):

board=board[:]

best_moves=(4,0,2,6,8,1,3,5,7)

for move in legal_moves(board):

board[move]=computer

if winner(board)==computer:

print("計算機下棋位置...",move)

return move

board[move]=empty

for move in legal_moves(board):

board[move]=human

if winner(board)==human:

print("計算機下棋位置...",move)

return move

board[move]=empty

for move in best_moves:

if move in legal_moves(board):

print("計算機下棋位置...",move)

return move

def next_turn(turn):

if turn==x:

return o

else:

return x

def main():

computer,human=pieces()#賦值x或o

turn=x

board=new_board()#初始化棋盤

display_board(board)#顯示當前棋盤

while not winner(board):

if turn==human:

move=human_move(board,human)

board[move]=human

else:

move=computer_move(board,computer,human)

board[move]=computer

display_board(board)

turn=next_turn(turn)

the_winner=winner(board)

if the_winner==computer:

print("computer winner!\n")

elif the_winner==human:

print("you win!\n")

elif the_winner=="tie":

print("tie!\n")

main()

input("按任意鍵退出遊戲")

井字棋遊戲

三連棋遊戲 兩人輪流在印有九格方盤上劃 或 o 字,誰先把三個同一記號排成橫線 直線 斜線,即是勝者 程式提供隨機演算法和智慧型演算法兩種ai,隨機演算法使用隨機數隨意選擇棋盤上的位置,智慧型演算法通過對每隔落子位置權重的計算,選取最優的落子點。include include include inc...

井字棋遊戲

井字棋,英文名叫tic tac toe,是一種在3 3格仔上進行的連珠遊戲,和五子棋類似,由於棋盤一般不畫邊框,格線排成井字故得名。遊戲需要的工具僅為紙和筆,然後由分別代表o和x的兩個遊戲者輪流在格仔裡留下標記 一般來說先手者為x 任意三個標記形成一條直線,則為獲勝。py100天day7 井字棋這個...

井字棋小遊戲

include include define row 3 define col 3 define player piece x define computer piece o 開始選單 void menu 函式宣告 void game void rule void board char board ...