五子棋python代码
时间: 2023-07-22 08:39:24 浏览: 125
下面是一个简单的五子棋 Python 代码实现,你可以在 Python 环境下运行它:
```python
import numpy as np
class Game:
def __init__(self, board_size=15):
self.board_size = board_size
self.board = np.zeros((board_size, board_size))
self.players = [1, 2]
self.num_moves = 0
def get_valid_moves(self):
return np.argwhere(self.board == 0)
def make_move(self, move, player):
self.board[move[0], move[1]] = player
self.num_moves += 1
def check_win(self, player):
for i in range(self.board_size):
for j in range(self.board_size):
if self.board[i][j] == player:
if self.check_direction(i, j, player, (0, 1)) or \
self.check_direction(i, j, player, (1, 0)) or \
self.check_direction(i, j, player, (1, 1)) or \
self.check_direction(i, j, player, (1, -1)):
return True
return False
def check_direction(self, i, j, player, direction):
count = 0
while i >= 0 and i < self.board_size and j >= 0 and j < self.board_size and \
self.board[i][j] == player and count < 5:
count += 1
i += direction[0]
j += direction[1]
if count == 5:
return True
else:
return False
def play(self):
current_player = self.players[self.num_moves % 2]
while True:
valid_moves = self.get_valid_moves()
if len(valid_moves) == 0:
print("Game over: tie")
return
move = tuple(map(int, input("Player {}, enter your move (row, col): ".format(current_player)).split(",")))
if move not in valid_moves:
print("Invalid move, try again.")
continue
self.make_move(move, current_player)
if self.check_win(current_player):
print("Player {} wins!".format(current_player))
return
current_player = self.players[self.num_moves % 2]
game = Game()
game.play()
```
这个代码实现了一个基本的五子棋游戏,玩家可以交替输入落子的位置,程序会检查落子的合法性以及是否有玩家胜出。
阅读全文