import Phaser from 'phaser';

export class GameBoard extends Phaser.Events.EventEmitter {
    constructor(scene, config) {
        super();
        this.scene = scene;
        this.config = config;
        this.board = [];
        this.sprites = [];
        this.selectedCell = null;
        this.animating = false;
        this.elementsData = {};
        this.selectionBorder = null;
        
        // 滑动操作相关
        this.isDragging = false;
        this.dragStart = null;
        this.dragStartCell = null;
        
        // 将元素配置转换为便于查找的格式
        this.processElementsConfig();
    }

    processElementsConfig() {
        this.config.elements.forEach(element => {
            this.elementsData[element.id] = element;
        });
    }

    create() {
        this.createBoard();
        this.createSprites();
        this.setupInput();
        this.createSelectionBorder();
    }

    createBoard() {
        // 从关卡数据初始化棋盘
        if (this.config.levelData && this.config.levelData.board) {
            this.board = this.deepCopyBoard(this.config.levelData.board);
        } else {
            // 生成随机棋盘（备用）
            this.generateRandomBoard();
        }
    }

    deepCopyBoard(sourceBoard) {
        return sourceBoard.map(row => row.map(cell => ({ ...cell })));
    }

    generateRandomBoard() {
        // 根据关卡配置获取可用元素类型数量
        const maxElementTypes = this.config.levelData ? this.config.levelData.elementTypes : 4;
        const elementTypes = Object.keys(this.elementsData).slice(0, maxElementTypes);
        
        for (let y = 0; y < this.config.height; y++) {
            this.board[y] = [];
            for (let x = 0; x < this.config.width; x++) {
                let elementType;
                let attempts = 0;
                
                // 确保初始不会有三连
                do {
                    elementType = elementTypes[Math.floor(Math.random() * elementTypes.length)];
                    attempts++;
                } while (attempts < 50 && this.wouldCreateMatch(x, y, elementType));

                this.board[y][x] = {
                    type: elementType,
                    obstacle: null,
                    special: false
                };
            }
        }
    }

    wouldCreateMatch(x, y, elementType) {
        // 检查水平三连
        if (x >= 2) {
            if (this.board[y][x-1] && this.board[y][x-1].type === elementType &&
                this.board[y][x-2] && this.board[y][x-2].type === elementType) {
                return true;
            }
        }

        // 检查垂直三连
        if (y >= 2) {
            if (this.board[y-1] && this.board[y-1][x] && this.board[y-1][x].type === elementType &&
                this.board[y-2] && this.board[y-2][x] && this.board[y-2][x].type === elementType) {
                return true;
            }
        }

        return false;
    }

    createSprites() {
        this.sprites = [];
        
        for (let y = 0; y < this.config.height; y++) {
            this.sprites[y] = [];
            for (let x = 0; x < this.config.width; x++) {
                const cell = this.board[y][x];
                const sprite = this.createElementSprite(x, y, cell);
                this.sprites[y][x] = sprite;
            }
        }
    }

    createElementSprite(x, y, cell) {
        const posX = this.config.startX + x * this.config.cellSize + this.config.cellSize / 2;
        const posY = this.config.startY + y * this.config.cellSize + this.config.cellSize / 2;
        
        // 从元素配置中获取sprite名称
        const elementConfig = this.elementsData[cell.type];
        const spriteName = elementConfig ? elementConfig.sprite : cell.type;
        
        const sprite = this.scene.add.image(posX, posY, spriteName);
        sprite.setDisplaySize(this.config.cellSize - 4, this.config.cellSize - 4);
        sprite.setInteractive({ useHandCursor: true });
        
        // 存储坐标信息和原始尺寸
        sprite.gridX = x;
        sprite.gridY = y;
        sprite.elementType = cell.type;
        sprite.originalScale = sprite.scaleX;
        
        return sprite;
    }

    createSelectionBorder() {
        // 创建选中边框（初始时隐藏）
        this.selectionBorder = this.scene.add.graphics();
        this.selectionBorder.lineStyle(3, 0xffff00, 1);
        this.selectionBorder.strokeRoundedRect(0, 0, this.config.cellSize, this.config.cellSize, 4);
        this.selectionBorder.setVisible(false);
    }

