Hangman

I'm not sure how to get the users response to link with the string

Page 1 of 1

3 Replies - 4882 Views - Last Post: 18 December 2009 - 12:04 PM Rate Topic: -----

#1 Sp1nxer  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 18-December 09

Hangman

Posted 18 December 2009 - 05:02 AM

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Diagnostics;
using System.IO;

namespace Assessment4HangMan
{
	class Program
	{
		// class constants
		const int iNUMCALC = 3;
		const int iRANDMAX = 10;
		const int iMILLITOSEC = 1000;
		const String sFILENAME = "scoreboard.txt";

		static void Main(string[] args)
		{
			// declare variables
			int iOption;

			// display menu and get option choice from user
			iOption = getMenuOption();

			// keep looping through program and menu systm
			while (iOption != 4)
			{
				Console.Clear();

				// process menu choice
				switch (iOption)
				{
					case 1: //instructions
						displayInstructions();
						break;

					case 2: // Play Hangman
						PlayHangman();
						break;

					case 3: // display the scoreboard
						displayScoreboard();
						break;

				}

				// wait for user to press a key
				Console.WriteLine();
				Console.WriteLine("Press any key to continue.");
				Console.ReadKey();
				Console.Clear();

				// display the menu again
				iOption = getMenuOption();
			}
		}

		// Allows the user to see the menu
		static int getMenuOption()
		{
			int iChoice;

			// display menu
			Console.WriteLine("Recreation of Hangman 2009!");
			Console.WriteLine();
			Console.WriteLine("1: Instructions");
			Console.WriteLine("2: Play Hangman");
			Console.WriteLine("3: Scoreboard");
			Console.WriteLine("4: Exit");

			Console.WriteLine();
			Console.Write("Please enter 1 - 3 or 4 to close: ");
			iChoice = Convert.ToInt32(Console.ReadLine());

			// validate user input
			while (iChoice < 1 || iChoice > 4)
			{
				Console.Write("Incorrect option. Please re-enter: ");
				iChoice = Convert.ToInt32(Console.ReadLine());
			}

			// return menu choice selected
			return iChoice;
		}

		// function to display instructions
		static void displayInstructions()
		{
			Console.Write("You will be giving so many characters");
			Console.WriteLine(" you will have 10 tries");
			Console.Write("If you guess the word correctly");
			Console.WriteLine(" you will be added to our scoreboard.");
		}

		// function to play hangman
		static void PlayHangman()
		{
			// Create variables
			int iCount;
			int iSelect;
			int iPieces;
			int iLifes = 10;
			int iAnswer;
			int iGuess;
			int iCorrectCount;
			int iTime;

			char cGuess;

			String sName;

			// 1D string array to represent Hangman
			String[] sHorseParts = {"   __", "__\n",
									"   |/", " |\n",
									"   |", " ( )", "\n",
									"   |", " -|-\n",
									"   |", "  /\\\n"};

			string[] sWordList = new string[5];
			sWordList[0] = "Computer";
			sWordList[1] = "Systems";
			sWordList[2] = "Laptop";
			sWordList[3] = "Windows";
			sWordList[4] = "Crash";

			//declare the word list display/output condition
			if (sWordList[0].Length == 7)
			{
				Console.WriteLine(" The word is : _ _ _ _ _ _ _ ");

			}
			else if (sWordList[1].Length == 7)
			{
				Console.WriteLine(" The word is : _ _ _ _ _ _ _ _ _ _ _ ");
			}
			else if (sWordList[2].Length == 6)
			{
				Console.WriteLine(" The word is : _ _ _ _ _ _ _ ");
			}
			else if (sWordList[3].Length == 7)
			{
				Console.WriteLine(" The word is : _ _ _ _ _ _ _ _ ");
			}
			else if (sWordList[4].Length == 5)
			{
				Console.WriteLine(" The word is : _ _ _ _ _ _ _ _ ");
			}



			// create stopwatch
			Stopwatch stopWatch = new Stopwatch();

			// start stopwatch
			stopWatch.Start();

			// initialise count of correct questions answered
			iCorrectCount = 0;

			// repeat for each question
			for (iCount = 1; iCount <= iNUMCALC; iCount++)
			{

				Console.WriteLine();
				Console.WriteLine("				 Enter a Letter!");
				Console.WriteLine();
				bool repeat = false;
				do
				{
					Console.Write("What Is Your letter? : ");
					string sGuess = Console.ReadLine();
					if (sGuess.Length > 1)
					{
						Console.WriteLine("only one letter is allowed");
						repeat = true;
					}
					else
					{
						cGuess = Convert.ToChar(sGuess);
						if (char.IsLetter(cGuess) == true)
						{
							cGuess = char.ToUpper((char)cGuess);//changing all character input to uppercase
							repeat = false;
						}
						else
						{
							Console.WriteLine("You can only enter letter values, please re-enter");
							repeat = true;
						}
					}
				} while (repeat);
			}

			// stop stopwatch
			stopWatch.Stop();
			iTime = (int)stopWatch.ElapsedMilliseconds / iMILLITOSEC;

			// reset stopwatch
			stopWatch.Reset();

			// Recorded time
			Console.WriteLine();
			Console.WriteLine("You answered " + iCorrectCount + " questions correctly.");
			Console.WriteLine("Your time was " + iTime + " seconds");

			// check to see if guess was correct
			if (iCorrectCount == iNUMCALC)
			{
				Console.WriteLine();
				Console.WriteLine("Congratulations! You will be added to our scoreboard.");

				// obtain user's name
				Console.Write("Enter your name: ");
				sName = Console.ReadLine();

				// append name and time to scoreboard file
				using (StreamWriter sw = new StreamWriter(sFILENAME, true))
				{
					sw.WriteLine(sName + ", " + iTime);
					sw.Close();
				}
			}
		}

