基于基于python纯函数实现井字棋游戏纯函数实现井字棋游戏
1、定义全局变、定义全局变
'''全局变量:
X 和 O 表示两方的棋子;
EMPTY 表示棋位为空;
TIE 表示平局;
NUM_SQUARES 表示有 9 个棋位
'''
X = "X"
O = "O"
EMPTY = " "
TIE = "TIE"
NUM_SQUARES = 9
2、定义调用到的函数、定义调用到的函数
def ask_yes_no(question):
'''问一个是或否的问题,用 y 或 n 回答。'''
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('好,你先请。')
human = X
computer = O
else:
print('你放弃先手,我先走。')
computer = X
human = O
return computer, human
def new_board():
'''创建一个棋盘。'''
board = [] for square in range(NUM_SQUARES):
board.append(EMPTY)
return board
def display_board(board):
'''显示棋盘。'''
print(' ', board[0], '|', board[1], '|', board[2])
print(' ', '---------')
print(' ', board[3], '|', board[4], '|', board[5])
print(' ', '---------')
print(' ', board[6], '|', board[7], '|', board[8], '')
def legal_moves(board):
'''创建合法的行棋位置清单。'''
moves = [] for square in range(NUM_SQUARES):
if board[square] == EMPTY: # 该棋位为空
moves.append(square)
return moves
def winner(board):
'''判定游戏获胜者。'''
WAYS_TO_WIN = ((0, 1, 2), # 横
(3, 4, 5),
评论0