public MainPage() { InitializeComponent(); _gameHistory = LocalStorage.Load(); // read from local storage and populate the observable collection. ListView.ItemsSource = _gameHistory; _gridSize = 4; DisplayScores(); }
// this method gets called when a user taps a rectangle private void Rectangle_Tapped(object sender, TappedRoutedEventArgs e) { // get the rectangle that was clicked var rect = (Rectangle)sender; // on first click, the tile flips if (_clickNo == 0) { RevealImage(rect); _firstRectangle = rect; _clickNo = 1; } else if (_clickNo == 1) { // on second click, tile flips // ignore clicks on the same image if (_firstRectangle == rect) { return; } RevealImage(rect); _secondRectangle = rect; _clickNo = 2; bool gameOver = _totalTilesLeft == 2; if (gameOver) { _currentScore += 10; // each match is worth 10 points if (_currentScore > LocalStorage.LoadHighScore()) { LocalStorage.SaveHighScore(_currentScore); } DisplayScores(); // adding a game to the game history observable collection will make it appear in the game history page. _gameHistory.Add(new Game(LocalStorage.Load().Count + 1, _currentScore, _gridSize, DateTime.Now)); // save all the games to local storage. LocalStorage.Save(_gameHistory); //display Game over message TxtGameOver.Visibility = Visibility.Visible; return; } } else if (_clickNo == 2) { // ton 3rd click, check the previous 2 rectangles to see if they match if (rect == _firstRectangle || rect == _secondRectangle) { // ignore clicks on the same two rectangles. return; } // use tag to determine if 2 rectangles are a pair bool rectanglesMatch = _firstRectangle.Tag.ToString() == _secondRectangle.Tag.ToString(); if (rectanglesMatch) { // remove the event handler so it can't be clicked again _firstRectangle.Tapped -= Rectangle_Tapped; _secondRectangle.Tapped -= Rectangle_Tapped; _totalTilesLeft -= 2; // we have 2 fewer tiles. _currentScore += 10; // user gets 10 points when getting a match if (_currentScore > LocalStorage.LoadHighScore()) { LocalStorage.SaveHighScore(_currentScore); } } else { // reset the 2 images that didn't match SetToDefault(_firstRectangle); SetToDefault(_secondRectangle); _currentScore -= 1; // user loses 5 if the make a mistake. // the minimum score is 0, prevent negative scores. if (_currentScore < 0) { _currentScore = 0; } } RevealImage(rect); // display the new image _firstRectangle = rect; // save it _clickNo = 1; } DisplayScores(); }