Hint system to tell a random false selection - c#

I'm making a c# windows form application in which there are five buttons each corresponding to a number 1-5 and the user guesses a random number out of those. I need to implement a hint which would tell the user a random false selection. How would I do this?
public partial class frmGuessANumber : Form
{
int number;
public frmGuessANumber()
{
InitializeComponent();
Random rnd = new Random();
number = rnd.Next(1, 6);
}
private void SelectionMade(object sender, EventArgs e)
{
Button selection = (Button)sender;
int guess = Convert.ToInt32(selection.Text);
if (guess == number)
{
DisableButtons();
lblMessage.Text = "Congratulations! " + guess + " is correct!";
lblMessage.Visible = true;
}
else
{
DisableButtons();
lblMessage.Text = "Sorry! " + guess + " isn't the right answer.";
lblMessage.Visible = true;
}
}
private void lblHint_MouseHover(object sender, EventArgs e)
{
Random rnd = new Random();
int wrongSelection = rnd.Next(2, 6);
if (number == 1)
lblHint.Text = "The number is not " + wrongSelection;
else
lblHint.Text = "The number is not " + (number - 1);
}
private void DisableButtons()
{
btnGuess1.Enabled = false;
btnGuess2.Enabled = false;
btnGuess3.Enabled = false;
btnGuess4.Enabled = false;
btnGuess5.Enabled = false;
}
}

You could
1) enumerate the possible numbers using Enumerable.Range
2) then take all except the correct solution (in your case number). You can use the Where method
3) then you would randomly pick a number from this set as a hint. You can use the ElementAt method
Random rnd = new Random();
int CorrectAnswer = rnd.Next(1, 6);
int hint = Enumerable.Range(1,6).Where(x=>x != CorrectAnswer ).ElementAt(rnd.Next(1,5));
Since the user has been deleted, I will just leave the answer for future people with a similar problem:

Related

How do I use a random number I generated in a separate sum

I'm a complete beginner and trying to create a Times Table game app that asks the user to input a number, generates a multiplication sum, and then checks if it's the write answer to deliver a congratulations message and then adds the score.
I've managed to generate the random number, but when I input the correct answer I get the Incorrect message which makes me think that the random number is not pulling through to the second button. Any help much appreciated!
Button 1
private void button1_Click(object sender, EventArgs e)
{
userInput = Convert.ToInt32(textBox1.Text);
if (userInput >= 1 && userInput <= 10)
{
Random rNum = new Random(); //uses built in function Random()
int rrNum = rNum.Next(1, 12); // creates a number between 1 and 12
label5.Text = (Convert.ToString(rrNum) + " x " + userInput);
}
}
Button 2
private void button2_Click(object sender, EventArgs e)
{
userAnswer = Convert.ToInt32(textBox2.Text);
Random rNum = new Random();
int rrNum = rNum.Next(1, 12);
if (userAnswer == userInput * rrNum)
{
label8.Text = "Congratulations!";
pictureBox1.Enabled = true;
pictureBox1.Visible = true;
}
else
{
label8.Text = ("Incorrect, try again!");
}
}

How to enable GetAsyncKeyState using char?