    setupInput() {
        // 为整个游戏区域设置触摸事件
        this.gameArea = this.scene.add.rectangle(
            this.config.startX + (this.config.width * this.config.cellSize) / 2,
            this.config.startY + (this.config.height * this.config.cellSize) / 2,
            this.config.width * this.config.cellSize,
            this.config.height * this.config.cellSize,
            0x000000,
            0
        );
        this.gameArea.setInteractive();

        // 触摸开始
        this.gameArea.on('pointerdown', (pointer) => {
            if (this.animating) return;
            
            const cell = this.getCellFromPosition(pointer.x, pointer.y);
            if (cell) {
                this.dragStart = { x: pointer.x, y: pointer.y };
                this.dragStartCell = cell;
                this.isDragging = false;
                
                // 选中当前方块
                this.selectCell(cell.x, cell.y);
            }
        });

        // 触摸移动
        this.gameArea.on('pointermove', (pointer) => {
            if (this.animating || !this.dragStart) return;
            
            const distance = Phaser.Math.Distance.Between(
                this.dragStart.x, this.dragStart.y,
                pointer.x, pointer.y
            );
            
            // 如果移动距离超过阈值，开始拖拽
            if (distance > 20 && !this.isDragging) {
                this.isDragging = true;
            }
        });

        // 触摸结束
        this.gameArea.on('pointerup', (pointer) => {
            if (this.animating) return;
            
            if (this.isDragging && this.dragStartCell) {
                // 计算滑动方向
                const deltaX = pointer.x - this.dragStart.x;
                const deltaY = pointer.y - this.dragStart.y;
                const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
                
                // 只有滑动距离足够大才处理
                if (distance > 30) {
                    let targetX = this.dragStartCell.x;
                    let targetY = this.dragStartCell.y;
                    
                    // 判断主要滑动方向
                    if (Math.abs(deltaX) > Math.abs(deltaY)) {
                        // 水平滑动
                        if (deltaX > 0) {
                            // 向右滑动
                            targetX = this.dragStartCell.x + 1;
                        } else {
                            // 向左滑动
                            targetX = this.dragStartCell.x - 1;
                        }
                    } else {
                        // 垂直滑动
                        if (deltaY > 0) {
                            // 向下滑动
                            targetY = this.dragStartCell.y + 1;
                        } else {
                            // 向上滑动
                            targetY = this.dragStartCell.y - 1;
                        }
                    }
                    
                    // 检查目标位置是否有效
                    if (targetX >= 0 && targetX < this.config.width && 
                        targetY >= 0 && targetY < this.config.height) {
                        this.attemptSwap(this.dragStartCell.x, this.dragStartCell.y, targetX, targetY);
                    } else {
                        // 目标位置无效，取消选择
                        this.deselectCell();
                    }
                } else {
                    // 滑动距离太小，取消选择
                    this.deselectCell();
                }
            } else if (!this.isDragging && this.dragStartCell) {
                // 简单点击，如果已经选中了其他方块则尝试交换
                if (this.selectedCell && 
                    (this.selectedCell.x !== this.dragStartCell.x || this.selectedCell.y !== this.dragStartCell.y)) {
                    if (this.isAdjacent(this.selectedCell.x, this.selectedCell.y, this.dragStartCell.x, this.dragStartCell.y)) {
                        this.attemptSwap(this.selectedCell.x, this.selectedCell.y, this.dragStartCell.x, this.dragStartCell.y);
                    } else {
                        this.selectCell(this.dragStartCell.x, this.dragStartCell.y);
                    }
                }
            }
            
            // 重置拖拽状态
            this.dragStart = null;
            this.dragStartCell = null;
            this.isDragging = false;
        });
    }

    getCellFromPosition(x, y) {
        const localX = x - this.config.startX;
        const localY = y - this.config.startY;
        
        if (localX < 0 || localY < 0) return null;
        
        const cellX = Math.floor(localX / this.config.cellSize);
        const cellY = Math.floor(localY / this.config.cellSize);
        
        if (cellX >= 0 && cellX < this.config.width && 
            cellY >= 0 && cellY < this.config.height) {
            return { x: cellX, y: cellY };
        }
        
        return null;
    }

