python 判断五子棋 算法代码
时间: 2023-10-04 11:05:01 浏览: 112
以下是一个简单的基于Python语言实现的五子棋判断算法代码示例:
```python
# 定义棋盘大小
BOARD_SIZE = 15
# 定义棋子颜色
EMPTY = 0
BLACK = 1
WHITE = 2
# 定义判断方向
DIRECTIONS = [(0, 1), (1, 0), (1, 1), (1, -1)]
# 判断某个位置是否在棋盘内
def is_valid_location(x, y):
return x >= 0 and x < BOARD_SIZE and y >= 0 and y < BOARD_SIZE
# 判断当前位置是否为空
def is_empty_location(board, x, y):
return board[x][y] == EMPTY
# 判断当前位置是否为黑子
def is_black_location(board, x, y):
return board[x][y] == BLACK
# 判断当前位置是否为白子
def is_white_location(board, x, y):
return board[x][y] == WHITE
# 判断某个位置是否连成五子
def is_five_in_row(board, x, y, color):
for dx, dy in DIRECTIONS:
count = 1
for i in range(1, 5):
nx, ny = x + i * dx, y + i * dy
if is_valid_location(nx, ny) and is_same_color(board, nx, ny, color):
count += 1
else:
break
for i in range(1, 5):
nx, ny = x - i * dx, y - i * dy
if is_valid_location(nx, ny) and is_same_color(board, nx, ny, color):
count += 1
else:
break
if count >= 5:
return True
return False
# 判断当前位置与指定颜色是否相同
def is_same_color(board, x, y, color):
if color == BLACK:
return is_black_location(board, x, y)
elif color == WHITE:
return is_white_location(board, x, y)
return False
# 判断当前位置是否可以下棋
def is_valid_move(board, x, y, color):
if not is_valid_location(x, y) or not is_empty_location(board, x, y):
return False
board[x][y] = color
is_win = is_five_in_row(board, x, y, color)
board[x][y] = EMPTY
return is_win
# 五子棋判断算法
def is_game_over(board):
for x in range(BOARD_SIZE):
for y in range(BOARD_SIZE):
if is_valid_move(board, x, y, BLACK):
return False
if is_valid_move(board, x, y, WHITE):
return False
return True
```
这段代码实现了基本的五子棋规则判断功能,可以判断某个位置是否可以下棋、是否连成五子等。
阅读全文