用python写一个五子棋小游戏的代码
时间: 2023-04-09 15:02:51 浏览: 136
用python实现的五子棋小游戏
4星 · 用户满意度95%
好的,我可以回答这个问题。以下是一个简单的五子棋小游戏的Python代码:
```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
if board[row][col] != 0:
return False
return True
def get_winner(board):
# 检查行
for i in range(15):
for j in range(11):
if board[i][j] == board[i][j+1] == board[i][j+2] == board[i][j+3] == board[i][j+4] and board[i][j] != 0:
return board[i][j]
# 检查列
for i in range(11):
for j in range(15):
if board[i][j] == board[i+1][j] == board[i+2][j] == board[i+3][j] == board[i+4][j] and board[i][j] != 0:
return board[i][j]
# 检查对角线
for i in range(11):
for j in range(11):
if board[i][j] == board[i+1][j+1] == board[i+2][j+2] == board[i+3][j+3] == board[i+4][j+4] and board[i][j] != 0:
return board[i][j]
for i in range(11):
for j in range(4, 15):
if board[i][j] == board[i+1][j-1] == board[i+2][j-2] == board[i+3][j-3] == board[i+4][j-4] and board[i][j] != 0:
return board[i][j]
return 0
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 col: "))
if is_valid_move(board, row, col):
place_piece(board, row, col, 1)
turn = 2
else:
row = int(input("Player 2, enter row: "))
col = int(input("Player 2, enter col: "))
if is_valid_move(board, row, col):
place_piece(board, row, col, 2)
turn = 1
print(board)
winner = get_winner(board)
if winner != 0:
print("Player " + str(winner) + " wins!")
game_over = True
```
这个代码使用了numpy库来创建一个15x15的棋盘,然后实现了下棋、判断是否有效、判断胜负等功能。玩家1使用1表示,玩家2使用2表示。在每个回合结束后,程序会检查是否有玩家获胜,如果有,游戏结束。
阅读全文