这里有一个使用Python语言实现的简单五子棋代码示例:
```python
定义棋盘大小
BOARD_SIZE = 15
定义棋盘
board = [[' ' for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
定义棋子类型
BLACK = 'B'
WHITE = 'W'
判断是否胜利的函数
def check_win(row, col, player):
directions = [(1, 0), (0, 1), (1, 1), (1, -1)] 四个方向:竖直、水平、斜向下、斜向上
for d in directions:
dx, dy = d
count = 1
x, y = row + dx, col + dy
while 0 <= x < BOARD_SIZE and 0 <= y < BOARD_SIZE and board[x][y] == player:
x += dx
y += dy
count += 1
if count >= 5:
return True
return False
主函数
def main():
current_player = BLACK
while True:
打印棋盘
for row in board:
print(' '.join(row))
print()
玩家落子
row = int(input("玩家落子,请输入行号 (0-14): "))
col = int(input("玩家落子,请输入列号 (0-14): "))
if board[row][col] != ' ':
print("该位置已有棋子,请重新输入。")
continue
board[row][col] = current_player
判断游戏胜负
if check_win(row, col, current_player):
print(f"玩家 {current_player} 获胜!")
break
电脑落子
if not check_win(row, col, current_player):
这里可以添加电脑落子的逻辑,例如使用Minimax算法或随机选择
为了简单起见,我们假设电脑总是随机落子
import random
ai_row = random.randint(0, BOARD_SIZE - 1)
ai_col = random.randint(0, BOARD_SIZE - 1)
while board[ai_row][ai_col] != ' ':
ai_row = random.randint(0, BOARD_SIZE - 1)
ai_col = random.randint(0, BOARD_SIZE - 1)
board[ai_row][ai_col] = 'W' 假设电脑使用白色棋子
切换玩家
current_player = 'W' if current_player == 'B' else 'B'
if __name__ == "__main__":
main()
```
这个代码实现了一个简单的五子棋游戏,玩家和电脑轮流在棋盘上落子,直到有一方获胜。游戏会打印出当前的棋盘状态,并在玩家落子后检查是否有玩家获胜。电脑的落子逻辑是随机的,实际应用中可以使用更复杂的算法,如Minimax算法来提高游戏的难度和趣味性。