源代码下载
http://download.csdn.net/source/1881645
用MVVM模式写成的。
感觉难点在于搜索路径,这里是自己的算法,主要是加权了一下
int SearchPath(ObservableCollection<ButtonCommandViewModel> coll, int mouseIndex)
{
int resultIndex = -1;
double resultSteps = -1;
int leftIndex = -1, topIndex = -1, rightIndex = -1, bottomIndex = -1;
double leftSteps = -1, topSteps = -1, rightSteps = -1, bottomSteps = -1;
if (coll[mouseIndex - 1].ButtonState != IsShaded)//左
{
leftIndex = mouseIndex - 1;
leftSteps = coll[mouseIndex].IndexColumn;
int j = coll[mouseIndex].IndexColumn;
double weights = 1;//权值
for (int i = j - 1; i >= 0; i--)
{
int diff = j - i;
if (coll[mouseIndex - diff].ButtonState == IsShaded)
{
weights += 1.0 / diff;
}
}
//leftSteps *= weights;
for (int n = 0; n < Rows; n++)
leftSteps *= weights;
resultIndex = leftIndex;
resultSteps = leftSteps;
}
if (coll[mouseIndex - Columns].ButtonState != IsShaded)//上
{
topIndex = mouseIndex - Columns;
topSteps = coll[mouseIndex].IndexRow;
int j = coll[mouseIndex].IndexRow;
double weights = 1;//权值
for (int i = j - 1; i >= 0; i--)
{
int diff = j - i;
if (coll[mouseIndex - diff * Rows].ButtonState == IsShaded)
{
weights += 1.0 / (double)diff;
}
}
for (int n = 0; n < Rows; n++)
topSteps *= weights;
if (resultIndex < 0)
{
resultIndex = topIndex;
resultSteps = topSteps;
}
else
{
if (resultSteps > topSteps)
{
resultIndex = topIndex;
resultSteps = topSteps;
}
}
}
if (coll[mouseIndex + 1].ButtonState != IsShaded)//右
{
rightIndex = mouseIndex + 1;
rightSteps = Columns - 1 - coll[mouseIndex].IndexColumn;
int j = coll[mouseIndex].IndexColumn;
double weights = 1;//权值
for (int i = j + 1; i < Columns; i++)
{
int diff = i - j;
if (coll[mouseIndex + diff].ButtonState == IsShaded)
{
weights += 1.0 / (double)diff;
}
}
for (int n = 0; n < Rows; n++)
rightSteps *= weights;
if (resultIndex < 0)
{
resultIndex = rightIndex;
resultSteps = rightSteps;
}
else
{
if (resultSteps > rightSteps)
{
resultIndex = rightIndex;
resultSteps = rightSteps;
}
}
}
if (coll[mouseIndex + Columns].ButtonState != IsShaded)//下
{
bottomIndex = mouseIndex + Columns;
bottomSteps = Rows - 1 - coll[mouseIndex].IndexRow;
int j = coll[mouseIndex].IndexRow;
double weights = 1;//权值
for (int i = j + 1; i < Rows; i++)
{
int diff = i - j;
if (coll[mouseIndex + diff * Columns].ButtonState == IsShaded)
{
weights += 1.0 / (double)diff;
}
}
for (int n = 0; n < Rows; n++)
bottomSteps *= weights;
if (resultIndex < 0)
{
resultIndex = bottomIndex;
resultSteps = bottomSteps;
}
else
{
if (resultSteps > bottomSteps)
{
resultIndex = bottomIndex;
resultSteps = bottomSteps;
}
}
}
return resultIndex;
}