【五子棋源码-python】

以下是一个简单的五子棋代码示例,使用Python语言实现:

import numpy as np
# 初始化棋盘
def init_board():
    board = np.zeros((15, 15))
    return board
# 判断落子是否合法
def is_valid(board, row, col):
    if board[row][col] == 0:
        return True
    else:
        return False
# 落子
def drop_piece(board, row, col, player):
    board[row][col] = player
# 判断胜负
def is_win(board, player):
    # 判断行
    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
    # 判断列
    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
    # 判断正对角线
    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
    # 判断反对角线
    for i in range(11):
        for j in range(4, 15):
            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
    return False
# 主函数
def main():
    board = init_board()
    player = 1
    while True:
        print(board)
        row = int(input("请玩家{}输入行号:".format(player)))
        col = int(input("请玩家{}输入列号:".format(player)))
        if is_valid(board, row, col):
            drop_piece(board, row, col, player)
            if is_win(board, player):
                print("玩家{}获胜!".format(player))
                break
            if player == 1:
                player = 2
            else:
                player = 1
if __name__ == '__main__':
    main()

这个五子棋代码使用numpy库实现了棋盘的初始化和落子,使用了简单的循环来判断胜负。在主函数中,循环交替落子并判断胜负。

你可能感兴趣的:(python,python,numpy,开发语言)