Creating a Counter for user input C# - c#

Hey guys I need some help creating a counter for user input based on how much time they enter a guess to guess a random number from 1 - 100. So far this is what I have but it only output 1 count and does not count the next input. Can you please tell me what I am doing wrong?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GuessingGameGUI
{
public partial class frmGuess : Form
{
public frmGuess()
{
InitializeComponent();
}
private void frmGuess_Load(object sender, EventArgs e)
{
lblCount.Visible = true;
lblHowMuch.Visible = true;
}
private void btnReset_Click(object sender, EventArgs e)
{
txtGuess.Text = "";
lblCount.Text = "";
lblHowMuch.Text = "";
this.BackColor = System.Drawing.Color.Empty;
txtGuess.Focus();
}
private void btnCheck_Click(object sender, EventArgs e)
{
Random r = new Random();
int target = r.Next(0, 101);
int userGuess = int.Parse(txtGuess.Text);
int guessCount = 0;
if (userGuess == target)
{
guessCount++;
this.BackColor = System.Drawing.Color.DarkOliveGreen;
lblHowMuch.Text = "You guess the right number " + "it took you: " + guessCount.ToString() + " guesses";
}
else if (userGuess < target)
{
guessCount++;
this.BackColor = System.Drawing.Color.Yellow;
}
else if (userGuess > target)
{
guessCount++;
this.BackColor = System.Drawing.Color.Red;
}
lblCount.Text = "You made: " + guessCount.ToString() + " Guesses";
}
}
}

The issue with your code is that you are setting the guess counter to zero every time btnCheck is clicked. You need to make sure it is reset only once per guess session.
So this means that you need to move guessCount out as a class-level variable and make sure that you only reset it at the first run of the form and whenever btnReset is clicked.
Here's how I would refactor your code to achieve this:
public partial class frmGuess : Form
{
public frmGuess()
{
InitializeComponent();
}
private void frmGuess_Load(object sender, EventArgs e)
{
lblCount.Visible = true;
lblHowMuch.Visible = true;
ResetData();
}
private void btnReset_Click(object sender, EventArgs e)
{
ResetData();
}
private Random r = new Random();
private int guessCount;
private int target;
private void ResetData()
{
guessCount = 0;
target = r.Next(0, 101);
txtGuess.Text = "";
lblCount.Text = "";
lblHowMuch.Text = "";
this.BackColor = System.Drawing.Color.Empty;
txtGuess.Focus();
}
private void btnCheck_Click(object sender, EventArgs e)
{
int userGuess = int.Parse(txtGuess.Text);
guessCount++;
if (userGuess == target)
{
this.BackColor = System.Drawing.Color.DarkOliveGreen;
lblHowMuch.Text = String.Format(
"You guessed the right number it took you {0} guesses",
guessCount);
}
else
{
this.BackColor = userGuess < target
? System.Drawing.Color.Yellow
: System.Drawing.Color.Red;
}
lblCount.Text = String.Format(
"You made {0} Guesses",
guessCount);
}
}
You'll also notice that you were resetting the target each time btnCheck was clicked. That too needed to be moved to a class-level variable.
It's also a good habit to get in to making instances of Random a class-level variable too as there are circumstances where you can end up with less-than random numbers if you don't.
You'll notice that I moved all of the reset code into a new ResetData method that can get called both when the form loads and when btnReset is clicked.

It can't be so obvious. Why are you setting int guessCount = 0 in btnCheck_Click? Why don't you keep a global counter?