		// This code desplys the scoreboard
		static void displayScoreboard()
		{
			Console.WriteLine("Current Scoreboard");
			Console.WriteLine();

			// SteamReader goes though the text file to disply the scoreboard
			using (StreamReader sr = new StreamReader(sFILENAME))
			{
				while (sr.Peek() != -1)
				{
					Console.WriteLine(sr.ReadLine() + " sec");
				
				sr.Close();

				Console.WriteLine();
				Console.WriteLine("Press any key to close.");
				Console.ReadKey();
}

}

			}
		
	}
}


This post has been edited by Sp1nxer: 18 December 2009 - 05:51 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Hangman

#2 ragingben  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 170
  • View blog
  • Posts: 637
  • Joined: 07-October 08

Re: Hangman

Posted 18 December 2009 - 05:10 AM

Hi there, if you paste code you can paste it in "
 your code 
" blocks to make it easier to read.

So if I get it right you want to compare a users input character to see if it appears in the word? Try looking into

"mystring".Contains(); 



...to see if they get the right character
Was This Post Helpful? 0
  • +
  • -

#3 Sp1nxer  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 18-December 09

Re: Hangman

Posted 18 December 2009 - 05:46 AM

View Postragingben, on 18 Dec, 2009 - 04:10 AM, said:

Hi there, if you paste code you can paste it in "
 your code 
" blocks to make it easier to read.

So if I get it right you want to compare a users input character to see if it appears in the word? Try looking into

"mystring".Contains(); 



...to see if they get the right character


Sorry new to the site and hows its formated. yes i've been learning c# since sempember but dont quite understand how to input when the user guesses a word into the letter the users trying to guess
Was This Post Helpful? 0
  • +
  • -

#4 MentalFloss  Icon User is offline

  • "ADDICTED"[2:5]
  • member icon

Reputation: 526
  • View blog
  • Posts: 1,397
  • Joined: 02-September 09

Re: Hangman

Posted 18 December 2009 - 12:04 PM

I'm not gonna get into your overall game structure. However, here's an idea about your hangman word entries.

I'm gonna go in pieces though so I can explain what is going on.

First, the hangman word itself:
class HangmanWord
	{
		class SmartCharacter
		{
			private string value;
			public bool IsCorrect { get; private set; }

			public SmartCharacter(string value)
			{
				this.value = value;
				IsCorrect = false;
			}

			public bool IsGuessCorrect(string guess)
			{
				if (value.ToUpper() == guess.ToUpper())
					IsCorrect = true;

				return IsCorrect;
			}

			public override string ToString()
			{
				if (IsCorrect)
				{
					return value;
				}
				else
				{
					return "_";
				}
			}
		}


		private IList<SmartCharacter> answer = new List<SmartCharacter>();

		public HangmanWord(string answer)
		{
			foreach (char c in answer)
			{
				this.answer.Add(new SmartCharacter(c.ToString()));
			}
		}

		public void MakeGuess(string guess)
		{
			foreach (SmartCharacter smartChar in answer)
			{
				smartChar.IsGuessCorrect(guess);
			}
		}

		public void PrintWord()
		{
			foreach (SmartCharacter smartChar in answer)
			{
				Console.Write(smartChar.ToString());
			}
			Console.WriteLine();
		}

		public bool IsWinner()
		{
			foreach (SmartCharacter smartChar in answer)
			{
				if (smartChar.)
					return false;
			}
		}
	}



Ok, so quite a bit going on here. Let's look at that inner class first:

