Print 

Author Topic: C# Hangman?  (Read 8011 times)

Offline Dusaro

  • Junior Poster
  • **
  • Posts: 150
  • AWPS are for n00bs
C# Hangman?
« on: August 14, 2012, 02:42:54 AM »
Well, in Information Communication Technology Advanced at my high school, we have been given a task to make a hangman game in C#.
I have the main idea of how to do it but i got a little stuck...
Using Regex I am trying to replace the generated "_ " per letter with the correct letter if they got it correct.
Can anybody help me?

So far I have this:

Code: [Select]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        string word;
        int games;
        string newword;
        List<string> words = new List<string>();
        List<string> guessed = new List<string>();


        private void button1_Click(object sender, EventArgs e)
        {
            if (txtGames.Text != "")
            {
                if (IsNumeric(txtGames.Text))
                {
               
               
                    games = Convert.ToInt32(txtGames.Text);
                    if (games >= 4)
                    {
                        MessageBox.Show("You can only play 3 games at a time.");
                    }
                    else if (games <= 0)
                    {
                        btnBegin.Enabled = true;
                        txtGames.Enabled = true;
                        MessageBox.Show("Please enter more that 0 games");
                    }
                    else
                    {
                        btnBegin.Enabled = false;
                        txtGames.Enabled = false;
                        games--;
                        txtGames.Text = games.ToString();
                        GenerateWord();
                    }
                }
            }
            else
            {
                MessageBox.Show("Please enter an amount of games to play");
            }
        }

        private void GenerateWord()
        {

            Random rand = new Random();
            int r = rand.Next(words.Count());
            word = words[r];
            word.ToCharArray();

            string newword = Regex.Replace(word, @"[a-zA-Z0-9]", "_ ");

            lblWord.Text = newword;
        }
       
        private void ReGenerateWord()
        {
            if (guessed.Contains("a"))
            {
                newword = Regex.Replace(word, @"[b-z]", "_ ");
            }
           
            else if (guessed.Contains("b"))
            {
                newword = Regex.Replace(word, @"[a-ac-z]", "_ ");
            }
            lblWord.Text = newword;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            words.Add("apple");
            words.Add("camera");
            words.Add("teacher");
            words.Add("abandon");
            words.Add("normal");
            words.Add("positive");
            words.Add("perceive");
            words.Add("revolution");
            words.Add("release");
            words.Add("transit");
            words.Add("uniform");
        }

        private void btnGuess_Click(object sender, EventArgs e)
        {
            if (guessed.Contains(txtInput.Text))
            {
                    txtInput.Text = "";
                    MessageBox.Show("You have already guessed this letter!");
            }
            else
            {
                guessed.Add(txtInput.Text);
                txtInput.Text = "";
                ReGenerateWord();
            }
        }

        private void txtGames_TextChanged(object sender, EventArgs e)
        {

        }

        public static Boolean IsNumeric(string stringToTest)
        {
               // int result;
               // return int.TryParse(stringToTest, out result);
                try
                {
                    Convert.ToInt32(stringToTest);
                    return true;
                }
                catch
                {
                    MessageBox.Show("Please only insert numeric values");
                    return false;
                }
        }

    }
}

I have the general idea of how to do it but i don't know how i would go about checking for each letter and replacing only that "_ " with the proper letter in the ReGenerateWord private void.

If anyone can help me, or if anybody needs more information please reply and I will get back to you :)

Thanks
--FM






Dusaro/FM's Known HB History
Nov 13, 2010: Joined HB
UNKNOWN PERIOD
Jul 28, 2011: Reapplied for HB
Jul 29, 2011: ReAccepted into HB
Jul 31, 2011: RePromoted to Forum Moderator(Field Marshall)
Jan 30, 2012: Promoted to Co-Leader
July 27, 2012: HB Disbanded
Dec 2, 2012: HB Reopened
Dec 2, 2012: Became Advisor for Anarchy(new leader)



Offline BFM_Kiwi

  • Major
  • *
  • Posts: 9174
Re: C# Hangman?
« Reply #1 on: August 15, 2012, 03:38:49 AM »
I think doing the regex one letter at a time and trying to work out the [c-z] stuff is going to be hard, and you'll have to do it 26 times!

