python五子棋代码
时间: 2023-10-08 11:13:39 浏览: 54
以下是一个简单的 Python 五子棋游戏代码:
```python
import numpy as np
# 初始化棋盘
def create_board():
board = np.zeros((15,15))
return board
# 判断落子是否合法
def is_valid_move(board, row, col):
return board[row][col] == 0
# 落子
def place_piece(board, row, col, piece):
board[row][col] = piece
# 判断胜负
def is_win(board, piece):
# 判断行
for r in range(15):
for c in range(11):
if board[r][c] == piece and board[r][c+1] == piece and board[r][c+2] == piece and board[r][c+3] == piece and board[r][c+4] == piece:
return True
# 判断列
for c in range(15):
for r in range(11):
if board[r][c] == piece and board[r+1][c] == piece and board[r+2][c] == piece and board[r+3][c] == piece and board[r+4][c] == piece:
return True
# 判断对角线
for r in range(11):
for c in range(11):
if board[r][c] == piece and board[r+1][c+1] == piece and board[r+2][c+2] == piece and board[r+3][c+3] == piece and board[r+4][c+4] == piece:
return True
# 判断反对角线
for r in range(11):
for c in range(4, 15):
if board[r][c] == piece and board[r+1][c-1] == piece and board[r+2][c-2] == piece and board[r+3][c-3] == piece and board[r+4][c-4] == piece:
return True
return False
# 主函数
def main():
board = create_board()
game_over = False
turn = 1
while not game_over:
if turn == 1:
row = int(input("Player 1, enter row: "))
col = int(input("Player 1, enter column: "))
if is_valid_move(board, row, col):
place_piece(board, row, col, 1)
if is_win(board, 1):
print("Player 1 wins!")
game_over = True
turn = 2
else:
row = int(input("Player 2, enter row: "))
col = int(input("Player 2, enter column: "))
if is_valid_move(board, row, col):
place_piece(board, row, col, 2)
if is_win(board, 2):
print("Player 2 wins!")
game_over = True
turn = 1
print(board)
if __name__ == "__main__":
main()
```
这个代码中使用了 NumPy 库来创建和操作二维数组表示棋盘,实现了基本的落子、判断胜负和交替玩家等功能。然而,这只是一个简单的实现,还有很多优化和功能可以添加,比如实现 AI 玩家、改进界面等。
阅读全文