Now heavily extend the reference script (with easy UCI) extensively into whatever this topic is; "Quantum Gambit Chess Engine Full Complex Application" into a single python code.

CONTENT = The content here, is based-off the description as well as it's matching topic.

Description: "A probabilistic chess engine that incorporates principles of quantum computation, employing "superposition moves" to evaluate multiple potential board states simultaneously. Rather than making deterministic decisions, it uses quantum randomness to explore unusual, aggressive gambits that confound traditional engines. Features quantum-inspired heuristics for parallel line exploration, especially in mid-game play, where it thrives on chaos. U.S.O.P (Unique Set-of Properties): 'Superposition Move Search', 'Quantum-Zobrist Hybrid', 'Randomized Collapse Heuristic'."

Directed Features: "Quantum Collapsing: Refines position evaluations by "collapsing" into the most promising lines as more depth is searched. Entanglement Heuristics: Links evaluations of interconnected pieces (like rook-queen cooperation) to simulate entanglement principles. Schrödinger’s Opening Book: Uses probabilistic gambits, switching between multiple opening lines to confuse opponents. Quantum Superposition Search: Evaluates multiple moves simultaneously using probabilistic calculations."

[ENGINE_SAMPLING: 2.1]
[TOP_M: 1]

Reference Script (REFERENCE ONLY):

```
import chess
import chess.engine
import random

class SimpleChessEngine:
    def __init__(self):
        self.board = chess.Board()

    def make_move(self, move):
        """Attempts to make a move on the board."""
        try:
            self.board.push_san(move)
        except ValueError:
            return "Invalid move. Please try again."

    def get_random_move(self):
        """Returns a random legal move from the current board state."""
        moves = list(self.board.legal_moves)
        return random.choice(moves) if moves else None

    def play_engine_move(self):
        """Makes a random move for the engine and returns it."""
        move = self.get_random_move()
        if move:
            self.board.push(move)
        return move

    def display_board(self):
        """Returns a string representation of the current board."""
        return str(self.board)

def main():
    engine = SimpleChessEngine()
    print("Welcome to Simple Chess Engine!")
    print("Enter your moves in standard algebraic notation (e.g., e2e4).")

    while not engine.board.is_game_over():
        print(engine.display_board())
        user_move = input("Your move: ")
        if user_move.lower() == 'quit':
            break
        response = engine.make_move(user_move)
        if response:
            print(response)
            continue
        if not engine.board.is_game_over():
            engine_move = engine.play_engine_move()
            if engine_move:
                print(f"Engine move: {engine_move}")

    print("Game over!")
    print(engine.display_board())

if __name__ == "__main__":
    main()
```

