How to create album matching Game with XAML

This is a simple game created with Xaml. It plays a song, while the player should listen to it and select the right album for the song. If the right album is selected then you get points counting else you lose points till the game is over.

Sreenshorts
















Copy and paste this Codes in MainPage.xaml

<Page
x:Class="AlbumCoverMatchGame.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:AlbumCoverMatchGame"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:data="using:AlbumCoverMatchGame.Models"
mc:Ignorable="d">
<Page.Resources>
<Storyboard x:Name="Countdown" Completed="Countdown_Completed">
<DoubleAnimationUsingKeyFrames EnableDependentAnimation=
"True" Storyboard.TargetName="MyProgressBar" Storyboard.TargetProperty="(RangeBase.Value)">
<DiscreteDoubleKeyFrame KeyTime="0" Value="100"/>
<DiscreteDoubleKeyFrame KeyTime="0:0:1" Value="100"/>
<DiscreteDoubleKeyFrame KeyTime="0:0:2" Value="90"/>
<DiscreteDoubleKeyFrame KeyTime="0:0:3" Value="80"/>
<DiscreteDoubleKeyFrame KeyTime="0:0:4" Value="70"/>
<DiscreteDoubleKeyFrame KeyTime="0:0:5" Value="60"/>
<DiscreteDoubleKeyFrame KeyTime="0:0:6" Value="50"/>
<DiscreteDoubleKeyFrame KeyTime="0:0:7" Value="40"/>
<DiscreteDoubleKeyFrame KeyTime="0:0:8" Value="30"/>
<DiscreteDoubleKeyFrame KeyTime="0:0:9" Value="20"/>
<DiscreteDoubleKeyFrame KeyTime="0:0:10" Value="10"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</Page.Resources>
<Grid Grid.Loaded="Grid_Loaded">
<Grid.RowDefinitions>
<RowDefinition Height="100"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Margin="10">
<ProgressBar Name ="MyProgressBar"
Minimum="0"
Maximum="100"
Value="100"
Height="20"
Foreground="Blue"/>
<TextBlock Name="InstructionTextBlock"
Text="" Foreground="Blue"
HorizontalAlignment="Center"/>
<MediaElement Name="MyMediaElement"
AutoPlay="True"/>
</StackPanel>
<StackPanel Grid.Row="1" Orientation="Vertical" Margin="10">
<GridView Name="SongGridView" ItemsSource="{x:Bind Songs}"
IsItemClickEnabled="True"
ItemClick="SongGridView_ItemClick">
<GridView.ItemTemplate>
<DataTemplate x:DataType="data:Song">
<Grid>
<Image Name="AlbumArtImage"
Height="75"
Width="75"
Source="{x:Bind AlbumCover}"/>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
<TextBlock Name="ResultTextBlock"/>
<TextBlock Name="TitleTextBlock"/>
<TextBlock Name="ArtistTextBlock"/>
<TextBlock Name="AlbumTextBlock"/>
<Button Name="PlayAgainButton"
Content="Play Again" Background="Red"
HorizontalAlignment="Center"
Visibility="Collapsed"
Click="PlayAgainButton_Click"/>
</StackPanel>
<Grid Grid.Row="1">
<ProgressRing Name="startupProgresssRing"
HorizontalAlignment="Center"
VerticalAlignment="Center" Width="100"
Height="100" Foreground="Gray"/>
</Grid>
</Grid>
</Page>

Copy and paste this code in the  MainPage.xaml.cs


using AlbumCoverMatchGame.Models;

using System;

using System.Collections.Generic;

using System.Collections.ObjectModel;

using System.IO;

using System.Linq;

using System.Runtime.InteropServices.WindowsRuntime;

using System.Threading.Tasks;

using Windows.Foundation;

using Windows.Foundation.Collections;

using Windows.Storage;

using Windows.Storage.FileProperties;

using Windows.UI;

using Windows.UI.Xaml;

using Windows.UI.Xaml.Controls;

using Windows.UI.Xaml.Controls.Primitives;

using Windows.UI.Xaml.Data;

using Windows.UI.Xaml.Input;

using Windows.UI.Xaml.Media;

using Windows.UI.Xaml.Media.Imaging;

using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace AlbumCoverMatchGame

