samedi 30 septembre 2017

C# Randomly Choosing Word Not Working

I'm working on a hangman game, each time via debugging I find that despite guessIndex generating a number it doesn't pick a word from the words array. I've debugged and I know 100% that it creates a number, but currentWord is still null. Can anyone help fix this?

namespace Guess_The_Word
{

    public partial class Form1 : Form
    {
        private int wrongGuesses = 0;
        private int userGuesses;
        private string secretWord = String.Empty;
        private string[] words;
        private string currentWord = string.Empty;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadWords();
            setUpWords();

        }

        private void guessBtn_Click(object sender, EventArgs e)
        {

            wrongGuesses++;
            if (wrongGuesses <= 0)
            {
                MessageBox.Show("You have lost! The currect word was {0}", currentWord);
            }
        }

        private void LoadWords()
        {

            string path = (@"C:\commonwords.txt"); // Save the variable path with the path to the txt file
            string[] readText = File.ReadAllLines(path);
            words = new string[readText.Length];
        }

        private void setUpWords()
        {
            wrongGuesses = 0;
            int guessIndex = (new Random()).Next(words.Length);
            currentWord = words[guessIndex];
            userGuesses = currentWord.Length;

        }
        private void ResetGame()
        {

            //.Show("You have {0} guesses for this word, guess three in a row to win!");
        }

        private void resetGamebtn_Click(object sender, EventArgs e)
        {
            LoadWords();

        }
    }
}

I get System.NullReferenceException: 'Object reference not set to an instance of an object.'

at line 58




Aucun commentaire:

Enregistrer un commentaire