using methods for program?

2020-05-23 c# c#-2.0

So I did this hangman game, and it works perfectly fine, the only problem is that I want to use methods to organize everything.

And yes, it is a school project. I tried my best but whenever I try to put a part of the program in a method it's as if I removed a variable and it underlines it in red.

I removed them for now so it's more clear. also, the file I used contained 19 8 letters max words, one on each line.

Can someone tell me how I can incorporate methods without ruining the whole thing? also English isn't my first language plz excuse any mistakes, the code was in french and I translated it for this question. thank you very much. I appreciate your time and effort :)

using System;
using System.IO;

namespace TP3
{
    class Program
    {
        public const String Dico = "dico.txt";

        public static void Welcome()
        {
            //Mot de bienvenue
            Console.WriteLine("Welcome to hangman !");
        }

        public static void Goodbye()
        {
            Console.WriteLine("thx for playing, goodbye!");
        }

        public static void Program()
        {
            int SolvedWords= 0;
            string WordToGuess= "";
            int NumberOfLetters ;
            int x = 0;
            int WordTried = 0;

            Console.WriteLine("");
            Console.WriteLine("Do you wanna guess a word ? oui or non.");
            Console.WriteLine("you have 8  chances per word.");
            string Answer= Console.ReadLine();
            Answer= Answer.ToLower();

            while (Answer== "oui" && WordTried <19) 
            {
                const int Lives= 8;
                int LostLives= 0;
                int LivesLeft= 8;
                int LettersGuesed= 0;
                x += 1;
                WordTried += 1;

                if (WordTried <= 20 && WordTried >1) 
                {
                    Console.WriteLine("Do you wanna guess a word ? oui or non.");
                    Answer= Console.ReadLine();
                    Answer= Answer.ToLower();
                }

                //Read a word in the file
                int compteur = 0;
                string ligne;
                // Read file and show on the line
                System.IO.StreamReader file = new System.IO.StreamReader(@"dico.txt");
                while ((line = file.ReadLine()) != null)
                {
                    compteur++;
                    if (compteur == x)
                    {
                        WordToGuess= line;
                    }
                }
                file.Close();

                char[] table;
                table = new char[WordToGuess.Length];
                for (int i = 0; i < table.Length; i++)
                {
                    table[i] = WordToGuess [i];
                }

                //change each letter into a *
                Console.WriteLine("here’s the word to guess : ");
                string HiddenWord = "********";
                char[] table2;
                table2 = new char[WordToGuess.Length];
                for (int i = 0; i < table2.Length; i++)
                {
                    table2[i] = HiddenWord[i];
                }
                for (int i = 0; i < table2.Length; i++)
                {
                    Console.Write(table2[i]);
                }
                Console.WriteLine("");

                //guess the word
                while (LettersGuesed< WordToGuess.Length && LivesLeft> 0)
                {
                    Console.WriteLine("");
                   /* Console.WriteLine("Devinez une seule Letterdu mot. Ne pas écrire une Letter plus d'une fois de suite. Si c'est le cas, recommencez le jeu.");*/
                    string Letter= Console.ReadLine();
                    Letter= Letter.ToLower();
                    NumberOfLetters  = Letter.Length;
                    char[] table3;
                    table3= new char[NumberOfLetters ];

                    for (int i = 0; i < table2.Length; i++)
                    {
                        if (table[i].Equals(Letter[0]))
                        {
                            Table2[i] = Letter[0];
                            LettersGuesed+= 1;
                        }
                    }

                    for (int i = 0; i < table2.Length; i++)
                    {
                        Console.Write(table2[i]);
                    }

                    if (WordToGuess.IndexOf(Lettre) < 0)
                    {
                        Console.WriteLine("");
                        Console.WriteLine("wrong letter.");
                        LostLives+= 1;
                        LivesLeft= Lives- LostLives;
                        Console.WriteLine("you have " + LivesLeft+ " lives left.");
                    }

                    if (WordToGuess.IndexOf(Lettre) >= 0)
                    {
                        Console.WriteLine(" ");
                        Console.WriteLine("right !");
                        Console.WriteLine("you have " + LivesLeft+ " lives left.");
                    }

                    if (LettersGuesed== WordToGuess.Length && LivesLeft> 0)
                    {
                        SolvedWords+= 1;
                        Console.WriteLine(" ");
                        Console.WriteLine("you found the word !");
                        Console.WriteLine("you found " + SolvedWords+ " on" + WordTried + " words so far.");
                    }

                    if (LivesLeft== 0)
                    {
                        Console.WriteLine("you couldnt guess the word.");
                        Console.WriteLine("the word was :");
                        for (int i = 0; i < table.Length; i++)
                        {
                            Console.Write(table[i]);
                        }
                        Console.WriteLine(" ");
                        Console.WriteLine("you found " + SolvedWords+ " on" + WordTried + " words so far.");
                    }

                    if (WordTried == 19)
                    {
                        Console.WriteLine("no more words to guess.");
                    }
                }
            }
        }

        static void Main(string[] args)
        {
            Welcome();

            Programme();

            Goodbye();
        }
    }
}

Answers

Im not going to make every method for your project, I'll help kickstart on how to think about it. Look at your current code for reading the file of words. You can move that into a method -

public string[] ReadWordsFromFile()
{
    string file = "path to your file here";
    return File.ReadAllLines(file);
}

Or pass the file path as parameter -

public string[] ReadWordsFromFile(string filePath)
{
    return File.ReadAllLines(filePath);
}

Next you can have a method to get random words -

public string GetRandomWord(string[] wordsArray)
{
    Random random = new Random();
    int randomIndex = random.Next(0, wordsArray.Length);
    return wordsArray[randomIndex];
}

Note - words can be repeated if you do it this way, if you don't want that - then add logic to remove that item from the list once its used in the game. If you remove it within this method, its not actually going to remove it from the game, as you'll still be passing the entire array when getting a new word. Ill leave the implementation of that logic to you, if you want it.

In the "game controller" code - you can use the above methods like this -

string file = "your path to txt file";
string[] allWords = ReadWordsFromFile(file);
string WordToGuess = GetRandomWord(allWords);

May be your next goal should be something like this -

public void GameControler()
{
    // get all words here and other logic before game starts
    while (Attempts > 0)
    {
        string WordToGuess = GetRandomWord(wordsArray);
        // get letterGuessed from user
        bool letterExists = CheckIfLetterExists(WordToGuess, letterGuessed);
        if (!letterExists)
            {
                Attempts--;
                ExecuteWrongGuessMethod(x, y);
            }
        else
            {
                ExecuteRightGuessMethod(w);
            }
    }
}

public bool CheckIfLetterExists(string word, string letter)
{
    if (word.Contains(letter)) return true;
    else return false;
}

public void ExecuteWrongGuessMethod(string passWhatYouNeedTo, int somethingElse)
{
     // what to do when the guess is wrong e.g. Console.Writeline("wrong guess");
}

public void ExecuteRightGuessMethod(string word)
{
     // logic when guess is right. e.g. Show the letter guessed within the word on the console etc.
}

All of this isn't the best way to do it. BUT I personally feel this is logically next step a beginner takes after what you've implemented. Seeing a fully well-developed program might be too much without understanding atleast some basic concepts of OOP.

After learning how to create Methods and use them, then comes classes and objects. Which should be implemented in this game, but this is all for now. I recommend you do a short C# course on coursera etc or even youtube. And slowly move towards a better understanding of SOLID principles. And by SOLID I mean an acronym for the 5 principles and not the actual word. All the best.

Related