Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Gauge for SharePoint
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » Silverlight » Hangman game in Silverlight

Hangman game in Silverlight

All work and no play makes Jack a dull boy. It means that without time off from work, a person becomes both bored and boring. So come and play the hangman game.

Author Rank :
Page Views : 3873
Downloads : 167
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
HangmaninSL.zip
 
 
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


1.gif

What is this game?

Hangman is a word guessing game. The player tries to guess it by suggesting letters.

The word to guess is represented by a row of dashes, giving the number of letters. If the guessing player suggests a letter which occurs in the word, the other player writes it in all its correct positions. If the suggested letter does not occur in the word, the other player draws one element of the hangman diagram as a tally mark.

Let's see how to implement this in our program.

First thing we need is to design the page.

Below is the XAML for our page.

<UserControl
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
          x:Class="HangmaninSL.MainPage"
          Width="640" Height="480">
          <Canvas x:Name="LayoutRoot" Background="#FF8CCDDE" Width="750">
                  <Path Data="M87.5,0.5 C133.29648,0.5 170.82834,4.363894 174.24632,9.2690659 L174.38034,9.499999 L174.5,9.499999 L174.5,10 L174.5,30.5 L0.5,30.5 L0.5,10 L0.5,9.499999 L0.6196655,9.499999 L0.75368494,9.2690659 C4.1716671,4.363894 41.70351,0.5 87.5,0.5 z" Fill="#FF04F513" Height="21" Canvas.Left="197" Stretch="Fill" Stroke="#FF04F513" Canvas.Top="189" UseLayoutRounding="False" Width="185"/>                             <Path Data="M156.36375,15.51034 L146.66528,15.516942 L156.36375,27.089062 z M171.49979,0.5 L171.50999,15.50003 L171.36374,15.500132 L171.36374,127.34 L156.36375,127.34 L156.36375,42.205841 L134.00331,15.525562 L0.51022357,15.616439 L0.5,0.61641157 z" Fill="#FF937407" Height="127.84" Canvas.Left="116.47" RenderTransformOrigin="0.952640891075134,0.50328034394114" Stretch="Fill" Stroke="#FF937407" Canvas.Top="-29.16" UseLayoutRounding="False" Width="172.01">
                                      <Path.RenderTransform>
                                                <CompositeTransform Rotation="-89.961"/>
                                      </Path.RenderTransform>
                             </Path>
                             <Path Data="M114,52 L114.66666,128" Fill="#FF937407" Height="47.667" Canvas.Left="295" Stretch="Fill" Stroke="#FF937407" Canvas.Top="43" UseLayoutRounding="False" Width="1.667"/>
                             <Rectangle Fill="#FF937407" Height="127.001" Canvas.Left="272.334" Stroke="#FF937407" Canvas.Top="-28.321" Width="16" RenderTransformOrigin="0.5,0.5" UseLayoutRounding="False" >
                                      <Rectangle.RenderTransform>
                                                <CompositeTransform Rotation="-89.961"/>
                                      </Rectangle.RenderTransform>
                             </Rectangle>
                             <Rectangle Fill="#FF937407" Height="3.671" Canvas.Left="290.67" Stroke="#FF937407" Canvas.Top="88.635" Width="11.334" RenderTransformOrigin="0.5,0.5" UseLayoutRounding="False" >
                                      <Rectangle.RenderTransform>
                                                <CompositeTransform Rotation="-89.961"/>
                                      </Rectangle.RenderTransform>
                             </Rectangle>
                             <Ellipse x:Name="loop1" Fill="#FFFDFDFB" Height="29" Canvas.Left="285" Stroke="#FF937407" Canvas.Top="95" Width="24"/>
                             <Ellipse x:Name="head" Fill="#FFFDFDFB" Height="20" Canvas.Left="285" Stroke="#FF0E0E0D" Canvas.Top="95" Width="24" StrokeThickness="3" Visibility="Collapsed"/>
                             <Rectangle x:Name="body1" Fill="#FF0E0E0E" Height="19" Canvas.Left="295" Stroke="#FF080808" StrokeThickness="3" Canvas.Top="115" Width="3" Visibility="Collapsed"/>
                             <Rectangle x:Name="leftleg" Fill="#FF0E0E0E" Height="23.99" Canvas.Left="288.631" Stroke="#FF080808" StrokeThickness="3" Canvas.Top="133.591" Width="3" RenderTransformOrigin="0.5,0.5" UseLayoutRounding="False" d:LayoutRounding="Auto" Visibility="Collapsed">
                                      <Rectangle.RenderTransform>
                                                <CompositeTransform Rotation="33.269"/>
                                      </Rectangle.RenderTransform>
                             </Rectangle>
                             <Rectangle x:Name="rightleg" Fill="#FF0E0E0E" Height="22.385" Canvas.Left="302.998" Stroke="#FF080808" StrokeThickness="3" Canvas.Top="134.674" Width="3" RenderTransformOrigin="0.5,0.5" UseLayoutRounding="False" d:LayoutRounding="Auto" Visibility="Collapsed">
                                      <Rectangle.RenderTransform>
                                                <CompositeTransform Rotation="143.845"/>
                                      </Rectangle.RenderTransform>
                             </Rectangle>
                             <Rectangle x:Name="righthand" Fill="#FF0E0E0E" Height="19" Canvas.Left="311" Stroke="#FF080808" StrokeThickness="3" Canvas.Top="117" Width="1" RenderTransformOrigin="0.5,0.5" UseLayoutRounding="False" d:LayoutRounding="Auto" Visibility="Collapsed">
                                      <Rectangle.RenderTransform>
                                                <CompositeTransform Rotation="119.21"/>
                                      </Rectangle.RenderTransform>
                             </Rectangle>
                             <Rectangle x:Name="lefthand" Fill="#FF0E0E0E" Height="19" Canvas.Left="280" Stroke="#FF080808" StrokeThickness="3" Canvas.Top="118" Width="1" RenderTransformOrigin="0.5,0.5" UseLayoutRounding="False" d:LayoutRounding="Auto" Visibility="Collapsed">
                                      <Rectangle.RenderTransform>
                                                <CompositeTransform Rotation="54.316"/>
                                      </Rectangle.RenderTransform>
                            </Rectangle>
                             <TextBlock x:Name="deadtxt" Height="35" Canvas.Left="195" TextWrapping="Wrap" Canvas.Top="210" Width="198" FontWeight="Bold" FontSize="24" Text="You are dead!" Foreground="#FFFD0606" Visibility="Collapsed"/>
                             <Button x:Name="trybutton" Click="trybutton_Click" Content="Try Again" Height="29" Canvas.Left="211" Canvas.Top="245" Width="140" FontWeight="Bold" FontSize="16" Foreground="#FF0E0E0D" Visibility="Collapsed"/>
          </Canvas>
