五子棋游戏 请使用Python语言开发一个五子棋游戏
时间: 2024-12-28 11:09:05 浏览: 7
五子棋是一款双人对战的策略型棋类游戏,目标是在棋盘上首先形成五个同色的棋子连成一线(横、竖、斜向)。我们可以通过Python来编写一个简单的命令行版五子棋游戏。
以下是使用Python的一个简单实现思路:
```python
import numpy as np
# 定义棋盘大小
BOARD_SIZE = 15
def create_board():
return np.zeros((BOARD_SIZE, BOARD_SIZE), dtype=int)
def print_board(board):
for row in board:
print(' '.join(str(cell) for cell in row))
def valid_move(board, x, y):
if board[x][y] != 0 or (x < 0 or y < 0 or x >= BOARD_SIZE or y >= BOARD_SIZE):
return False
return True
def make_move(board, player, x, y):
board[x][y] = player
def check_win(board, player):
# 检查横向、纵向和斜向是否有五子相连
win_conditions = [
[board[i:i+5, j:j+1], i, j] for i in range(BOARD_SIZE-4) for j in range(BOARD_SIZE)
+ [[board[i:i+5, :], i, None]] for i in range(BOARD_SIZE-4)
+ [[board[:, j:j+5], None, j] for j in range(BOARD_SIZE-4)]
+ [[board[i:i+5, i:i+5], i, i] for i in range(BOARD_SIZE-4)]
]
for condition in win_conditions:
if all(condition[0][:] == player and len(np.where(condition[0] == 0)[0]) == 0):
return True
return False
def play_game():
board = create_board()
current_player = 1 # 1代表黑子,2代表白子
while not check_win(board, current_player):
print_board(board)
print(f"Player {current_player}'s turn")
x = int(input("Enter row number (0-{}): ".format(BOARD_SIZE-1)))
y = int(input("Enter column number (0-{}): ".format(BOARD_SIZE-1)))
if valid_move(board, current_player, x, y):
make_move(board, current_player, x, y)
if check_win(board, current_player):
print("Player {} wins!".format(current_player))
break
current_player = -current_player # 切换玩家
else:
print("Invalid move, please try again.")
play_game()
```
这个脚本创建了一个基本的命令行五子棋游戏框架,你可以运行它开始游戏。注意这只是一个基础版本,实际应用可能会有更复杂的用户界面和AI对手功能。
阅读全文