以下是一个简单的五子棋小游戏的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 print_board(board):
    print(np.flip(board, 0))

def winning_move(board, piece):
    # Check horizontal locations for win
    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

    # Check vertical locations for win
    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

    # Check positively sloped diaganols
    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

    # Check negatively sloped diaganols
    for r in range(11):
        for c in range(4, 15):
            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 play_game():
    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 column: "))
            if is_valid_move(board, row, col):
                place_piece(board, row, col, 1)
                print_board(board)
                if winning_move(board, 1):
                    print("Player 1 wins!")
                    game_over = True
                else:
                    turn = 2
            else:
                print("Invalid move! Try again.")
        else:
            row = int(input("Player 2 enter row: "))
            col = int(input("Player 2 enter column: "))
            if is_valid_move(board, row, col):
                place_piece(board, row, col, 2)
                print_board(board)
                if winning_move(board, 2):
                    print("Player 2 wins!")
                    game_over = True
                else:
                    turn = 1
            else:
                print("Invalid move! Try again.")

play_game()

这个代码使用了一个15x15的二维数组作为游戏棋盘,1代表玩家1的棋子,2代表玩家2的棋子,0代表空格。游戏开始时,玩家轮流输入要放置棋子的行和列,程序会检查这个位置是否是一个有效的移动,并在棋盘上放置相应的棋子。每当一个玩家放置棋子时,程序会检查是否已经有5个棋子连成一条线,如果有,游戏结束并宣布获胜者。如果棋盘已经被填满,但没有任何一方获胜,游戏以平局结束。

请用python编一个五子棋小游戏

原文地址: https://www.cveoy.top/t/topic/blPk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录