```
GUILLABLE DECISIONS:
# Script 1, 2, and 3.
# See python-chess documentation at https://python-chess.readthedocs.io/en/latest/

import chess
import chess.pgn
import random

# Plays a randomly selected legal move each turn
class RandomPlayer:
    def __init__(self):
        pass

    def select_move(self, board):
        return random.choice(list(board.legal_moves)) if board.legal_moves else None

# Plays a checkmate if possible, otherwise a capture if possible, 
# otherwise a random move
class CheckmateOrCapturePlayer:
    def __init__(self):
        pass

    def select_move(self, board):
        if not board.legal_moves:
            return None

        legal_moves = list(board.legal_moves)
        chosen_move = None

        for move in legal_moves:
            if board.is_capture(move):
                chosen_move = move
            board.push(move)
            if board.is_checkmate():
                board.pop()
                return move
            board.pop()

        if not chosen_move:
            return random.choice(legal_moves)

        return chosen_move

def play_game(white, black):
    board = chess.Board()
    game = chess.pgn.Game()
    node = game

    while not board.is_game_over():
        player = white if board.turn else black
        move = player.select_move(board)
        board.push(move)
        node = node.add_variation(move)

    game.headers["Result"] = board.result()
    game.headers["White"] = " " + type(white).__name__
    game.headers["Black"] = " " + type(black).__name__
    excluded_tags = ["Event", "Site", "Date", "Round"]
    for tag in excluded_tags:
        if tag in game.headers:
            del game.headers[tag]
    return game

def playoff(player1, player2):
    pass

board = chess.Board()
game = chess.pgn.Game()
node = game
white = CheckmateOrCapturePlayer()
black = RandomPlayer()

game = play_game(white, black)
print (game)

# 2:

import requests
import chess
import chess.pgn
import torch
import torch.nn as nn
import torch.optim as optim
import io
from stockfish import Stockfish

class NNUE(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super(NNUE, self).__init__()
        self.fc1 = nn.Linear(input_size, hidden_size)
        self.fc2 = nn.Linear(hidden_size, hidden_size)
        self.fc3 = nn.Linear(hidden_size, output_size)
        self.relu = nn.ReLU()

    def forward(self, x):
        x = self.relu(self.fc1(x))
        x = self.relu(self.fc2(x))
        x = self.fc3(x)
        return x

def download_lichess_games(username, max_games=400):
    url = f"https://lichess.org/api/games/user/{username}?max={max_games}&pgnInJson=true"
    response = requests.get(url)
    if response.status_code != 200:
        raise Exception(f"Failed to fetch data from Lichess API: {response.status_code}")
    try:
        games = response.json()
    except ValueError:
        raise Exception(f"Failed to parse JSON response from Lichess API: {response.text}")
    return games

def extract_fen_positions_and_evaluations(games, stockfish_path, depth=15):
    stockfish = Stockfish(stockfish_path)
    positions = []
    evaluations = []
    for i, game in enumerate(games):
        pgn = game.get('pgn')
        if not pgn:
            print(f"No PGN found for game {i + 1}.")
            continue
        
        try:
            pgn_io = io.StringIO(pgn)
            game = chess.pgn.read_game(pgn_io)
            if game is None:
                print(f"Failed to parse PGN for game {i + 1}.")
                continue
            
            board = game.board()
            for move in game.mainline_moves():
                board.push(move)
                positions.append(board.fen())
                stockfish.set_fen_position(board.fen())
                evaluation = stockfish.get_evaluation()
                if evaluation['type'] == 'cp':
                    evaluations.append(evaluation['value'] / 100.0)  
                elif evaluation['type'] == 'mate':
                    evaluations.append(1000 if evaluation['value'] > 0 else -1000)  
        except Exception as e:
            print(f"Error processing PGN for game {i + 1}: {e}")
            continue
    return positions, evaluations

def board_to_tensor(board):
    pieces = ['p', 'n', 'b', 'r', 'q', 'k', 'P', 'N', 'B', 'R', 'Q', 'K']
    board_tensor = torch.zeros(64 * 12)
    for square in chess.SQUARES:
        piece = board.piece_at(square)
        if piece:
            index = pieces.index(piece.symbol())
            board_tensor[square * 12 + index] = 1
    return board_tensor

def preprocess_data(positions, evaluations):
    data = []
    for position, evaluation in zip(positions, evaluations):
        board = chess.Board(position)
        input_tensor = board_to_tensor(board)
        target_tensor = torch.tensor([evaluation], dtype=torch.float32)
        data.append((input_tensor, target_tensor))
    return data

def train_model(data, input_size, hidden_size, output_size, epochs=10, learning_rate=0.001):
    if not data:
        raise ValueError("No data available for training.")
    
    model = NNUE(input_size, hidden_size, output_size)
    criterion = nn.MSELoss()
    optimizer = optim.Adam(model.parameters(), lr=learning_rate)

    for epoch in range(epochs):
        total_loss = 0
        for input_tensor, target_tensor in data:
            optimizer.zero_grad()
            output = model(input_tensor)
            loss = criterion(output, target_tensor)
            loss.backward()
            optimizer.step()
            total_loss += loss.item()
        average_loss = total_loss / len(data)
        print(f'Epoch {epoch+1}/{epochs}, Average Loss: {average_loss}')

    return model

# Download games from Lichess
username = "NoOneCanBeatMe4"
try:
    games = download_lichess_games(username)
    print(f"Downloaded {len(games)} games from Lichess.")
except Exception as e:
    print(e)
    games = []


stockfish_path = "stockfish-windows-x86-64-sse41-popcnt.exe"  
positions, evaluations = extract_fen_positions_and_evaluations(games, stockfish_path)
print(f"Extracted {len(positions)} positions and evaluations.")

data = preprocess_data(positions, evaluations)
print(f"Preprocessed {len(data)} data points.")
input_size = 64 * 12
hidden_size = 256
output_size = 1

if data:
    # Train the NNUE model
    trained_model = train_model(data, input_size, hidden_size, output_size)

    # Save the trained model
    torch.save(trained_model.state_dict(), 'nnue_model.pth')
    print("Saved trained model to nnue_model.pth.")
else:
    print("No data available for training.")

#3:

import argparse
import chess
import chess.pgn
import multiprocessing

NTHREADS  = 16
BATCHSIZE = 16384

def extract_uci_moves_str(game):

    board = game.board()
    uci_moves = []

    for move in game.mainline_moves():
        board.push(move)
        uci_moves.append(move.uci())

    return ' '.join(uci_moves)

def extract_san_pgn_moves_str(game):

    string = ''

    for node in game.mainline():
        if node.ply() % 2:
            string += '%d. ' % (node.ply() // 2 + 1)
        string += '%s ' % (node.san())

    return string.rstrip()

def score_line(engine_path, uci_moves):

    board = chess.Board()
    for move in uci_moves.split():
        board.push_uci(move)

    with chess.engine.SimpleEngine.popen_uci(engine_path) as engine:
        info = engine.analyse(board, chess.engine.Limit(depth=25, time=30.0))

    if isinstance(info['score'].relative, chess.engine.Cp):
        return info['score'].relative.score()


def source_generator(book_path):
    with open(book_path) as pgn_file:
        while (game := chess.pgn.read_game(pgn_file)):
            yield game

def enqueue_elements(generator, elements, queue):
    for f in range(elements):
        try: queue.put(next(generator))
        except StopIteration: return f
    return elements

def process_data(in_queue, out_queue, engine_path):
    with chess.engine.SimpleEngine.popen_uci(engine_path) as engine:
        while (game := in_queue.get()):
            out_queue.put((game, score_line(engine_path, extract_uci_moves_str(game))))

def write_book_entry(game, score):
    print ('[Result "1/2-1/2"]')
    print ('[RelativeScore "%+.2f"]' % (score / 100))
    print ()
    print (extract_san_pgn_moves_str(game))
    print ()


def main():

    p = argparse.ArgumentParser(description='Chess engine and book configuration')
    p.add_argument('--engine', type=str, required=True, help='Engine path')
    p.add_argument('--book',   type=str, required=True, help='Book path')
    args = p.parse_args()

    in_queue = multiprocessing.Queue()
    out_queue = multiprocessing.Queue()

    workers = [
        multiprocessing.Process(target=process_data, args=(in_queue, out_queue, args.engine,), daemon=True)
        for f in range(NTHREADS)
    ]

    for worker in workers:
        worker.start()

    generator = source_generator(args.book)

    while True:
        n = enqueue_elements(generator, BATCHSIZE, in_queue)
        for f in range(n):
            write_book_entry(*out_queue.get())

if __name__ == '__main__':
    main()
```