</UserControl>

Rest of the controls you see on page load is done dynamically in code behind. Let's see each one of this separately.

For showing 26 alphabets I have created buttons for each on them as shown below:

for (int i = 0; i < 26; i++)
{
    Button b = new Button();
    b.Name = "b" + i;
    b.Content = alph[i];
    b.Width = 25;
    b.Height = 25;
    b.FontWeight = FontWeights.Bold;
    sp.Children.Add(b);
}

Where "alph" is an array of alphabets. This buttons are placed in a stackpanel named "sp".

Now, on every page load we select random words and accordingly we show separate dashes for the number of characters in the word. The code is as follows:

Random r = new Random();
s = words[r.Next(0, words.Length)];
for (int j = 0; j < s.Length; j++)
{
    r1 = new Rectangle();
    r1.Width = 25;
    r1.Height = 5;
    SolidColorBrush sb1 = new SolidColorBrush();
    sb1.Color = Colors.Black;
    r1.Fill = sb1;
    TextBox t = new TextBox();
    t.Name = "t" + j;
    t.Text = s[j].ToString().ToUpper();
    t.Visibility = Visibility.Collapsed;
    t.Width = 25;
    t.Height = 25;
    t.IsEnabled = false;
    g.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength((double)40) });
    g1.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength((double)40) });
    g1.ShowGridLines = true;
    Grid.SetColumn(t, j);
    Grid.SetColumn(r1, j);
    if (t.Text != " ")
    {
        g.Children.Add(r1);
        g1.Children.Add(t);
    }
    nooftxtbox++;
}

