python写一个五子棋代码
时间: 2023-05-25 14:05:00 浏览: 147
抱歉,我不能使用编程语言编写代码,但是以下是Python中实现五子棋游戏的示例代码:
```python
import numpy as np
ROW = 15
COL = 15
class Board:
def __init__(self):
self.board = np.zeros((ROW, COL))
def move(self, row, col, player):
if self.board[row, col] != 0:
raise ValueError("Invalid move")
self.board[row, col] = player
def get_winner(self):
for r in range(ROW):
for c in range(COL):
if c + 4 < COL and np.all(self.board[r, c:c+5] == self.board[r, c]) and self.board[r, c] != 0:
return self.board[r, c]
if r + 4 < ROW and np.all(self.board[r:r+5, c] == self.board[r, c]) and self.board[r, c] != 0:
return self.board[r, c]
if r + 4 < ROW and c + 4 < COL and np.all(np.diag(self.board[r:r+5, c:c+5]) == self.board[r, c]) and self.board[r, c] != 0:
return self.board[r, c]
if r + 4 < ROW and c - 4 >= 0 and np.all(np.diag(np.fliplr(self.board[r:r+5, c-4:c+1])) == self.board[r, c]) and self.board[r, c] != 0:
return self.board[r, c]
if np.all(self.board != 0):
return -1
return 0
def __str__(self):
ret = ""
for r in range(ROW):
for c in range(COL):
if self.board[r, c] == 1:
ret += "X"
elif self.board[r, c] == 2:
ret += "O"
else:
ret += "."
ret += "\n"
return ret
def play():
board = Board()
player = 1
while True:
print(board)
try:
move = input("Player {} move (row, col): ".format(player))
row, col = move.split(",")
row = int(row.strip())
col = int(col.strip())
board.move(row, col, player)
winner = board.get_winner()
if winner != 0:
print(board)
if winner == -1:
print("It's a tie!")
else:
print("Player {} wins!".format(winner))
break
except ValueError:
print("Invalid move")
else:
player = 3 - player
if __name__ == "__main__":
play()
```
这段代码使用numpy实现了一个15x15的五子棋盘面和相关的游戏逻辑。它将棋盘表示为一个2D数组,并为每个位置赋予与玩家相应的整数值(1代表玩家一,2代表玩家二,0代表没有棋子)。它还提供了一个`get_winner`方法来检查游戏是否结束,如果有一方赢了,它将返回该玩家的整数值,否则返回零表示游戏仍在进行中,或者返回-1表示平局。游戏由一个循环驱动,玩家轮流行动,如果游戏结束,则退出循环并输出胜利者的信息。
阅读全文