void image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { Image image = sender as Image; int selectPic = (int)image.DataContext; int column = Grid.GetColumn(image); int row = Grid.GetRow(image); if (this.RemovedPictureIndexs.Contains(selectPic) == true) { return; } moveCount ++; if (this.selectPicInfo == null) { this.selectPicInfo = new SelectPicInfo() { PictureIndex = selectPic, Column = column, Row = row }; string bitmapUri = string.Format(@"/images/Bitmap{0}.bmp", selectPic); BitmapImage bitmapImage = new BitmapImage(new Uri(bitmapUri, UriKind.Relative)); image.Source = bitmapImage; } else if (this.selectPicInfo.Column != column || this.selectPicInfo.Row != row) { string bitmapUri = string.Format(@"/images/Bitmap{0}.bmp", selectPic); BitmapImage bitmapImage = new BitmapImage(new Uri(bitmapUri, UriKind.Relative)); image.Source = bitmapImage; if (this.selectPicInfo.PictureIndex == selectPic) { this.selectPicInfo = null; this.RemovedPictureIndexs.Add(selectPic); if (this.RemovedPictureIndexs.Count >= 8) { if (MessageBoxResult.OK == MessageBox.Show("游戏结束!你总共用了" + moveCount.ToString() + "步", "恭喜你", MessageBoxButton.OK)) { this.InitPictures(); } } } else { UIElement preSelectPic = null; foreach (UIElement item in grdPics.Children) { if (Grid.GetRow(item) == selectPicInfo.Row && Grid.GetColumn(item) == selectPicInfo.Column) { preSelectPic = item; } } this.selectPicInfo = null; Task task = new Task(ResetPicture, image); task.Start(); task = new Task(ResetPicture, preSelectPic); task.Start(); } } else { MessageBox.Show("点击了重复的图像, 无效"); this.selectPicInfo = null; string bitmapUri = @"/images/BlankBitmap.bmp"; BitmapImage bitmapImage = new BitmapImage(new Uri(bitmapUri, UriKind.Relative)); image.Source = bitmapImage; } }
private void InitPictures() { this.RemovedPictureIndexs = new List<int>(); this.selectPicInfo = null; this.grdPics.Children.Clear(); moveCount = 0; List<int> startList = Enumerable.Range(0, 16).Select(value => value / 2).ToList(); List<int> randomSortedList = CommonFunction.RandomSort(startList); for (int i = 0; i < randomSortedList.Count; i++) { string bitmapUri = @"/images/BlankBitmap.bmp"; BitmapImage bitmapImage = new BitmapImage(new Uri(bitmapUri, UriKind.Relative)); Image image = new Image(); image.Source = bitmapImage; image.DataContext = randomSortedList[i]; image.MouseLeftButtonDown += image_MouseLeftButtonDown; Grid.SetColumn(image, i % 4); Grid.SetRow(image, i / 4); this.grdPics.Children.Add(image); } }