Liam Vallance Liam Vallance - 1 year ago 99
C# Question

C# Hangman with Bugs

I get an index out of range when I make a empty guess, I also have problem with updating my score label. Currently it will go through the update but not perform it on the form. I’d also like to make sure the user can’t keep entering a valid letter to get more points, please help just got back to learning c# and projects like this help me learn

namespace Guess_The_Word
{
public partial class Form1 : Form
{
private int wrongGuesses = 0;
private int userGuesses;
private int score = 0;
private string secretWord = String.Empty;
private string[] words;
private string currentWord = string.Empty;
private string userGuess = string.Empty;
private string userInput = string.Empty;
private string randomInput = string.Empty;


public Form1()
{
InitializeComponent();
}

private void guessBtn_Click(object sender, EventArgs e)
{
string guess = userInputBox.Text.ToString();
char[] randomCharArray = currentWord.ToLowerInvariant().ToCharArray();
char[] userInputArray = guess.ToLowerInvariant().ToCharArray();
//Assume that userInput would never be superior than randomCharArray
//And contain only one char
for (int i = 0; i < randomCharArray.Length; i++)
{
if (userInputArray[0].Equals(randomCharArray[i])) // Here is where the error happens
{
UpdateScore();
}
}
// Clean userInput in form
userInputBox.Text = string.Empty;

}


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

private void SetUpWords()
{
string path = (@"C:\commonwords.txt"); // Save the variable path with the path to the txt file
words = File.ReadAllLines(path);
int guessIndex = (new Random()).Next(words.Length);
currentWord = words[guessIndex];
wordlbl.Text = string.Empty;
for (int i = 0; i < currentWord.Length; i++)
{

wordlbl.Text += "*";

}
}

private void UpdateScore()
{
scorelbl.Text = Convert.ToString(score);
}

}
}

Answer Source

Make sure you check the length of the array before attempting to access specific indices whether known or not. The example below is kind of overkill on the logic, but it demonstrates the previous statement thoroughly.

if (userInputArray.Length > 0 && userInputArray.Length > i)
    if (randomCharArray.Length > 0 && randomCharArray.Length > i)
        if (userInputArray[0].Equals(randomCharArray[i]))
            UpdateScore();

private void UpdateScore() {
    score++;
    scorelbl.Text = Convert.ToString(score);
}

I went over to .NET Fiddle and did a basic run through without all of the extra complexity of using arrays and I'm returning some pretty good results. The logic in the example below is pretty basic and will currently only handle the current word having only one of each letter. You'll have to expand on it from here to allow handling of multiple letters in words such as "banana" or "apple". Hopefully this will get you headed in the right direction with your project, and I hope my answer above taught you what you needed to know about checking the length of arrays before attempting to access their indices.

using System;
using System.Collections.Generic;

public class Program
{
    private static int score = 0;
    private static string currentWord = string.Empty;
    private static char userGuess = '`';
    private static List<char> correctLetters = new List<char>();

    public static void Main()
    {
        currentWord = "are";

        do {
            Console.WriteLine("Enter a letter: ");
            userGuess = Console.ReadLine()[0];
        } while (TestInput());

        Console.WriteLine("The word was: " + currentWord);
        Console.ReadLine();
    }

    private static bool TestInput() {
        if (currentWord.ToLowerInvariant().Contains(userGuess.ToString().ToLowerInvariant())) {
            correctLetters.Add(userGuess);
            score++;
            Console.WriteLine("Current Score: " + score);
        }

        if (correctLetters.Count == currentWord.Length)
            return false;

        return true;
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download