python五子棋源代码
时间: 2023-08-29 15:07:04 浏览: 84
以下是一个简单的 Python 五子棋源代码示例:
```python
import numpy as np
class Board:
def __init__(self, size):
self.size = size
self.board = np.zeros((size, size), dtype=int)
self.player = 1
def move(self, x, y):
if x >= self.size or y >= self.size or self.board[x][y] != 0:
return False
self.board[x][y] = self.player
self.player = 3 - self.player
return True
def check_win(self):
player = 3 - self.player
for i in range(self.size):
for j in range(self.size):
if self.board[i][j] == player:
if self.check_line(i, j, 0, 1) or self.check_line(i, j, 1, 0) or self.check_line(i, j, 1, 1) or self.check_line(i, j, -1, 1):
return player
return 0
def check_line(self, x, y, dx, dy):
count = 0
player = self.board[x][y]
while x >= 0 and x < self.size and y >= 0 and y < self.size and self.board[x][y] == player:
count += 1
x += dx
y += dy
return count >= 5
def __str__(self):
result = ' '
for i in range(self.size):
result += str(i) + ' '
result += '\n'
for i in range(self.size):
result += str(i) + ' '
for j in range(self.size):
if self.board[i][j] == 0:
result += '. '
elif self.board[i][j] == 1:
result += 'X '
else:
result += 'O '
result += '\n'
return result
def main():
board = Board(15)
print(board)
while True:
x = int(input("X: "))
y = int(input("Y: "))
if board.move(x, y):
print(board)
winner = board.check_win()
if winner != 0:
print("Player %s wins!" % winner)
break
else:
print("Invalid move.")
if __name__ == '__main__':
main()
```
这个示例中,我们使用了 numpy 来创建并管理棋盘,其中 0 表示空白,1 表示黑子,2 表示白子。我们还实现了一个 check_win() 方法来检查是否有玩家获胜。在主函数中,我们使用 input() 函数来读取玩家的输入,并在每次落子后检查是否有玩家获胜。
阅读全文