0

Okay, so I'm creating a hang-man game (Lame, I know, but I gotta' start somewhere). I have successfully pulled ~30 random words from a text file into a variable and can properly display the word in a random order onto the screen (just to test and make sure the variable is obtaining a whole word in random order).

But I need to take that string and break it into single characters in order to 'blank' out the letters to be 'guessed' by the user. I assume an array is the best way to do this - coupled with a while loop that will run while the character != null.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Hangman
{
class Program
{
    static void Main(string[] args)
    {
        String[] myWordArrays = File.ReadAllLines("WordList.txt");
        Random randomWord = new Random();
        int lineCount = File.ReadLines("WordList.txt").Count();            
        int activeWord = randomWord.Next(0, lineCount);

        /*CharEnumerator activeWordChar = activeWord; --- I have tried this, 
        but it says "Cannot implicitly convert type 'int' to 'System.CharEnumerator' 
        --- while redlining "activeWord." */

        /*CharEnumerator activeWordChar = activeWord.ToString 
        -- I have tried this but it says "Cannot convert method group 'ToString' to 
        non-delegate type 'System.CharEnumerator'. Did you intend to invoke the method?

         I also tried moving the declaration of activeWordChar below the 'writeline' 
         that displays the word properly to the console. 

         I have even tried to create a Char[] activeWordChar = activeWord.toCharArray; But this doesn't work either. 
         */            

        //I'm using this writeline "the word for this game is: " ONLY to test that the 
        //system is choosing random word **end comment

        Console.WriteLine("The Word for this game is: " + myWordArrays[activeWord]);



        //Console.WriteLine("The Characters are like this: " + activeWordChar[]); 
        //my attempt at printing something, but it doesn't work. :(
        Console.ReadLine();


    }


  }
}

I'm open to references in order to figure it out myself, but I'm kinda' stuck here.

Also, how do I close the file that I've opened so that it can be accessed later on in the program if need be? I've only learned the StreamReader("filename") way of 'variable.Close();' - but that isn't working here.

Edit

And why someone would vote this question down is beyond me. lol

5
  • var chars = "abcd".ToArray(); Commented Jul 22, 2015 at 14:49
  • But the words are chosen randomly, and the words are of varying length. I won't know what 'word' to move to an array - and I can only seem to get activeWord to function as a 'write to console' if it's in the element myWordArrays[activeWord] Commented Jul 22, 2015 at 14:53
  • myWordArrays[activeWord].ToArray() :) Commented Jul 22, 2015 at 14:54
  • For your second question on .Close() use a using statement instead. It basically keeps the file open while inside the using statement. msdn.microsoft.com/en-us/library/yh598w02.aspx Commented Jul 22, 2015 at 14:56
  • @thinklarge - thank you for that. Commented Jul 22, 2015 at 15:16

4 Answers 4

1

A couple of points here (first of all, you are off to a great start):

  1. You are needlessly re-reading your file to get the line count. You can use myWordArrays.Length to set your lineCount variable
  2. Regarding your question about closing the file, per MSDN File.ReadAllLines() closes the file after it is done reading it, so you are fine there with what you already have.

A string itself can be treated like an array in terms of accessing by index and accessing its Length property. There's also the ability to iterate over it implicitly like so:

foreach (char letter in myWordArrays[activeWord])
{
// provide a blanked-out letter for each char
}
Sign up to request clarification or add additional context in comments.

5 Comments