    selectCell(x, y) {
        // 先取消之前的选择
        this.deselectCell();
        
        this.selectedCell = { x, y };
        const sprite = this.sprites[y][x];
        
        // 只放大，不变色
        this.scene.tweens.add({
            targets: sprite,
            scaleX: sprite.originalScale * 1.1,
            scaleY: sprite.originalScale * 1.1,
            duration: 100,
            ease: 'Power2'
        });
        
        // 显示选中边框
        const posX = this.config.startX + x * this.config.cellSize;
        const posY = this.config.startY + y * this.config.cellSize;
        this.selectionBorder.setPosition(posX, posY);
        this.selectionBorder.setVisible(true);
        
        // 边框动画效果
        this.scene.tweens.add({
            targets: this.selectionBorder,
            alpha: 0.7,
            duration: 300,
            yoyo: true,
            repeat: -1
        });
    }

    deselectCell() {
        if (this.selectedCell) {
            const sprite = this.sprites[this.selectedCell.y][this.selectedCell.x];
            
            // 恢复原始大小
            this.scene.tweens.add({
                targets: sprite,
                scaleX: sprite.originalScale,
                scaleY: sprite.originalScale,
                duration: 100,
                ease: 'Power2'
            });
            
            this.selectedCell = null;
        }
        
        // 隐藏选中边框
        this.selectionBorder.setVisible(false);
        this.scene.tweens.killTweensOf(this.selectionBorder);
        this.selectionBorder.setAlpha(1);
    }

    isAdjacent(x1, y1, x2, y2) {
        const dx = Math.abs(x1 - x2);
        const dy = Math.abs(y1 - y2);
        return (dx === 1 && dy === 0) || (dx === 0 && dy === 1);
    }

    attemptSwap(x1, y1, x2, y2) {
        this.animating = true;
        
        // 临时交换
        this.swapElements(x1, y1, x2, y2);
        
        // 检查是否有匹配
        const matches = this.findMatches();
        
        if (matches.length > 0) {
            // 有效移动
            this.deselectCell();
            this.animateSwap(x1, y1, x2, y2, () => {
                this.processMatches(matches);
            });
        } else {
            // 无效移动，播放失败动画后交换回去
            this.swapElements(x1, y1, x2, y2); // 先交换回去
            this.playInvalidMoveAnimation(x1, y1, x2, y2, () => {
                this.animating = false;
                this.deselectCell();
            });
        }
    }

    playInvalidMoveAnimation(x1, y1, x2, y2, callback) {
        const sprite1 = this.sprites[y1][x1];
        const sprite2 = this.sprites[y2][x2];
        
        const pos1X = this.config.startX + x1 * this.config.cellSize + this.config.cellSize / 2;
        const pos1Y = this.config.startY + y1 * this.config.cellSize + this.config.cellSize / 2;
        const pos2X = this.config.startX + x2 * this.config.cellSize + this.config.cellSize / 2;
        const pos2Y = this.config.startY + y2 * this.config.cellSize + this.config.cellSize / 2;

        // 稍微移动然后回弹，表示无效操作
        const moveDistance = 10;
        const deltaX1 = (pos2X - pos1X) > 0 ? moveDistance : -moveDistance;
        const deltaY1 = (pos2Y - pos1Y) > 0 ? moveDistance : -moveDistance;
        const deltaX2 = -deltaX1;
        const deltaY2 = -deltaY1;

        let completed = 0;
        const onComplete = () => {
            completed++;
            if (completed === 2 && callback) {
                callback();
            }
        };

        // 第一个方块的回弹动画
        this.scene.tweens.add({
            targets: sprite1,
            x: pos1X + (Math.abs(deltaX1) > Math.abs(deltaY1) ? deltaX1 : 0),
            y: pos1Y + (Math.abs(deltaY1) > Math.abs(deltaX1) ? deltaY1 : 0),
            duration: 100,
            yoyo: true,
            ease: 'Power2',
            onComplete: onComplete
        });

        // 第二个方块的回弹动画
        this.scene.tweens.add({
            targets: sprite2,
            x: pos2X + (Math.abs(deltaX2) > Math.abs(deltaY2) ? deltaX2 : 0),
            y: pos2Y + (Math.abs(deltaY2) > Math.abs(deltaX2) ? deltaY2 : 0),
            duration: 100,
            yoyo: true,
            ease: 'Power2',
            onComplete: onComplete
        });
    }

    swapElements(x1, y1, x2, y2) {
        // 只交换棋盘数据，不交换精灵引用
        const temp = this.board[y1][x1];
        this.board[y1][x1] = this.board[y2][x2];
        this.board[y2][x2] = temp;
    }

