<VerticalStackLayout>
<Grid Margin="10" HeightRequest="330" WidthRequest="330" RowDefinitions="*,*,*" ColumnDefinitions="*,*,*" BackgroundColor="Gray">
<Button x:Name="btn1" Text="1" Grid.Row="0" Grid.Column="0" ZIndex="0" CornerRadius="0" BackgroundColor="Orange" Clicked="btn_Clicked" FontSize="36"/>
<Button x:Name="btn2" Text="2" Grid.Row="0" Grid.Column="1" ZIndex="1" CornerRadius="0" BackgroundColor="Orange" Clicked="btn_Clicked" FontSize="36"/>
<Button x:Name="btn3" Text="3" Grid.Row="0" Grid.Column="2" ZIndex="2" CornerRadius="0" BackgroundColor="Orange" Clicked="btn_Clicked" FontSize="36"/>
<Button x:Name="btn4" Text="4" Grid.Row="1" Grid.Column="0" ZIndex="3" CornerRadius="0" BackgroundColor="Orange" Clicked="btn_Clicked" FontSize="36"/>
<Button x:Name="btn5" Text="5" Grid.Row="1" Grid.Column="1" ZIndex="4" CornerRadius="0" BackgroundColor="Orange" Clicked="btn_Clicked" FontSize="36"/>
<Button x:Name="btn6" Text="6" Grid.Row="1" Grid.Column="2" ZIndex="5" CornerRadius="0" BackgroundColor="Orange" Clicked="btn_Clicked" FontSize="36"/>
<Button x:Name="btn7" Text="7" Grid.Row="2" Grid.Column="0" ZIndex="6" CornerRadius="0" BackgroundColor="Orange" Clicked="btn_Clicked" FontSize="36"/>
<Button x:Name="btn8" Text="8" Grid.Row="2" Grid.Column="1" ZIndex="7" CornerRadius="0" BackgroundColor="Orange" Clicked="btn_Clicked" FontSize="36"/>
<Button x:Name="btn9" Text="9" Grid.Row="2" Grid.Column="2" ZIndex="8" CornerRadius="0" BackgroundColor="Orange" Clicked="btn_Clicked" FontSize="36"/>
</Grid>
<Button Text="开始游戏" WidthRequest="220" Margin="20" Clicked="btnPlay_Clicked" FontSize="26"/>
</VerticalStackLayout>
Button[,] arrBtn = new Button[3, 3];
int unRow = 0, unCol = 0;
private void btn_Clicked(object sender, EventArgs e)
{
int row = ((Button)sender).ZIndex / 3;
int col = ((Button)sender).ZIndex % 3;
if(Math.Abs(unRow-row)+Math.Abs(unCol-col)==1)
{
string temp = arrBtn[unRow, unCol].Text;
arrBtn[unRow, unCol].Text = arrBtn[row, col].Text;
arrBtn[row, col].Text=temp;
arrBtn[unRow, unCol].IsVisible = true;
arrBtn[row, col].IsVisible = false;
unCol = col;
unRow = row;
for (int i = 0; i < 9; i++)
{
if (arrBtn[i / 3, i % 3].Text != Convert.ToString(i + 1))
{
break;
}
if (i == 8)
{
arrBtn[unRow,unCol].IsVisible = true;
DisplayAlert("消息", "恭喜您通过了游戏", "确定");//对话框
}
}
}
}
private void btnPlay_Clicked(object sender, EventArgs e)
{
arrBtn[0,0]= btn1;
arrBtn[0, 1] = btn2;
arrBtn[0, 2] = btn3;
arrBtn[1, 0] = btn4;
arrBtn[1, 1] = btn5;
arrBtn[1, 2] = btn6;
arrBtn[2, 0] = btn7;
arrBtn[2, 1] = btn8;
arrBtn[2, 2] = btn9;
arrBtn[unRow, unCol].IsVisible = true;
int[] arrNum = {1,2,3,4,5,6,7,8,9};
//抽题算法
Random rm = new Random();
for (int i = 0; i < 8; i++)
{
int rmNum = rm.Next(i,9);
int temp = arrNum[i];
arrNum[i] = arrNum[rmNum];
arrNum[rmNum] = temp;
}
for (int i = 0; i < 9; i++)
{
arrBtn[i / 3, i % 3].Text = arrNum[i].ToString();
}
int cover=rm.Next(0,9);
unRow = cover/3;
unCol = cover%3;
arrBtn[unRow,unCol].IsVisible=false;
}