C#C
C#12mo ago
Blippet

✅ Need help with a function

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

string[] word = File.ReadAllLines("words.txt");
Random rnd = new Random();
int random = rnd.Next(1, 4);
char[] letters = word[random].ToCharArray();

int maxLives = 7;
int currentLives = maxLives;

bool win = false;

List<char> guessedLetters = new List<char>();

while (currentLives > 0 && !win)
{

foreach (var c in letters)
{
if (guessedLetters.Contains(c))
Console.Write(c);
else
Console.Write("_");
}
//the prompt which asks you to guess and shows current lives
Console.WriteLine("\nGuess a letter:");
Console.WriteLine(currentLives + "/" + maxLives + " lives left.");

//takes the input from the console and uses the ToChar to convert it to a single character
static char PlayerInput()
{
char guess = Convert.ToChar(Console.ReadLine());
return guess;
}


if (letters.Contains(PlayerInput()) && !guessedLetters.Contains(PlayerInput()))
Console.WriteLine("Correct guess!");
else
{
Console.WriteLine("Incorrect guess!");
currentLives--;
}
guessedLetters.Add(PlayerInput());

bool wordComplete = true;

foreach (var c in letters)
if(!guessedLetters.Contains(c))
wordComplete = false;

win = wordComplete;
}

if(win)
Console.WriteLine("You win!");
else
{
Console.WriteLine("You lost!");
}
Was this page helpful?