用Python代码实现A对战的五子棋游戏
时间: 2023-06-16 14:07:55 浏览: 69
基于Python实现五子棋(三人对战)
5星 · 资源好评率100%
以下是使用Python实现的五子棋游戏代码,其中A和B轮流下棋,当其中一方获胜时游戏结束。
```python
import numpy as np
def create_board():
board = np.zeros((15,15))
return board
def drop_piece(board, row, col, piece):
board[row][col] = piece
def is_valid_location(board, col):
return board[0][col] == 0
def get_next_open_row(board, col):
for r in range(14,-1,-1):
if board[r][col] == 0:
return r
def print_board(board):
print(np.flip(board, 0))
def winning_move(board, piece):
# Check horizontal locations for win
for c in range(11):
for r in range(15):
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
# Check vertical locations for win
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
# Check positively sloped diaganols
for c in range(11):
for r 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
# Check negatively sloped diaganols
for c in range(11):
for r 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
board = create_board()
game_over = False
turn = 0
while not game_over:
# Ask for Player 1 Input
if turn == 0:
col = int(input("Player A make your selection (0-14):"))
if is_valid_location(board, col):
row = get_next_open_row(board, col)
drop_piece(board, row, col, 1)
if winning_move(board, 1):
print("Player A wins!")
game_over = True
# Ask for Player 2 Input
else:
col = int(input("Player B make your selection (0-14):"))
if is_valid_location(board, col):
row = get_next_open_row(board, col)
drop_piece(board, row, col, 2)
if winning_move(board, 2):
print("Player B wins!")
game_over = True
print_board(board)
turn += 1
turn = turn % 2
```
当你运行这个代码时,你会看到一个15x15的棋盘,并提示玩家A或玩家B选择他们想要下棋的列。当其中一方获胜时,游戏结束。
阅读全文