Python五子棋游戏代码
时间: 2023-11-05 18:01:23 浏览: 144
下面是一份简单的 Python 五子棋游戏代码,供您参考:
```
import numpy as np
def create_board():
board = np.zeros((15,15))
return board
def is_valid_move(board, row, col):
if board[row][col] == 0:
return True
else:
return False
def make_move(board, row, col, player):
board[row][col] = player
def is_game_over(board, player):
# check rows
for i in range(15):
for j in range(11):
if board[i][j] == player and board[i][j+1] == player and board[i][j+2] == player and board[i][j+3] == player and board[i][j+4] == player:
return True
# check columns
for i in range(11):
for j in range(15):
if board[i][j] == player and board[i+1][j] == player and board[i+2][j] == player and board[i+3][j] == player and board[i+4][j] == player:
return True
# check diagonals
for i in range(11):
for j in range(11):
if board[i][j] == player and board[i+1][j+1] == player and board[i+2][j+2] == player and board[i+3][j+3] == player and board[i+4][j+4] == player:
return True
if board[i][j+4] == player and board[i+1][j+3] == player and board[i+2][j+2] == player and board[i+3][j+1] == player and board[i+4][j] == player:
return True
return False
def print_board(board):
print(board)
def main():
board = create_board()
print_board(board)
player = 1
while True:
row = int(input("Enter row: "))
col = int(input("Enter column: "))
if is_valid_move(board, row, col):
make_move(board, row, col, player)
if is_game_over(board, player):
print("Player", player, "wins!")
break
player = 2 if player == 1 else 1
print_board(board)
else:
print("Invalid move. Try again.")
if __name__ == '__main__':
main()
```
这份代码实现了一个简单的五子棋游戏,使用了 numpy 库来创建棋盘。您可以在控制台中运行该代码,并按照提示输入行和列来落子。当有一方获胜时,游戏结束并显示胜者。
阅读全文