九步python五子棋
时间: 2023-11-09 12:03:38 浏览: 64
好的,以下是九步Python五子棋的代码:
```python
import numpy as np
def create_board():
board = np.zeros((15,15))
return board
def place(board, player, position):
if board[position] == 0:
board[position] = player
return board
def possibilities(board):
positions = np.where(board == 0)
return list(zip(positions[0], positions[1]))
def random_place(board, player):
selections = possibilities(board)
if len(selections) > 0:
position = selections[np.random.randint(len(selections))]
board = place(board, player, position)
return board
def row_win(board, player):
for i in range(15):
if np.all(board[i,:] == player):
return True
return False
def col_win(board, player):
for i in range(15):
if np.all(board[:,i] == player):
return True
return False
def diag_win(board, player):
if np.all(board.diagonal() == player):
return True
if np.all(np.fliplr(board).diagonal() == player):
return True
return False
def evaluate(board):
winner = 0
for player in [1,2]:
if (row_win(board, player) or col_win(board,player) or diag_win(board,player)):
winner = player
if np.all(board != 0) and winner == 0:
winner = -1
return winner
def play_game():
board = create_board()
winner = 0
while winner == 0:
for player in [1,2]:
board = random_place(board, player)
winner = evaluate(board)
if winner != 0:
break
return winner
print(play_game())
```
阅读全文