I'd do something like this - go through each letter of the original word, and if the letter is one of the guesses, then output that letter, otherwise "_", and build up a string.

      StringBuilder sb = new StringBuilder();     // start with empty string

      for ( int i = 0; i < word.length; i++ )       // for each letter in the word
      {
          letter = word.SubString( i, 1 );
          if ( guessed.Contains( letter )
               sb.Append(letter);                         // add the actual letter (already guessed)
         else
               sb.Append("_");                           // add a _ since they haven't guessed this one yet
      }

      newword = sb.ToString();

Offline Dusaro

  • Junior Poster
  • **
  • Posts: 150
  • AWPS are for n00bs
Re: C# Hangman?
« Reply #2 on: August 15, 2012, 05:05:05 PM »
Thank you Kiwi!!

The final code
I still have a bit of work on it but this is with kiwi's fix :)

Code: [Select]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        string word;
        int games;
        string newword;
        int i;
        List<string> words = new List<string>();
        List<string> guess = new List<string>();
        char[] letters;
        string input;
        string letter;
       

        private void button1_Click(object sender, EventArgs e)
        {
            if (txtGames.Text != "")
            {
                if (IsNumeric(txtGames.Text))
                {
               
               
                    games = Convert.ToInt32(txtGames.Text);
                    if (games >= 4)
                    {
                        MessageBox.Show("You can only play 3 games at a time.");
                    }
                    else if (games <= 0)
                    {
                        btnBegin.Enabled = true;
                        txtGames.Enabled = true;
                        MessageBox.Show("Please enter more that 0 games");
                    }
                    else
                    {
                        btnBegin.Enabled = false;
                        txtGames.Enabled = false;
                        games--;
                        txtGames.Text = games.ToString();
                        GenerateWord();
                    }
                }
            }
            else
            {
                MessageBox.Show("Please enter an amount of games to play");
            }
        }

        private void GenerateWord()
        {
            lblWord.Text = "";
            newword = "";
            char[] letters = word.ToCharArray();
            var guesses = string.Join(",", guess.ToArray());

             StringBuilder sb = new StringBuilder();     // start with empty string

            for ( int i = 0; i < word.Length; i++ )       // for each letter in the word
            {
                 letter = word.Substring( i, 1 );
                if ( guess.Contains( letter ))
                sb.Append(letter);                         // add the actual letter (already guessed)
            else
               sb.Append("_ ");                           // add a _ since they haven't guessed this one yet
            }

            newword = sb.ToString();


            lblWord.Text = newword;
            //newword = word.Replace("a", _);
            //lblWord.Text = guessed.ToString();
            //string newword = Regex.Replace(word, @"[a-zA-Z0-9]", "_ ");
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            words.Add("apple");
            words.Add("camera");
            words.Add("teacher");
            words.Add("abandon");
            words.Add("normal");
            words.Add("positive");
            words.Add("perceive");
            words.Add("revolution");
            words.Add("release");
            words.Add("transit");
            words.Add("uniform");

            Random rand = new Random();
            int r = rand.Next(words.Count());
            word = words[r];
        }

        private void btnGuess_Click(object sender, EventArgs e)
        {
            input = txtInput.Text;
            if (guess.Contains(input))
            {
                    txtInput.Text = "";
                    MessageBox.Show("You have already guessed this letter!");
            }
            else
            {
                guess.Add(input);
                if (word.Contains(input))
                {
                    txtInput.Text = "";
                    label3.Text = label3.Text + input;
                    GenerateWord();
                }
            }
            txtInput.Text = "";
           
        }

        private void txtGames_TextChanged(object sender, EventArgs e)
        {

        }

        public static Boolean IsNumeric(string stringToTest)
        {
               // int result;
               // return int.TryParse(stringToTest, out result);
                try
                {
                    Convert.ToInt32(stringToTest);
                    return true;
                }
                catch
                {
                    MessageBox.Show("Please only insert numeric values");
                    return false;
                }
        }

    }
}






Dusaro/FM's Known HB History
Nov 13, 2010: Joined HB
UNKNOWN PERIOD
Jul 28, 2011: Reapplied for HB
Jul 29, 2011: ReAccepted into HB
Jul 31, 2011: RePromoted to Forum Moderator(Field Marshall)
Jan 30, 2012: Promoted to Co-Leader
July 27, 2012: HB Disbanded
Dec 2, 2012: HB Reopened
Dec 2, 2012: Became Advisor for Anarchy(new leader)



Offline BFM_Kiwi

  • Major
  • *
  • Posts: 9174
Re: C# Hangman?
« Reply #3 on: August 15, 2012, 10:42:45 PM »
Those sorts of things are easier if you write tests.  I don't know if you're familiar with nUnit.  If not, you can just have your main() call a routine that does something like:

public void MyTest()
{
     guesses = new List<string> { "a", "e", "s" };
     word = "ponies";
     GenerateWord();
     // at this point newword should equal "_ _ _ _ e s"
}

That way you don't have to do a lot of typing and actually play the whole game to see if it works.

Print