class SmartCharacter
	{
		private string value;
		public bool IsCorrect { get; private set; }

		public SmartCharacter(string value)
		{
			this.value = value;
			IsCorrect = false;
		}

		public bool IsGuessCorrect(string guess)
		{
			if (value.ToUpper() == guess.ToUpper())
				IsCorrect = true;

			return IsCorrect;
		}

		public override string ToString()
		{
			if (IsCorrect)
			{
				return value;
			}
			else
			{
				return "_";
			}
		}
	}



So, this manages itself. It's either guessed correct or not. If it's right, then it returns the actual value (that was given in constructor) of the character. If it's wrong, it returns a dash. With guessing, I raise both to upper case so that comparison is easier.

Now, onto that other class (I have removed the inner class for brevity).

class HangmanWord
	{
		
		private IList<SmartCharacter> answer = new List<SmartCharacter>();

		public HangmanWord(string answer)
		{
			foreach (char c in answer)
			{
				this.answer.Add(new SmartCharacter(c.ToString()));
			}
		}

		public void MakeGuess(string guess)
		{
			foreach (SmartCharacter smartChar in answer)
			{
				smartChar.IsGuessCorrect(guess);
			}
		}

		public void PrintWord()
		{
			foreach (SmartCharacter smartChar in answer)
			{
				Console.Write(smartChar.ToString());
			}
			Console.WriteLine();
		}
	}



This class essentially maintains the collection of characters in a list. When the user guesses, they make a guess against the word as a whole and the word provides each SmartCharacter in its collection with the guess. Since the word doesn't actually care about whether the guess was correct (that might be something you can implement if needed), it just forwards it off to the SmartCharacter and moves on.

When it's time to print the word, it calls each SmartCharacter in its collection's ToString method. Which as stated before either prints a dash or the value based on if it has been guessed.

So, let's look at usage:

class Program
	{
		static void Main(string[] args)
		{
			// Simulate a game:
			HangmanWord hangman = new HangmanWord("MentalFloss");

			// Random guesses:
			List<string> guesses = new List<string>() { "a", "e", "r", "g", "m", "3", "s", "j", "n", "t", "Z", "l", "f", "o" };

			// Make all those guesses. Print results.
			foreach (string g in guesses)
			{
				Console.WriteLine("Guessing {0}", g);
				hangman.MakeGuess(g);
				hangman.PrintWord();
			}

			Console.ReadLine();
		}
	}



Pretty simple here. I create a hangman word and I just make some guess list (to simulate actually playing).

Then foreach simulated guess, i call MakeGuess on the word and then I print that word.

Here's output:

Guessing a
____a______
Guessing e
_e__a______
Guessing r
_e__a______
Guessing g
_e__a______
Guessing m
Me__a______
Guessing 3
Me__a______
Guessing s
Me__a____ss
Guessing j
Me__a____ss
Guessing n
Men_a____ss
Guessing t
Menta____ss
Guessing Z
Menta____ss
Guessing l
Mental_l_ss
Guessing f
MentalFl_ss
Guessing o
MentalFloss



So, that's just how I might do it. It does look kind of over-engineered for this game, but I really like the fact that the word itself doesn't care what the answer is. Although it could:

(In HangmanWord Class)
public bool IsWinner()
		{
			foreach (SmartCharacter smartChar in answer)
			{
				// If any are false then the game isn't over.
				if (smartChar.IsCorrect == false)
					return false;
			}
			// All of them are correct at this point.
			return true;
		}



And client code:

class Program
	{
		static void Main(string[] args)
		{
			// Simulate a game:
			HangmanWord hangman = new HangmanWord("MentalFloss");

			// Random guesses:
			List<string> guesses = new List<string>() { "a", "e", "r", "g", "m", "3", "s", "j", "n", "t", "Z", "l", "f", "o" };

			// Make all those guesses. Print results.
			foreach (string g in guesses)
			{
				Console.WriteLine("Guessing {0}", g);
				hangman.MakeGuess(g);
				hangman.PrintWord();

				if (hangman.IsWinner())
				{
					Console.WriteLine("YOU WIN!!");
				}
			}

			Console.ReadLine();
		}
	}



And new output:

Guessing a
____a______
Guessing e
_e__a______
Guessing r
_e__a______
Guessing g
_e__a______
Guessing m
Me__a______
Guessing 3
Me__a______
Guessing s
Me__a____ss
Guessing j
Me__a____ss
Guessing n
Men_a____ss
Guessing t
Menta____ss
Guessing Z
Menta____ss
Guessing l
Mental_l_ss
Guessing f
MentalFl_ss
Guessing o
MentalFloss
YOU WIN!!



Hopefully this helps you out.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1