To make it global, take out int guessCount = 0; from the btnCheck_Click function and put it at the top where it appears like:
namespace GuessingGameGUI
{
public partial class frmGuess : Form
{
int guessCount = 0;
That way guessCount won't be continually reset to zero and then incremented each time you press the btnCheck button.

Related

How to change label text and color when a condition is met? (C#)

I am making a password generator and on websites when you enter certain conditions are met the strength of the password changes how can I change the color and text of the label when the password strength is >= 8, <8<10, >12?
Here is the Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Password_Generator
{
public partial class PassGen : Form
{
int currentPasswordLength = 0;
Random Character = new Random();
private void PasswordGenerator(int PasswordLength)
{
String validChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$&?";
String randomPassword = "";
//25
for(int i = 0; i < PasswordLength; i++)
{
int randomNum = Character.Next(0, validChars.Length);
randomPassword += validChars[randomNum];
}
Password.Text = randomPassword;
}
public PassGen()
{
InitializeComponent();
PasswordLengthSlider.Minimum = 5;
PasswordLengthSlider.Maximum = 22;
PasswordGenerator(5);
}
private void Label1_Click(object sender, EventArgs e)
{
}
private void Copy_Click(object sender, EventArgs e)
{
Clipboard.SetText(Password.Text);
}
//52
private void PasswordLength_Click(object sender, EventArgs e)
{
}
private void PasswordLengthSlider_Scroll(object sender, EventArgs e)
{
PasswordLength.Text = "Password Length:" + " " + PasswordLengthSlider.Value.ToString();
currentPasswordLength = PasswordLengthSlider.Value;
PasswordGenerator(currentPasswordLength);
}
private void pswdStrengthTest()
{
if (currentPasswordLength <= 8)
{
pswdStrength.Text = "weak";
pswdStrength.ForeColor = Color.Red;
} else if (currentPasswordLength<= 9)
{
pswdStrength.Text = "ok";
pswdStrength.ForeColor = Color.Blue;
}
}
//78
private void pswdStrength_Click(object sender, EventArgs e)
{
}
}
}
If anyone could help me with this it would be greatly appreciated. This is based off a tutorial I found on YouTube. I'm not sure what the video is called but if it helps I could search for it and update my posting.
Try this:
Password.TextChanged += (s1, e1) =>
{
if (Password.Text.Length > 10)
pswdStrength.ForeColor = Color.Green
else if (Password.Text.Length > 8)
pswdStrength.ForeColor = Color.Blue
else
pswdStrength.ForeColor = Color.Red
};
Your code looks like a windows form application.
If you have for example one objetc txt_password, check to code some of these events:
TextChanged: this occurs when your textbox has been changed
Others events could be:
KeyPress or KeyDown

Array/String of dynamically created textBoxes in Visual Studio - C#

I created, dynamically, a number of textBoxes. The user will write input in those textBoxes and then press a button ("SAVE").
I want to save the info from those textBoxes in an array(or string). Is it possible to implement something like this: for(i = 0; i < the_number_of_textBoxes; i++) MY_ARRAY_or_MY_STRING += textBox[i].Text; //I know this isn't correct
I'm sure there should be something similar to my "way of thinking", but I can't find it.
If I would always have the same number of texboxes, lets say 2, I could implement it like this: MY_ARRAY_or_MY_STRING = textBox1.Text + textBox2.Text;, but my textBoxes are dynamicaly generated.
Here is the code I use (although I don't think it will be of need), my program has 2 Forms (Form1 is noted as frm1) - It has nothing to do with my question, but maybe it helps, idk. If you need more info about what the program does, ask away, I wont write it here, because it may be useless info.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//Add MySql Library
using MySql.Data.MySqlClient;
namespace Proiect
{
public partial class Form2 : Form
{
public Form1 frm1;
public int numar_textBox = 5;
public int numar_eticheta = 5;
public int numar_groupBox = 0;
public int LastTextBoxLeft = 15;
public int LastEtichetaLeft = 15;
public int LastGroupBoxLeft = 3;
public Form2()
{
InitializeComponent();
frm1 = new Form1();
}
private void Form2_Load(object sender, EventArgs e)
{
int i;
for (i = 0; i < frm1.get_nr_coloane(); i++)
AddNewGroupBox();
}
private void Form2_Click(object sender, EventArgs e)
{
Deselect.Focus(); //Deseleceaza orice element, mutand focusul pe un label fara text
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
/*
public int verifica_spatii(TextBox New_text_box)
{
int i, k=0;
if (New_text_box.Text == "") return 1;
else
{
for (i = 0; i < New_text_box.TextLength; i++)
if (New_text_box.Text[i] != ' ')
{
return 1;
}
return 0; // are numai spatii
}
}
*/
public void On_click()
{
}
public event EventHandler Click_event;
public System.Windows.Forms.GroupBox AddNewGroupBox()
{
EventHandler handler = Click_event;
System.Windows.Forms.GroupBox grp = new System.Windows.Forms.GroupBox();
this.Controls.Add(grp);
grp.Width = 133;
grp.Height = 50;
grp.Top = 10;
grp.Left = LastGroupBoxLeft;
LastGroupBoxLeft += grp.Width;
grp.Text = frm1.get_nume_coloane()[numar_groupBox];
numar_groupBox += 1;
TextBox txt = new TextBox();
txt.Top = 20;
txt.Left = 10;
numar_textBox = numar_textBox + 1;
grp.Controls.Add(txt);
txt.Leave += textBoxGeneral_LostFocus;
/////New_text_box.Click += handler(this,);
return grp;
}
private void textBoxGeneral_LostFocus(object sender, EventArgs e)
{
//ToolStripItem item = (ToolStripItem)sender;
// MessageBox.Show(item.Text);
}
private void button1_Click(object sender, EventArgs e)
{
string valorile_de_adaugat="";
int i;
for(i=0;i<numar_groupBox-1;i++)
valorile_de_adaugat+=textBox[i]
//MySqlCommand Salveaza_in_baza_de_date = new MySqlCommand("INSERT INTO " + frm1.get_nume_tabel_selectat() + " ("+ frm1.get_unirea_coloanelor + ") VALUES(22056, 15, 2000, 2004));
}
/*
Textbox myTxtbx = new Textbox();
myTxtbx.Text = "Enter text here...";
myTxtbx.GotFocus += GotFocus.EventHandle(RemoveText);
myTxtbx.LostFocus += LostFocus.EventHandle(AddText);
public RemoveText(object sender, EventArgs e)
{
myTxtbx.Text = "";
}
public AddText(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(myTxtbx.Text))
myTxtbx.Text = "Enter text here...";
}
*/
}
}
Thank you for your time,
Vlad

Why is this code not displaying output on the textbox?

I am beginning with C#. When I run the following code and click the generate button the output does not appear in the textbox. Why is this? I am calling the function palendrome and its not updating the textbox. What am I doing wrong? Am I missing something? What do I need to fix. I don't see the error. Please help. :(
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PalendromeChecker
{
public partial class Form1 : Form
{
int num;
int count;
static int result;
int setPalendromeValue;
int copyCount;
public Form1()
{
InitializeComponent();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
count = Int32.Parse(textBox2.Text);
copyCount = count;
if (!int.TryParse(textBox2.Text, out count))
{
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
else if (count < 0 || count > 100)
{
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
}
public static int palendrome(int num)
{
int temp = num; ;
int r;
int rv = 0;
while (num > 0)
{
r = num % 10;
rv = rv * 10 + r;
num /= 10;
}
if (rv == temp)
{
result = temp;
return temp;
}
else
{
return 0;
}
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
while (copyCount != 0)
{
string resultInString = result.ToString();
textBox3.Text = resultInString;
textBox3.Visible = true;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
num = Int32.Parse(textBox1.Text);
//MessageBox.Show(this.textBox1.Text);
if (!int.TryParse(textBox1.Text, out num))
{
//MessageBox.Show("This is a number only field");
//return;
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
else if (num < 0 || num > 1000000000)
{
// MessageBox.Show("Invalid Input needs to be between 0 and 1,000,000,000");
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
}
private void label2_Click(object sender, EventArgs e)
{
}
private void label4_Click(object sender, EventArgs e)
{
label4.Visible = false;
}
private void button1_Click(object sender, EventArgs e)
{
int palendromeValue;
while (count != 0)
{
palendromeValue = palendrome(num);
count--;
}
}
}
}
It is not generating any input on the textbox because your function palendrome is not generating in anyway output on any of textbox1 to textbox3.
Try this:
textBox1.Text = "output"; //Whatever output you want.
If you want to show result in textBox3 the code to update it's text property should be inside button click handler, not in text changed handler.
Also while (count != 0) or while (copyCount != 0) are like infinite loops (almost). They are going to make your form unresponsive. You need to avoid those.

How to save name that is entered in text box and the time that is on the timer when the game is completed

At the minute i have a match picture game in c# windows forms with a timer that stops when all matches are complete. I am wondering how do i save the time taken and the name that is entered using btn_player in a text file. The text file is stored at (#"E:\Match Picture\Public\Files\playerdetails.txt");
using System.Windows.Forms;
using System.Threading;
using System.IO;
namespace Match_Picture
{
public partial class Form1 : Form
{
string Temp_Tag = "";
int Number_of_Images = 0;
Label Clicked_Picture = new Label();
Label Temp_Pic = new Label();
int Num_Correct = 0;
public Form1()
{
InitializeComponent();
}
private void Picture_Click(object sender, EventArgs e)
{
Clicked_Picture = (Label)sender;
Number_of_Images++;
if (Number_of_Images < 3)
{
Clicked_Picture.Text = Clicked_Picture.Tag.ToString();
if (Number_of_Images == 1)
{
Temp_Tag = Clicked_Picture.Tag.ToString();
Temp_Pic = Clicked_Picture;
}
else
{
if (Temp_Tag != Clicked_Picture.Tag.ToString())
{
tmr_Delay.Enabled = true;
scorecounter.Text = Convert.ToString(Convert.ToInt32(scorecounter.Text) - 20);
}
else
{
Num_Correct++;
scorecounter.Text = Convert.ToString(Convert.ToInt32(scorecounter.Text) + 50);
lbl_Matches.Text = Num_Correct.ToString();
if (Num_Correct == 8)
{
tmr_1.Stop();
MessageBox.Show("Congratulations, all matches complete");
MessageBox.Show("Number of seconds to match all the pictures: " + i);
this.Close();
}
}
Number_of_Images = 0;
}
}
}
private void tmr_Delay_Tick(object sender, EventArgs e)
{
Clicked_Picture.Text = "R";
Temp_Pic.Text = "R";
tmr_Delay.Enabled = false;
}
int i = 0;
private void timer1_Tick(object sender, EventArgs e)
{
i++;
lbl_time.Text = i.ToString() ;
}
private void btn_player_Click(object sender, EventArgs e)
{
}
You can use the StreamWriter class in order to do what you need.
using (StreamWriter writer = new StreamWriter(#"E:\Match Picture\Public\Files\playerdetails.txt"))
{
writer.WriteLine("") // This is where you will write what you want to that file
}
As MethodMan, you can use EndTime - StartTime, and any other conversions necessary in order to get it in the format you want (minutes, seconds, etc).
This code will simply write to the text file. It will create it if it does not exists, and it will overwrite the file if it does exist. You need to do the proper checks to make sure that you don't overwrite it, or you can use
new StreamWriter(#"E:\Match Picture\Public\Files\playerdetails.txt", true)
if you want to append the file instead of overwriting. Full documentation of the StreamWriter class can be found here http://msdn.microsoft.com/en-us/library/system.io.streamwriter%28v=vs.110%29.aspx
As an aside, if you're trying to keep records of high score, you should also look into the StreamReader class. You can read in the file into a dictionary of Player and Time, and check to see if a player already exists in the file and only adjust their score if it beats their best score.

How do u add a 3 second delay in C# (visual studio 2010)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
int randumnum1;
public Form1()
{
InitializeComponent();
}
public int randumnum()
{
Random r = new Random();
int randumnum = r.Next(15, 30);
return randumnum;
}
private void button2_Click(object sender, EventArgs e)
{
randumnum1 = randumnum();
string strrandumnum = randumnum1.ToString();
label4.Text = strrandumnum;
button2.Text = "New Game";
}
private void button1_Click(object sender, EventArgs e)
{
Random r = new Random();
int computer = r.Next(1, 4);
String strrandumnum;
if (((Convert.ToInt32(textBox1.Text)) < 1) || ((Convert.ToInt32(textBox1.Text)) > 3))
{
MessageBox.Show("Invalid input. Remember you can enter numbers between 1 and 3 only", "Error");
textBox1.Text = "";
}
else if (Convert.ToInt32(textBox1.Text) == 1)
{ randumnum1 -= 1;
strrandumnum = randumnum1.ToString();
label4.Text = strrandumnum;
textBox1.Text = "";
}
else if (Convert.ToInt32(textBox1.Text) == 2)
{
randumnum1 -= 2;
strrandumnum = randumnum1.ToString();
label4.Text = strrandumnum;
textBox1.Text = "";
}
else if (Convert.ToInt32(textBox1.Text) == 3)
{
randumnum1 -= 3;
strrandumnum = randumnum1.ToString();
label4.Text = strrandumnum;
textBox1.Text = "";
}
//I want a 3 second delay right here but nothing seems to work. I tried the
//thread sleep but it skipped all the other if statements and was messed up.
randumnum1 -= computer;
strrandumnum = randumnum1.ToString();
label4.Text = strrandumnum;
}
You say in your comment that you tried Thread.Sleep, and you're right: that will pause the currently executing thread for 3 seconds, which means your UI will stop responding for those 3 seconds.
What you might try instead is using a System.Windows.Forms.Timer, which can be started in your code where you want the delay to happen. It will then fire an event when your delay is complete, and your post-delay code should go in the event handler. This way, your delay can happen without affecting the UI.
I guess one way would be Thread.Sleep(3000);. There are a number of ways to do what you want, but based on the code you've provided, that should suffice. Place it where you want the delay.

Categories