PYTHON 写一个五子棋代码
时间: 2024-05-07 07:19:44 浏览: 87
python实现五子棋小程序
好的,以下是一个简单的五子棋代码:
```python
import numpy as np
def create_board():
board = np.zeros((15,15))
return board
def place(board, player, row, col):
board[row][col] = player
def get_valid_moves(board):
valid_moves = []
for row in range(len(board)):
for col in range(len(board)):
if board[row][col] == 0:
valid_moves.append((row, col))
return valid_moves
def check_win(board, player):
# check rows
for row in range(len(board)):
if np.all(board[row] == player):
return True
# check columns
for col in range(len(board)):
if np.all(board[:,col] == player):
return True
# check diagonals
if np.all(board.diagonal() == player):
return True
if np.all(np.fliplr(board).diagonal() == player):
return True
return False
board = create_board()
player = 1
game_over = False
while not game_over:
valid_moves = get_valid_moves(board)
print(board)
print("Valid Moves:", valid_moves)
row = int(input("Enter row:"))
col = int(input("Enter column:"))
if (row, col) in valid_moves:
place(board, player, row, col)
if check_win(board, player):
print("Player", player, "wins!")
game_over = True
player = 3 - player # switch player
else:
print("Invalid move!")
```
这个代码使用了numpy库来创建15x15的棋盘,并且提供了放置棋子、获取有效移动和检查胜利的函数。在主循环中,程序会一直询问用户输入行和列,直到输入一个有效的移动。程序会在每次放置棋子后检查是否有玩家获胜,如果有则游戏结束并宣布胜利者。
阅读全文