请帮我写一个计算机博弈的六子棋代码
时间: 2024-11-16 15:27:15 浏览: 9
编写一个完整的六子棋游戏代码需要考虑很多细节,这里提供一个简单的Python版本的示例,它实现了基本的游戏规则和用户界面,但并未包含全部的AI算法。你可以在这个基础上扩展和完善。
```python
# 六子棋棋盘大小和初始棋盘
SIZE = 7
board = [[' ' for _ in range(SIZE)] for _ in range(SIZE)]
def print_board():
for row in board:
print(' '.join(row))
def valid_move(x, y):
return 0 <= x < SIZE and 0 <= y < SIZE and board[x][y] == ' '
def make_move(player, x, y):
if valid_move(x, y) and board[x][y] == ' ':
board[x][y] = player
return True
else:
return False
def check_win(player):
# 检查四个方向是否有五子连珠
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
for dx, dy in directions:
count = 1
for i in range(SIZE):
if board[i][i + dx * count] == player and \
board[i + dx * (count - 1)][i + dy * count] == player:
count += 1
if count == SIZE:
return True
else:
break
return False
def play_game():
current_player = 'X'
while True:
print_board()
print(f"Player {current_player}, enter your move (x, y):")
x, y = input().split(',')
x, y = int(x), int(y)
if make_move(current_player, x, y):
if check_win(current_player):
print(f"Player {current_player} wins!")
break
current_player = 'O' if current_player == 'X' else 'X'
else:
print("Invalid move, please try again.")
play_game()
```
阅读全文