python write a chess game

board = [
    ['car', 'horse', 'elephant', 'shi', 'general', 'shi', 'elephant', 'horse', 'car'],
    [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
    [' ', 'Cannon', ' ', ' ', ' ', ' ', ' ', 'Cannon', ' '],
    ['Grad', ' ', 'Grad', ' ', 'Grad', ' ', 'Grad', ' ', 'Grad'],
    [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
    [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
    ['Soldier', ' ', 'Soldier', ' ', 'Soldier', ' ', 'Soldier', ' ', 'Soldier'],
    [' ', 'gun', ' ', ' ', ' ', ' ', ' ', 'gun', ' '],
    [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
    ['car', 'horse', 'phase', 'shi', 'handsome', 'shi', 'phase', 'horse', 'car']
]

# print the chessboard
def print_board(board):
    for row in board:
        print(' '.join(row))

# get user input
def get_input():
    src = input("Please enter the position of the chess piece to be moved (format: row and column):")
    dst = input("Please enter the target location (format: row and column):")
    return src, dst

# move pieces
def move_piece(board, src, dst):
    src_row, src_col = map(int, src.split())
    dst_row, dst_col = map(int, dst.split())
    piece = board[src_row][src_col]
    board[src_row][src_col] = ' '
    board[dst_row][dst_col] = piece

# Main game loop
def main():
    while True:
        print_board(board)
        src, dst = get_input()
        move_piece(board, src, dst)

# run game
if __name__ == '__main__':
    main()

Guess you like

Origin blog.csdn.net/ducanwang/article/details/131456671