    animateSwap(x1, y1, x2, y2, callback) {
        const sprite1 = this.sprites[y1][x1];
        const sprite2 = this.sprites[y2][x2];
        
        const pos1X = this.config.startX + x1 * this.config.cellSize + this.config.cellSize / 2;
        const pos1Y = this.config.startY + y1 * this.config.cellSize + this.config.cellSize / 2;
        const pos2X = this.config.startX + x2 * this.config.cellSize + this.config.cellSize / 2;
        const pos2Y = this.config.startY + y2 * this.config.cellSize + this.config.cellSize / 2;

        let completed = 0;
        const onComplete = () => {
            completed++;
            if (completed === 2) {
                // 动画完成后，交换精灵引用并更新属性
                this.sprites[y1][x1] = sprite2;
                this.sprites[y2][x2] = sprite1;
                
                // 更新精灵的网格坐标和元素类型
                sprite1.gridX = x2;
                sprite1.gridY = y2;
                sprite1.elementType = this.board[y2][x2].type;
                
                sprite2.gridX = x1;
                sprite2.gridY = y1;
                sprite2.elementType = this.board[y1][x1].type;
                
                if (callback) {
                    callback();
                }
            }
        };

        // 动画移动精灵1到位置2
        this.scene.tweens.add({
            targets: sprite1,
            x: pos2X,
            y: pos2Y,
            duration: 200,
            ease: 'Power2',
            onComplete: onComplete
        });

        // 动画移动精灵2到位置1
        this.scene.tweens.add({
            targets: sprite2,
            x: pos1X,
            y: pos1Y,
            duration: 200,
            ease: 'Power2',
            onComplete: onComplete
        });
    }

    findMatches() {
        const matches = [];

        // 查找水平匹配
        for (let y = 0; y < this.config.height; y++) {
            for (let x = 0; x < this.config.width - 2; x++) {
                const type = this.board[y][x].type;
                if (type && this.board[y][x + 1].type === type && this.board[y][x + 2].type === type) {
                    const match = [];
                    let i = x;
                    while (i < this.config.width && this.board[y][i].type === type) {
                        match.push({ x: i, y: y });
                        i++;
                    }
                    if (match.length >= 3) {
                        matches.push({
                            type: 'horizontal',
                            cells: match,
                            elementType: type
                        });
                        // 跳过已经处理的部分
                        x = i - 1;
                    }
                }
            }
        }

        // 查找垂直匹配
        for (let x = 0; x < this.config.width; x++) {
            for (let y = 0; y < this.config.height - 2; y++) {
                const type = this.board[y][x].type;
                if (type && this.board[y + 1][x].type === type && this.board[y + 2][x].type === type) {
                    const match = [];
                    let i = y;
                    while (i < this.config.height && this.board[i][x].type === type) {
                        match.push({ x: x, y: i });
                        i++;
                    }
                    if (match.length >= 3) {
                        matches.push({
                            type: 'vertical',
                            cells: match,
                            elementType: type
                        });
                        // 跳过已经处理的部分
                        y = i - 1;
                    }
                }
            }
        }

        // 合并所有匹配的格子，去除重复
        const allMatchedCells = new Set();
        const mergedMatches = [];
        
        matches.forEach(match => {
            match.cells.forEach(cell => {
                allMatchedCells.add(`${cell.x},${cell.y}`);
            });
        });

        // 将所有匹配的格子转换回数组格式
        if (allMatchedCells.size > 0) {
            const allCells = Array.from(allMatchedCells).map(cellKey => {
                const [x, y] = cellKey.split(',').map(Number);
                return { x, y };
            });
            mergedMatches.push(allCells);
        }

        return mergedMatches;
    }

