用python实现一个带有胜负判断的五子棋
时间: 2023-05-30 14:01:37 浏览: 84
以下是一个简单的五子棋游戏的实现,其中包括了胜负判断。
```python
import numpy as np
def create_board():
board = np.zeros((15, 15))
return board
def place_piece(board, row, col, piece):
board[row][col] = piece
def is_valid_move(board, row, col):
if row < 0 or row > 14 or col < 0 or col > 14:
return False
elif board[row][col] != 0:
return False
else:
return True
def has_won(board, piece):
# 横向判断
for i in range(15):
for j in range(11):
if board[i][j] == piece and board[i][j+1] == piece and board[i][j+2] == piece and board[i][j+3] == piece and board[i][j+4] == piece:
return True
# 竖向判断
for i in range(11):
for j in range(15):
if board[i][j] == piece and board[i+1][j] == piece and board[i+2][j] == piece and board[i+3][j] == piece and board[i+4][j] == piece:
return True
# 左上到右下判断
for i in range(11):
for j in range(11):
if board[i][j] == piece and board[i+1][j+1] == piece and board[i+2][j+2] == piece and board[i+3][j+3] == piece and board[i+4][j+4] == piece:
return True
# 右上到左下判断
for i in range(11):
for j in range(4, 15):
if board[i][j] == piece and board[i+1][j-1] == piece and board[i+2][j-2] == piece and board[i+3][j-3] == piece and board[i+4][j-4] == piece:
return True
return False
board = create_board()
print(board)
player = 1
game_over = False
while not game_over:
# 玩家1下棋
if player == 1:
row = int(input("Player 1 row: "))
col = int(input("Player 1 column: "))
if is_valid_move(board, row, col):
place_piece(board, row, col, 1)
if has_won(board, 1):
print("Player 1 wins!")
game_over = True
else:
print("Invalid move, try again.")
continue
# 玩家2下棋
else:
row = int(input("Player 2 row: "))
col = int(input("Player 2 column: "))
if is_valid_move(board, row, col):
place_piece(board, row, col, 2)
if has_won(board, 2):
print("Player 2 wins!")
game_over = True
else:
print("Invalid move, try again.")
continue
print(board)
# 切换玩家
player = 3 - player
```
这个实现使用了numpy库来创建一个15x15的矩阵作为棋盘,玩家1下的棋子用数字1表示,玩家2下的棋子用数字2表示。游戏开始时,玩家1先下棋,然后切换到玩家2,直到有一方获胜或者棋盘填满。胜利条件通过检查每个五元组(横向、竖向、左上到右下、右上到左下)来确定。如果五元组中有五个相同的数字,则该玩家获胜。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)