生成python五子棋代码
时间: 2023-05-22 14:07:12 浏览: 42
以下是一个简单的 Python 五子棋代码示例:
```
class Board:
def __init__(self, size=15):
self.size = size
self.grid = [[None] * size for _ in range(size)]
def print_board(self):
print(" " + " ".join(str(i) for i in range(self.size)))
for i in range(self.size):
print(str(i) + " " + " ".join(str(self.grid[i][j]) if self.grid[i][j] is not None else "·" for j in range(self.size)))
def legal_move(self, x, y, color):
if x < 0 or x >= self.size or y < 0 or y >= self.size or self.grid[y][x] is not None:
return False
for dx, dy in [(1, 0), (0, 1), (1, 1), (1, -1)]:
cx, cy = x + dx, y + dy
count = 0
while 0 <= cx < self.size and 0 <= cy < self.size and self.grid[cy][cx] == color:
count += 1
cx += dx
cy += dy
if count >= 4:
return True
return False
def play_game():
board = Board()
players = ["黑棋", "白棋"]
current_player = 0
while True:
board.print_board()
print("当前玩家: {}".format(players[current_player]))
x, y = map(int, input("请输入落子位置 x,y:").strip().split(","))
if board.legal_move(x, y, current_player):
board.grid[y][x] = current_player
if board.legal_move(x, y, current_player):
print("{} 取得胜利!".format(players[current_player]))
break
current_player = (current_player + 1) % 2
else:
print("非法落子,请重新输入!")
play_game()
```