    processMatches(matches) {
        if (!matches || matches.length === 0) return;

        let totalElements = 0;
        let centerX = 0, centerY = 0;

        // 计算中心位置用于分数显示
        matches.forEach(match => {
            match.forEach(cell => {
                totalElements++;
                centerX += this.config.startX + cell.x * this.config.cellSize + this.config.cellSize / 2;
                centerY += this.config.startY + cell.y * this.config.cellSize + this.config.cellSize / 2;
            });
        });

        if (totalElements > 0) {
            centerX /= totalElements;
            centerY /= totalElements;
        }

        // 检测是否为特殊组合（T字型、十字型等）
        const allCells = matches.flat();
        const comboType = this.detectComboType(allCells);
        
        // 发送匹配事件，包含组合类型信息
        this.emit('match', {
            matches: matches,
            elements: allCells,
            centerX: centerX,
            centerY: centerY,
            comboType: comboType,
            elementCount: totalElements
        });

        // 执行消除动画
        this.animateMatches(matches, () => {
            this.applyGravity(() => {
                this.fillEmptySpaces(() => {
                    // 检查是否有新的匹配
                    const newMatches = this.findMatches();
                    if (newMatches.length > 0) {
                        // 连锁反应
                        this.processMatches(newMatches);
                    } else {
                        this.animating = false;
                        this.emit('moveComplete');
                        
                        // 检查是否还有可能的移动
                        if (!this.hasPossibleMoves()) {
                            this.emit('noMatches');
                        }
                    }
                });
            });
        });
    }

    detectComboType(cells) {
        if (cells.length < 4) {
            return 'normal'; // 普通三连
        }

        // 按坐标分组，检查是否有T字型或十字型
        const cellMap = new Map();
        cells.forEach(cell => {
            const key = `${cell.x},${cell.y}`;
            cellMap.set(key, cell);
        });

        // 检查每个格子是否为交叉点
        for (const cell of cells) {
            let horizontalCount = 1; // 包括自己
            let verticalCount = 1; // 包括自己
            
            // 向左计数
            for (let x = cell.x - 1; x >= 0; x--) {
                if (cellMap.has(`${x},${cell.y}`)) {
                    horizontalCount++;
                } else {
                    break;
                }
            }
            
            // 向右计数
            for (let x = cell.x + 1; x < this.config.width; x++) {
                if (cellMap.has(`${x},${cell.y}`)) {
                    horizontalCount++;
                } else {
                    break;
                }
            }
            
            // 向上计数
            for (let y = cell.y - 1; y >= 0; y--) {
                if (cellMap.has(`${cell.x},${y}`)) {
                    verticalCount++;
                } else {
                    break;
                }
            }
            
            // 向下计数
            for (let y = cell.y + 1; y < this.config.height; y++) {
                if (cellMap.has(`${cell.x},${y}`)) {
                    verticalCount++;
                } else {
                    break;
                }
            }
            
            // 判断组合类型
            if (horizontalCount >= 3 && verticalCount >= 3) {
                if (horizontalCount >= 5 || verticalCount >= 5) {
                    return 'mega'; // 超级组合
                } else if (horizontalCount >= 4 && verticalCount >= 4) {
                    return 'cross'; // 十字型
                } else {
                    return 'tshape'; // T字型
                }
            }
        }

        // 检查是否为长链
        if (cells.length >= 6) {
            return 'long_chain';
        } else if (cells.length >= 4) {
            return 'four_match';
        }

        return 'normal';
    }

    animateMatches(matches, callback) {
        let animationsLeft = 0;
        
        matches.forEach(match => {
            match.forEach(cell => {
                const sprite = this.sprites[cell.y][cell.x];
                animationsLeft++;
                
                this.scene.tweens.add({
                    targets: sprite,
                    alpha: 0,
                    scaleX: sprite.originalScale * 1.5,
                    scaleY: sprite.originalScale * 1.5,
                    duration: 300,
                    ease: 'Power2',
                    onComplete: () => {
                        sprite.destroy();
                        this.sprites[cell.y][cell.x] = null;
                        this.board[cell.y][cell.x] = null;
                        
                        animationsLeft--;
                        if (animationsLeft === 0 && callback) {
                            callback();
                        }
                    }
                });
            });
        });
    }