That's fantastic, sir. It's so weird - I know I tried myWordArrays.Length at some point and it didn't work for whatever reason. lol. So basically, I can get rid of the entire lineCount variable now. :) Question about the foreach: is the 'letter' in your (char letter...) a variable you've created? or is it an actual type of thing within c#?
letter is just a variable created within that foreach closure. It will only exist inside those braces.
Very cool. I just used this and it worked, but when it displays to the console, I get f_ (then in a new line)o_(new line)r_(newline)t_ - the word was fort. LOL. Now I need to figure out how to replace each letter with a blank. Don't tell me though. Imma try to figure that one out on my own. Thank you so much!!!!
@Newbie One hint: there are other methods besides WriteLINE() on Console to solve your (newline) issue....
Yes, so I figured it out. I was doing the WriteLine just 'cause I'm used to it, and I was concatenating each 'letter' + "", so I just removed letter and kept "". Also, I am using Console.Write() instead so that it doesn't come on a new line each time. And thank you for not giving it away. Also, I have my program now where it will actually read the length of the word and ask "Can you guess what this 'x' letter word is" and the length is properly displaying!! Awesome! lol. Such a dumb program to be proud of, but it's purty schweet to me. :) Thanks again!
1

You can access any character in the string by its index, so you can think of string as array of chars:

For example, like this snippet:

string word = "word";
char w1 = word[0];
Console.WriteLine(w1);

5 Comments

Yes, but the words are chose randomly, therefore I won't know how many elements there are to each array. Would I have to grab the arrayVariable.Length first somehow, then reference each element separately ?
@Newbie each string has its length, specified by Length property. In the snipped I've posted, word.Length will return its exect length of 4. So from this point of view it is very similar to array. And if you need "true" char[] object, you can use String.ToCharArray method.
Right, but in order to write blank spaces for each letter, I'll need to know how many elements to writeline, right? Or can I just do Console.WriteLine(myWordArray[activeWord].length)?
@Newbie well, if all you need is output string containing spaces and having exact length, you can use appropriate constructor for string taking symbol to repeat and repetition count: Console.WriteLine(new String(' ', myWordArray[activeWord].Length));.
Thank you. In fact, that's exactly what I did to display the number of letters within the word after the 'foreach' loop in order to display an underscore for each representation of the letters. Thank you!!
0

You can simplify your code a bit as follows. Previously your activeWord variable was an integer and therefore cannot be converted to a character array.

static void Main(string[] args)
{
    String[] myWordArrays = File.ReadAllLines("WordList.txt");
    Random random = new Random();           
    string activeWord = myWordArrays[random.next(myWordArrays.Length)];
    char[] chars = activeWord.ToCharArray();
}

However a string in C# can be treated as an enumerable object and therefore you should only be using a character array if you need to mutate parts of the string.

1 Comment

I already tried that, but it says it cannot implicitly convert int to string - it's saying activeWord is an int automatically (which is why I declared it as an into to start). ??
0

Thanks to Sven, I was able to figure it out and I was able to add some things onto it as well!! I'm posting this for other newbs to understand from a newb's perspective:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Hangman
{
class Program
  {
    static void Main(string[] args)
    {
        printWord();                                          


    }

    /*I created a method to perform this, so that I can have the program stay open for 
    either 1) a new game or 2) just to see if I could do it. It works!*/

    private static void printWord()
    {
        String[] myWordArrays = File.ReadAllLines("WordList.txt");
        Random randomWord = new Random();
        //int lineCount = File.ReadLines("WordList.txt").Count();

        //The line below fixed my previous issue of double-reading file            
        int activeWord = randomWord.Next(0, myWordArrays.Length);

        string userSelection = "";

        Console.WriteLine("Are you Ready to play Hangman? yes/no: ");
        userSelection = Console.ReadLine();
            if(userSelection == "yes")
            {
                /*This runs through the randomly chosen word and prints an underscore in 
                place of each letter - it does work and this is what fixed my 
                previous issue - thank you Sven*/

                foreach(char letter in myWordArrays[activeWord])
                {
            Console.Write("_ ");

                }

                //This prints to the console "Can you guess what this 'varyingLength' letter word is?" - it does work.
                Console.WriteLine("Can you guess what this "+ myWordArrays[activeWord].Length +" letter word is?");
                Console.ReadLine();
            } 
            //else if(userSelection=="no") -- will add more later

    }


  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.