python帮我写一个五子棋游戏
时间: 2023-10-15 13:02:44 浏览: 66
python五子棋游戏,可双人对弈玩耍,运行简单,项目可作为毕业设计,下载即可运行
好的,我可以为您提供五子棋游戏的Python代码。以下是一个简单的示例:
```python
import numpy as np
# 创建棋盘
def create_board():
board = np.zeros((15,15))
return board
# 判断落子是否合法
def valid_move(board, row, col):
if board[row][col] == 0:
return True
else:
return False
# 落子
def place_piece(board, row, col, piece):
board[row][col] = piece
# 是否有胜者
def 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 r in range(11):
for c in range(15):
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(4,15):
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
return False
# 主函数
def main():
board = create_board()
print(board)
game_over = False
turn = 1
while not game_over:
# 黑棋为1,白棋为2
if turn == 1:
row = int(input("黑棋,请输入您要落子的行:"))
col = int(input("黑棋,请输入您要落子的列:"))
if valid_move(board, row, col):
place_piece(board, row, col, 1)
if win(board, 1):
print("黑棋胜利!")
game_over = True
turn += 1
else:
print("该位置已有落子,请重新输入!")
else:
row = int(input("白棋,请输入您要落子的行:"))
col = int(input("白棋,请输入您要落子的列:"))
if valid_move(board, row, col):
place_piece(board, row, col, 2)
if win(board, 2):
print("白棋胜利!")
game_over = True
turn -= 1
else:
print("该位置已有落子,请重新输入!")
print(board)
if __name__ == '__main__':
main()
```
希望这段代码可以帮助到您。
阅读全文