    applyGravity(callback) {
        const movements = [];
        
        // 计算所有方块的下落
        for (let x = 0; x < this.config.width; x++) {
            let writeIndex = this.config.height - 1;
            
            for (let y = this.config.height - 1; y >= 0; y--) {
                if (this.board[y][x] !== null) {
                    if (y !== writeIndex) {
                        movements.push({
                            from: { x, y },
                            to: { x, y: writeIndex },
                            sprite: this.sprites[y][x],
                            element: this.board[y][x]
                        });
                        
                        this.board[writeIndex][x] = this.board[y][x];
                        this.sprites[writeIndex][x] = this.sprites[y][x];
                        this.board[y][x] = null;
                        this.sprites[y][x] = null;
                    }
                    writeIndex--;
                }
            }
        }

        // 执行下落动画
        if (movements.length > 0) {
            let animationsLeft = movements.length;
            
            movements.forEach(movement => {
                const targetY = this.config.startY + movement.to.y * this.config.cellSize + this.config.cellSize / 2;
                
                this.scene.tweens.add({
                    targets: movement.sprite,
                    y: targetY,
                    duration: 300,
                    ease: 'Power2',
                    onComplete: () => {
                        movement.sprite.gridX = movement.to.x;
                        movement.sprite.gridY = movement.to.y;
                        
                        animationsLeft--;
                        if (animationsLeft === 0 && callback) {
                            callback();
                        }
                    }
                });
            });
        } else if (callback) {
            callback();
        }
    }

    fillEmptySpaces(callback) {
        const newSprites = [];
        
        for (let x = 0; x < this.config.width; x++) {
            for (let y = 0; y < this.config.height; y++) {
                if (this.board[y][x] === null) {
                    // 根据关卡配置获取可用元素类型数量
                    const elementTypes = Object.keys(this.elementsData);
                    const maxElementTypes = this.config.levelData ? this.config.levelData.elementTypes : 4;
                    const randomType = elementTypes[Math.floor(Math.random() * Math.min(elementTypes.length, maxElementTypes))];
                    
                    this.board[y][x] = {
                        type: randomType,
                        obstacle: null,
                        special: false
                    };
                    
                    // 创建新精灵（从上方掉落）
                    const startY = this.config.startY - this.config.cellSize * 2;
                    const targetY = this.config.startY + y * this.config.cellSize + this.config.cellSize / 2;
                    const posX = this.config.startX + x * this.config.cellSize + this.config.cellSize / 2;
                    
                    // 从元素配置中获取sprite名称
                    const elementConfig = this.elementsData[randomType];
                    const spriteName = elementConfig ? elementConfig.sprite : randomType;
                    
                    const sprite = this.scene.add.image(posX, startY, spriteName);
                    sprite.setDisplaySize(this.config.cellSize - 4, this.config.cellSize - 4);
                    sprite.gridX = x;
                    sprite.gridY = y;
                    sprite.elementType = randomType;
                    sprite.originalScale = sprite.scaleX;
                    
                    this.sprites[y][x] = sprite;
                    newSprites.push({ sprite, targetY });
                }
            }
        }

        // 执行掉落动画
        if (newSprites.length > 0) {
            let animationsLeft = newSprites.length;
            
            newSprites.forEach(({ sprite, targetY }) => {
                this.scene.tweens.add({
                    targets: sprite,
                    y: targetY,
                    duration: 400,
                    ease: 'Bounce',
                    onComplete: () => {
                        animationsLeft--;
                        if (animationsLeft === 0 && callback) {
                            callback();
                        }
                    }
                });
            });
        } else if (callback) {
            callback();
        }
    }

    hasPossibleMoves() {
        // 简化的可能移动检查
        for (let y = 0; y < this.config.height; y++) {
            for (let x = 0; x < this.config.width; x++) {
                // 检查向右交换
                if (x < this.config.width - 1) {
                    this.swapElements(x, y, x + 1, y);
                    const hasMatch = this.findMatches().length > 0;
                    this.swapElements(x, y, x + 1, y); // 交换回去
                    if (hasMatch) return true;
                }
                
                // 检查向下交换
                if (y < this.config.height - 1) {
                    this.swapElements(x, y, x, y + 1);
                    const hasMatch = this.findMatches().length > 0;
                    this.swapElements(x, y, x, y + 1); // 交换回去
                    if (hasMatch) return true;
                }
            }
        }
        return false;
    }

    regenerateBoard() {
        // 销毁当前精灵和边框
        this.sprites.forEach(row => {
            row.forEach(sprite => {
                if (sprite) sprite.destroy();
            });
        });
        
        if (this.selectionBorder) {
            this.selectionBorder.destroy();
        }
        
        // 销毁旧的交互区域
        if (this.gameArea) {
            this.gameArea.destroy();
        }
        
        // 重新生成棋盘
        this.generateRandomBoard();
        this.createSprites();
        this.createSelectionBorder();
        
        // 重新设置输入交互
        this.setupInput();
        
        this.selectedCell = null;
    }
} 