Good morning, I would like to "enable" the functions from GetAsyncKeyState from a button that is a char
ps. I am making a AutoClicker for game. (sorry for bad English xd)
example:
private void siticoneButton5_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 27)
{
siticoneButton5.Text = "Zbinduj";
keyRegisteringBool = false;
}
if (keyRegisteringBool)
{
siticoneButton5.Text = "Bind: " + e.KeyChar.ToString();
char bind = e.KeyChar;
keyRegisteringBool = false;
}
}
//here i have a void with a function
int min = Convert.ToInt32(materialSingleLineTextField1.Text);
int max = Convert.ToInt32(materialSingleLineTextField2.Text);
Random rand = new Random();
int cps = rand.Next(min, max);
while (true)
{
if (GetAsyncKeyState() < 0) //here I want to start this by key down a char.
{
bot.Mouse.LeftButtonClick();
Thread.Sleep(1000 / cps);
}
}
```
Thanks in advace

How to make loop wait until button is clicked

I'm working on a mathematical game that gives 10 different adding questions one by one. Those questions are displayed on the label and you can answer it by writing into a text box and clicking submit. I'm stuck with answering part, particularly with loop waiting until I press a button.
From looking it up, I found a method to make it as a new event, but I didn't get how I can make my loop wait for that event to continue
My code looks like this
int Between = 1;
Random rnd = new Random();
for (int i = 0; i < 10; i++)
{
if (Between == 1)
{
int num1 = rnd.Next(1, 11); // 1-10
int num2 = rnd.Next(1, 11); // 1-10
string number1 = num1.ToString();
string number2 = num2.ToString();
kusimus.Text = number1 + " + " + number2;
}
I need to add waiting after kusimus.Text = number1 + " + " + number2;. Reading the text box isn't yet added cause it wouldn't have use without button, so it aint included. "between" ain't completed eiter, so that's why i have if with int of it right before it
If you want to ask a total of 10 questions, one at a time, you don't need to use a loop and wait within it. You can simply use the button click event to check the answer and update the question label.
Move Between and rnd to be class members, so you can access them in multiple methods. Alongside these, create two integers to store the current correct answer, and how many questions have been asked.
For my answer, I used these names:
private int Between = 1;
private Random rnd = new Random();
private int questionsAsked = 0;
private int currentAnswer = 0;
Update the label for the first question in the form's constructor, like so.
public Form1()
{
InitializeComponent();
// Get two random numbers
int num1 = rnd.Next(1, 11); // 1-10
int num2 = rnd.Next(1, 11); // 1-10
// Save the answer.
currentAnswer = num1 + num2;
// Update the label.
kusimus.Text = String.Format("{0} + {1}", num1, num2);
// Keep track of how many questions have been asked.
questionsAsked++;
}
Then do much of the same in the click event, including answer checking.
private void button1_Click(object sender, EventArgs e)
{
// We've already asked ten questions, don't do anything else.
if (questionsAsked > 10) return;
// If the user entered a valid integer into the text box
int answer;
if (int.TryParse(txtBoxAnswer.Text, out answer))
{
// Implement Between if still needed.
if (Between == 1)
{
if (answer == currentAnswer)
{
// the answer is correct.
}
else
{
// the answer is incorrect
}
int num1 = rnd.Next(1, 11); // 1-10
int num2 = rnd.Next(1, 11); // 1-10
currentAnswer = num1 + num2;
kusimus.Text = String.Format("{0} + {1}", num1, num2);
}
// We've asked another question.
questionsAsked++;
if (questionsAsked > 10)
{
// User has answered last question, do something?
}
}
}
If you place it in the button click event it will work and fire when you click the button.
private void Button_Click(object sender, RoutedEventArgs e)
{
int between = 1;
Random rnd = new Random();
//This loop is pointless since there's only one number that can use it.
//However; I've left it as it incase you're needing it for another reason.
for (int i = 0; i < 10; i++)
{
if (between == 1)
{
int num1 = rnd.Next(1, 11); // 1-10
int num2 = rnd.Next(1, 11); // 1-10
string number1 = num1.ToString();
string number2 = num2.ToString();
kusimus.Text = number1 + " + " + number2;
}
}
}
Now, here's something to note also just FYI:
/* If the work is a loop, string manipulation, or anything that may require more than 100ms of work
* then I suggest doing it asynchronously. Hopefully this helps.
* If it's confusing or you need more comments to explain what's going on let me know.
* Don't worry about the work being done... I just tried to keep it as similar as I could to your question
* and still make it useful for the example.
* Note: This is WPF so the Textblock works like this but it should be RichTextBox for WinForms and button will just be button.Enabled = true : false */
private async void Button_Click(object sender, RoutedEventArgs e)
{
button1.IsEnabled = false;
textblock1.Text = string.Empty;
var between = 1;
Random rnd = new Random();
var randomText = await Task.Run(() =>
{
var stringBuilder = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
if (between == 1)
{
int num1 = rnd.Next(1, 11); // 1-10
int num2 = rnd.Next(1, 11); // 1-10
string number1 = num1.ToString();
string number2 = num2.ToString();
stringBuilder.AppendLine(number1 + " + " + number2);
}
}
return stringBuilder.ToString();
});
textblock1.Text = randomText;
button1.IsEnabled = true;
}

Enter button does not work at textbox

I'm a beginner in c# and first time need your help, because I can't find any solution to this problem.
I make a typewriting tutorial, I have a richtextbox filled with randomly generated characters, spaces and 3 new line.
The user must type the characters in a textbox, and if he typed the adequate character the character turn to green in richtextbox and he can type the the next one. If he makes a mistake, he cant move to next character until the the right button was pressed.
My problem is everything works, except new line part.
When the program compare the 2 new line accept the new line but just when ctrl+enter was pressed, simple enter wont work, the program somehow thinks enter is a wrong character.
I need to make this user friendly and a simple enter needed for this.
I tried this so far:
Make textbox MultiLine makes no difference.
Changed Acceptsreturn to true makes no difference.
Changed in string that will be the text of richtextbox the Environment.Newline to \r and \n and \r\n and its makes no difference.
Changed the textbox to Richtextbox makes no difference.
I tried every possible combination above and I cant work out what is the problem.
Here it is the random character generating part:
public partial class Form1 : Form
{
char[] karakterek = { 'a','á','b','c','d','e','é','f','g','h','i','í','j','k','l','m','n','o','ó','ö','ő','p','q','r','s','t','u','ú','ü','ű','v','x','y','z' };
char[] nemkarakterek = {'0','1','2','3','4','5','6','7','8','9','"',',','+','%','/','=',':','-',};
char egykarakter;
string teljes = "";
int mutato = 0;
Random r = new Random();
public Form1()
{
InitializeComponent();
karakterfeltolt();
}
private void karakterfeltolt()
{
int hanyszor = 0;
do
{
string egesz = "";
if (hanyszor < 3)
{
do
{
if (egesz.Length < 150)
{
if (r.Next(1,15)<14)
{
egykarakter = karakterek[r.Next(0, karakterek.Length)];
egesz = egesz + egykarakter;
}
else
{
egykarakter = nemkarakterek[r.Next(0, nemkarakterek.Length)];
egesz = egesz + egykarakter;
}
}
} while (egesz.Length < 150);
if (egesz.Length > 150)
{
egesz = egesz.Substring(0, 150);
}
int vanespace = 0;
egesz = egesz.Insert(r.Next(2, 10), " ");
for (int i = 0; i < egesz.Length - 10; i++)
{
if (egesz[i] == ' ')
{
vanespace = i;
int eselynovelo = r.Next(0, 10);
if (eselynovelo > 6)
{
egesz = egesz.Insert(r.Next(vanespace + 3, vanespace + 10), " ");
}
else
{
egesz = egesz.Insert(r.Next(vanespace + 6, vanespace + 10), " ");
}
}
}
string nagybetus = egesz.Substring(0, 1).ToUpper() + egesz.Substring(1);
nagybetus = nagybetus.Insert(nagybetus.Length, ".\r\n");
teljes = teljes + nagybetus;
hanyszor++;
}
} while (hanyszor < 3);
richTextBox1.Text = teljes;
}
And here is the textbox compare part:
private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == richTextBox1.Text[mutato])
{
richTextBox1.SelectionStart = 0;
richTextBox1.SelectionLength = mutato + 1;
richTextBox1.SelectionColor = Color.Green;
mutato++;
label2.Text = "OK";
}
else
{
label2.Text = "Wrong";
e.Handled = true;
}
}
What else can I do? Please help me.

Pick a random random from a list. If it's not the chosen one, pick another one.

I have this Guess the number game. The user thinks of a number and the computer will guess it. I have this code but the thing is, every attempt that computer makes there's a chance that the random number will repeat. I would like to know how to create a random list, the computer will pick a number from the list, if it's not correct I would like to have that number deleted so it will not be picked up again. I am new in this field so I would really appreciate any help.
private void btnStartTheGame_Click(object sender, EventArgs e)
{
int guessTheNumber = Convert.ToInt32(txtNumberGuess.Text);
DialogResult dialogResult;
do
{
Random newNumberGenerator = new Random();
number = newNumberGenerator.Next(0, 10);
dialogResult = MessageBox.Show("Is number" + number.ToString() + " you are thinking about?", "Answer the question!", MessageBoxButtons.YesNo);
}while (dialogResult == DialogResult.No);
MessageBox.Show("Congratulation! You guessed the number!!");
}
Here is a short but complete program which does as you require (I have used a console application rather than forms):
private static void Main(string[] args)
{
string dialogResult = "";
bool[] alreadyGuessed = new bool[10];
int guesses = 0;
Random newNumberGenerator = new Random();
do
{
int number = newNumberGenerator.Next(0, 10);
if (!alreadyGuessed[number])
{
guesses++;
alreadyGuessed[number] = true;
Console.WriteLine("Are you thinking of the number " + number.ToString() + "?")
dialogResult = Console.ReadLine();
}
}
while (dialogResult.ToUpper() != "Y" && guesses < 10);
if (dialogResult.ToUpper() == "Y")
{
Console.WriteLine("I guessed the number!");
}
else
{
Console.WriteLine("No numbers left!");
}
Console.ReadLine();
}
The logic in your original program seemed somewhat backwards; it wasn't clear whether it was the user or the computer doing the guessing. This program assumes that you are thinking of a number between 0 and 9 (inclusive) and leaving the computer to try to guess it, but you can obviously adapt it to your needs. I have also omitted any validation logic.
EDIT: As Tarec correctly points out, this doesn't extend to very large number sets. To do that you'd need a proper shuffling algorithm like this:
public static void Shuffle(int[] array)
{
var random = new Random();
for (int i = array.Length; i > 1; i--)
{
int j = random.Next(i);
int temp = array[j];
array[j] = array[i - 1];
array[i - 1] = temp;
}
}
Then you could change your program to this:
private static void Main(string[] args)
{
string dialogResult = "";
int size = 10;
int[] array = Enumerable.Range(0, size).ToArray();
Shuffle(array);
for (int i = 0; i < size; i++)
{
int number = array[i];
Console.WriteLine("Are you thinking of the number " + number.ToString() + "?");
dialogResult = Console.ReadLine();
if (dialogResult.ToUpper() == "Y")
{
break;
}
}
if (dialogResult.ToUpper() == "Y")
{
Console.WriteLine("I guessed the number!");
}
else
{
Console.WriteLine("No numbers left!");
}
Console.ReadLine();
}
Now you can change 'size' to whatever you like and the program will work correctly. This is probably overkill for the original poster's needs, though.
List<int> randomNumbers = Enumerable.Range(0,10).ToList();
DialogResult dialogResult;
Random newNumberGenerator = new Random();
do
{
int index = newNumberGenerator.Next(0, randomNumbers.Count);
dialogResult = MessageBox.Show("Is number" + randomNumbers[index] + " you are thinking about?", "Answer the question!", MessageBoxButtons.YesNo);
if(dialogResult==DialogResult.No)
{
randomNumbers.RemoveAt(index);
}
}
while (dialogResult == DialogResult.No);
I modified your code by adding an array of number to be chosen. Then I random only the index of the array. If the number if not correct, the number is removed from the array and redo again.
int guessTheNumber = Convert.ToInt32(txtNumberGuess.Text);
DialogResult dialogResult;
ArrayList numberList = new ArrayList();
for(int i=1; i<10; i++)
numberList.Add(i);
int length = index.Count;
do
{
Random newNumberGenerator = new Random();
index = newNumberGenerator.Next(length);
dialogResult = MessageBox.Show("Is number" + numberList[index].ToString() + " you are thinking about?", "Answer the question!", MessageBoxButtons.YesNo);
if( dialogResult == DialogResult.No)
{
numberList.RemoveAt(index);
length = length - 1;
if(length == 0)
{
MessageBox.Show("No number left!!");
return;
}
}
}while (dialogResult == DialogResult.No);
MessageBox.Show("Congratulation! You guessed the number!!");

Categories