{

///


/// An empty page that can be used on its own or navigated to within a Frame.

///


public sealed partial class MainPage : Page

{


private ObservableCollection Songs;

private ObservableCollection Allsongs;

bool _playingMusic = false;

int _round = 0;

int _totalscore = 0;

public MainPage()

{

this.InitializeComponent();

Songs = new ObservableCollection();

}

//Get access to music librabry method

private async Task RetrieveFilesInFolders(ObservableCollection list, StorageFolder parent)

{

foreach (var item in await parent.GetFilesAsync())

{

if (item.FileType == ".mp3")

list.Add(item);

}

foreach (var item in await parent.GetFoldersAsync())

{

await RetrieveFilesInFolders(list, item);

}

}

// 2. choose random songs from librabry helper method

private async Task> pickRandomSongs(ObservableCollection allSongs)

{

Random random = new Random();

var songCount = allSongs.Count;

var randomSongs = new List();

while (randomSongs.Count < 13) 

var randomNumber = random.Next(songCount); 
var randomSong = allSongs[randomNumber]; // I want two things to not happen before adding the random song to a LIST.: //1. Don't pick same song twice! //2.Don't pick a song from an album I've already picked! 
MusicProperties randomSongMusicProperties = await randomSong.Properties. GetMusicPropertiesAsync(); bool isDuplicate = false; foreach (var song in randomSongs)
 { 
MusicProperties songMusicProperties = await song.Properties.GetMusicPropertiesAsync(); 
if (string.IsNullOrEmpty(randomSongMusicProperties.Album)|| randomSongMusicProperties.Album == songMusicProperties.Album) isDuplicate = true; 
}
 if (!isDuplicate) randomSongs.Add(randomSong); 
return randomSongs; 

} // 3.Pluck off meta data from selected songs HELPER method private async Task PopulateSongList(List files)

{

int id = 0;

foreach (var file in files)

{

MusicProperties songProperties = await file.Properties.GetMusicPropertiesAsync();

StorageItemThumbnail currentThumb = await file.GetThumbnailAsync(ThumbnailMode.MusicView, 200, ThumbnailOptions.UseCurrentScale);

var albumCover = new BitmapImage();

albumCover.SetSource(currentThumb);

var song = new Song(); // Create a new Song Object from the Class Song.

song.Id = id;

song.Title = songProperties.Title;

song.Artist = songProperties.Artist;

song.Album = songProperties.Album;

song.AlbumCover = albumCover;

song.SongFile = file;

Songs.Add(song); // Then add the song to the instance of our observableCollection of Song Class

id++;

}

}

private async void SongGridView_ItemClick(object sender, ItemClickEventArgs e)

{

// Evaluate the user selection

// user should able to select

if (_playingMusic == true)

{

var clickedSong = (Song)e.ClickedItem;

var correctsong = Songs.FirstOrDefault(p => p.Selected == true);

Countdown.Pause();

MyMediaElement.Stop();

// if song is selected 

Uri uri;

int score;

if (clickedSong.Selected)

{

uri = new Uri("ms-appx:///Assets/correct.png");

score = (int)MyProgressBar.Value;

}

else

{

uri = new Uri("ms-appx:///Assets/incorrect.png");

score = (int)MyProgressBar.Value * -1;

}

StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(uri);

var filestream = await file.OpenAsync(FileAccessMode.Read);

await clickedSong.AlbumCover.SetSourceAsync(filestream);

_totalscore += score;

_round++;

ResultTextBlock.Text = string.Format("score:{0}, TotalScore after {1} Rounds: {2}", score , _round , _totalscore);

TitleTextBlock.Text = string.Format("The Tittle is: {0}", correctsong.Title);

ArtistTextBlock.Text = string.Format("Perfomed by: {0}", correctsong.Artist);

AlbumTextBlock.Text = string.Format("On Album: {0}", correctsong.Album);

clickedSong.Used = true;

correctsong.Selected = false;

correctsong.Used = true;

if (_round >= 5)

{

InstructionTextBlock.Text = string.Format("Hey! Game over... Your Totalscore:{0}", _totalscore);

PlayAgainButton.Visibility = Visibility.Visible;

}

else

{

StartCooldown();

}

}

}

private async void PlayAgainButton_Click(object sender, RoutedEventArgs e)

{

await PrepareNewGame();

PlayAgainButton.Visibility = Visibility.Collapsed;

}

//Helper method for the Grid_Loaded

private async Task> setupMusicList()

{

// 1. Get access to music library

StorageFolder folder = KnownFolders.MusicLibrary;

var allSongs = new ObservableCollection();

await RetrieveFilesInFolders(allSongs, folder);

return allSongs;

}

private async Task PrepareNewGame()

{

Songs.Clear();

// 2. choose random songs from librabry

var randomsongs = await pickRandomSongs(Allsongs);

// 3.Pluck off meta data from selected songs

await PopulateSongList(randomsongs);

StartCooldown();

//State Management

InstructionTextBlock.Text = "Get ready ...";

ResultTextBlock.Text = "";

TitleTextBlock.Text = "";

ArtistTextBlock.Text = "";

AlbumTextBlock.Text = "";

_totalscore = 0;

_round = 0;

}

private async void Grid_Loaded(object sender, RoutedEventArgs e)

{

startupProgresssRing.IsActive = true;

Allsongs = await setupMusicList();

await PrepareNewGame();

startupProgresssRing.IsActive = false;

StartCooldown();

}

private void StartCooldown()

{

_playingMusic = false;

SolidColorBrush brush = new SolidColorBrush(Colors.Blue);

MyProgressBar.Foreground = brush;

InstructionTextBlock.Text = string.Format("Get ready for round {0} ....", _round + 1);

InstructionTextBlock.Foreground = brush;

Countdown.Begin();

}

private void StartCountdown()

{

_playingMusic = true;

SolidColorBrush brush = new SolidColorBrush(Colors.Red);

MyProgressBar.Foreground = brush;

InstructionTextBlock.Text = "GO";

InstructionTextBlock.Foreground = brush;

Countdown.Begin();

}

private async void Countdown_Completed(object sender, object e)

{

if (!_playingMusic)

{

// Start playing some music

var song = pickSongs();

MyMediaElement.SetSource(awaitsong.SongFile.OpenAsync(FileAccessMode.Read), song.SongFile.ContentType);

// Start countdown 

StartCountdown();

}

}

private Song pickSongs()

{

Random random = new Random();

var unusedSongs = Songs.Where(p => p.Used == false);

var count = unusedSongs.Count();

var RandomNumber = random.Next(count);

var RandomSongs = unusedSongs.ElementAt(RandomNumber);

RandomSongs.Selected = true;

return RandomSongs;

}

}

}
Happy reading, I hope this help

No comments:

Post a Comment

Note: only a member of this blog may post a comment.