Now we will see the actual functioning of the program. On every button click I am matching the character from button and the characters in the word. When we have matching character display it in its position. Else we draw one part of the body of the man to indicate that the guess is wrong. For every wrong guess we draw one part of the body.

After six wrong attempts the game finishes.

Here is the code:

bstr = ((Button)sender).Content.ToString();
for (int j = 0; j <= nooftxtbox; j++)
{
    txtName = g1.Children[j] as TextBox;
    if (txtName.Text == bstr)
    {
        txtName.SetValue(Grid.ColumnProperty, j);
        txtName.Visibility = Visibility.Visible;
        txtName.IsEnabled = false;
        ((Button)sender).Visibility = Visibility.Collapsed;
        flag = true;
    }
    else
    {
        ((Button)sender).Visibility = Visibility.Collapsed;
    }
}

Code for restarting the application(Try again button code):

private void trybutton_Click(object sender, RoutedEventArgs e)
{
    this.LayoutRoot.Children.Add(new MainPage());
}

2.gif

Download full source code and enjoy the game!

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Author
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
Nice by Mahesh On September 10, 2010
May be we should have a live games section where we can actually play the games.
Reply | Email | Modify 
Game not working well by latonia On February 10, 2011
Nothing seems to happen after guessing all the letters correctly.
Reply | Email | Modify 
error by Tony On July 7, 2011
It seems that if you win, nothing happens. Here's what I added so that it is a little cleaner XAML: <TextBlock x:Name="wintxt" Height="35" Canvas.Left="195" TextWrapping="Wrap" Canvas.Top="210" Width="198" FontWeight="Bold" FontSize="24" Text="You win!" Foreground="#FFFD0606" Visibility="Collapsed"/> <Button x:Name="playbutton" Click="trybutton_Click" Content="Play Again" Height="29" Canvas.Left="211" Canvas.Top="245" Width="140" FontWeight="Bold" FontSize="16" Foreground="#FF0E0E0D" Visibility="Collapsed"/> private bool solved(object sender) { int i = 0; TextBox txtName; string bstr; bstr = ((Button)sender).Content.ToString(); for (int j = 0; j <= nooftxtbox; j++) { txtName = g1.Children[j] as TextBox; if (txtName.Visibility == System.Windows.Visibility.Visible) { i++; } if (txtName.Text == bstr) { txtName.SetValue(Grid.ColumnProperty, j); txtName.Visibility = Visibility.Visible; txtName.IsEnabled = false; ((Button)sender).Visibility = Visibility.Collapsed; } else { ((Button)sender).Visibility = Visibility.Collapsed; } } if (i-1 == nooftxtbox) { hideButtons(); wintxt.Visibility = Visibility.Visible; playbutton.Visibility = Visibility.Visible; return true; } else { return false; } } private void hideButtons() { //hide all other buttons Button b; for (int k = 0; k <= 25; k++) { b = (Button)FindName("b" + k); b.Visibility = Visibility.Collapsed; } } private void b_Click(object sender, System.Windows.RoutedEventArgs e) { bool flag = false; string bstr; TextBox txtName; bstr = ((Button)sender).Content.ToString(); if (x != 6 && !solved(sender)) { for (int j = 0; j <= nooftxtbox; j++) { txtName = g1.Children[j] as TextBox; if (txtName.Text == bstr) { txtName.SetValue(Grid.ColumnProperty, j); txtName.Visibility = Visibility.Visible; txtName.IsEnabled = false; ((Button)sender).Visibility = Visibility.Collapsed; flag = true; } else { ((Button)sender).Visibility = Visibility.Collapsed; } } if (!flag) { x = x + 1; } if (x == 1) { loop1.Visibility = Visibility.Collapsed; head.Visibility = Visibility.Visible; } if (x == 2) { body1.Visibility = Visibility.Visible; } if (x == 3) { lefthand.Visibility = Visibility.Visible; } if (x == 4) { righthand.Visibility = Visibility.Visible; } if (x == 5) { leftleg.Visibility = Visibility.Visible; } } if (!solved(sender) && x == 6) { deadtxt.Visibility = Visibility.Visible; rightleg.Visibility = Visibility.Visible; trybutton.Visibility = Visibility.Visible; hideButtons(); } } I am sure it can be refactored further but at least all the rules of the game now work.
Reply | Email | Modify 
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.