package com.gogame.minesweeper.swipe

import android.annotation.SuppressLint
import java.util.*

object LogicHelper {
    fun randomMines(xlength: Int, ylength: Int, x: Int, y: Int, count: Int): ArrayList<Int> {
        val total = xlength * ylength - 1
        if (count >= total || count <= 0) {
            throw IllegalArgumentException("Invalid mine count: $count")
        }

        val random = Random()
        val randoms = hashSetOf(getIndexByXY(xlength, ylength, x, y)) // 用HashSet防止重复

        while (randoms.size < count + 1) {
            val next = random.nextInt(xlength * ylength)
            randoms.add(next) // HashSet 自动忽略重复的数字
        }

        randoms.remove(getIndexByXY(xlength, ylength, x, y)) // 移除点击位置
        return ArrayList(randoms)
    }


    fun getIndexByXY(xlength: Int, ylength: Int, x: Int, y: Int): Int {
        return x + y * xlength
    }

    fun getXYbyIndex(xlength:Int,ylength:Int,index:Int):IntArray{
        val x = index%ylength
        val y = index/ylength
        return intArrayOf(x,y)
    }

    fun getAroundItems(xLength: Int, yLength: Int, index: Int): List<Int> {
        val result = mutableListOf<Int>()
        val x = index % xLength // 根据列数获取x坐标
        val y = index / xLength // 根据行数获取y坐标

        // 检查周围的8个格子
        for (i in -1..1) {
            for (j in -1..1) {
                if (i == 0 && j == 0) continue // 跳过当前格子
                val newX = x + i
                val newY = y + j
                // 检查边界
                if (newX in 0 until xLength && newY in 0 until yLength) {
                    result.add(newY * xLength + newX)
                }
            }
        }
        return result
    }



    /**
     * 转换成三位数文字
     */
    @SuppressLint("DefaultLocale")
    fun int2String(int: Int): String {
        return String.format("%03d", int)
    }

}