I'm using c# windows form in Visual studio 2017 version
I've made a high low game for practice and it works perfect but what I'm trying to accomplish is once someone hits 10 guesses it starts the application over again.
This was my last resort coming here and asking but i have no one else to turn to. I've tried all kinds of things to make it work when hitting 10 guesses to restart the app but nothing works and i get errors.
here's the start button and the guess button
variables I'm using
static int intRandomNumber;
static int intNumGuesses;
static int intBestLowScore;
static int intGuessedNum;
static int difference = 0;
Start Button
{
//Random Numbers//
Random rnRandomNumber = new Random();
intRandomNumber = rnRandomNumber.Next(0, 1000);
lblRandomNumber.Text = intRandomNumber.ToString();
txtGuess.Enabled = true;
btnGuess.Enabled = true;
btnStart.Enabled = false;
lblAnswer.Text = "".ToString();
intBestLowScore = intNumGuesses;
intNumGuesses = 0;
lblNumGuesses.Text = "0";
lblBestScore.Text = intBestLowScore.ToString();
lblAnswer.BackColor = Color.White;
txtGuess.Focus();
SoundPlayer audio = new SoundPlayer(High_Low_Game.Properties.Resources.Cheering);
audio.Stop();
}
Guess Button
{
intNumGuesses++;
lblNumGuesses.Text = intNumGuesses.ToString();
try
{
intGuessedNum = Convert.ToInt32(txtGuess.Text);
if (intRandomNumber - intGuessedNum < difference)
{
lblAnswer.Text = "To High";
lblAnswer.ForeColor = Color.Red;
lblAnswer.BackColor = Color.White;
txtGuess.Text = "";
txtGuess.Focus();
}
else if (intRandomNumber - intGuessedNum > difference)
{
lblAnswer.Text = "To Low";
lblAnswer.ForeColor = Color.Blue;
lblAnswer.BackColor = Color.White;
txtGuess.Text = "";
txtGuess.Focus();
}
else
{
lblAnswer.Text = "You Guessed it.";
lblAnswer.ForeColor = Color.Black;
lblAnswer.BackColor = Color.Green;
btnGuess.Enabled = false;
txtGuess.Enabled = false;
txtGuess.Text = "";
btnStart.Enabled = true;
SoundPlayer audio = new SoundPlayer(High_Low_Game.Properties.Resources.Cheering);
audio.Play();
}
}
catch
{
MessageBox.Show("Input your Guess again and Integers Only. Retry.");
txtGuess.Focus();
}
}
You're missing an if statement
Guess Button:
private void btnGuess_Click(object sender, EventArgs e)
{
intNumGuesses++;
lblNumGuesses.Text = intNumGuesses.ToString();
//This is what you're looking for-v
if(intNumGuesses==10)
{
btnGuess.Enabled = false;
txtGuess.Enabled = false;
txtGuess.Text = "";
btnStart.Enabled = true;
intNumGuesses=0;
}
//This is what you're looking for-^
try
{
intGuessedNum = Convert.ToInt32(txtGuess.Text);
if (intRandomNumber - intGuessedNum < difference)
{
lblAnswer.Text = "To High";
lblAnswer.ForeColor = Color.Red;
lblAnswer.BackColor = Color.White;
txtGuess.Text = "";
txtGuess.Focus();
}
else if (intRandomNumber - intGuessedNum > difference)
{
lblAnswer.Text = "To Low";
lblAnswer.ForeColor = Color.Blue;
lblAnswer.BackColor = Color.White;
txtGuess.Text = "";
txtGuess.Focus();
}
else
{
lblAnswer.Text = "You Guessed it.";
lblAnswer.ForeColor = Color.Black;
lblAnswer.BackColor = Color.Green;
btnGuess.Enabled = false;
txtGuess.Enabled = false;
txtGuess.Text = "";
btnStart.Enabled = true;
}
}
catch
{
MessageBox.Show("Input your Guess again and Integers Only. Retry.");
txtGuess.Focus();
}
}
In your 'guess-button' handler do the following:
{
intNumGuesses++;
lblNumGuesses.Text = intNumGuesses.ToString();
bool guessed = false;
try
{
intGuessedNum = Convert.ToInt32(txtGuess.Text);
if (intRandomNumber - intGuessedNum < difference)
{
...
}
else if (intRandomNumber - intGuessedNum > difference)
{
...
}
else
{
...
guessed = true;
}
if ((intNumGuesses == 10}&&(!guessed))
{
// Show Message "max. nr. of guesses reached'
// call method to clear values from textBoxes & enable Start-button
}
catch
{
MessageBox.Show("Input your Guess again and Integers Only. Retry.");
txtGuess.Focus();
}
}
What about this?
{
intNumGuesses++;
if(intNumGuesses >= 10)
{
StartButton(); // pseudo call, replace with whatever the name and parameters of your method really are
return;
}
lblNumGuesses.Text = intNumGuesses.ToString();
// ...
}
I would recommend to write an Init()method, that you call either from your StartButton() method or from your GuessButton() method when necessary
Related
I'm trying to code a Simon Says game and I ran into a problem. I cannot figure out how to make my Randomizer timer (that randomizes which boxes are lit up) to run by waves. I want it to run once, then when it's referred to again - run twice and so on.
This is RandomPlace():
private PictureBox RandomPlace()
{
PictureBox p = new PictureBox();
Random rnd = new Random();
switch (rnd.Next(1, 5))
{
case 1:
p = TopRight;
break;
case 2:
p = TopLeft;
break;
case 3:
p = BottomRight;
break;
case 4:
p = BottomLeft;
break;
}
return p;
} //Gets a random PictureBox
This is RandomImage():
private void RandomImage()
{
TopLeft.Enabled = false;
TopRight.Enabled = false;
BottomLeft.Enabled = false;
BottomRight.Enabled = false;
PictureBox a = RandomPlace();
if (a == TopLeft)
{
TopLeft.Image = Resources.TopLeftLit;
label1.Text = "TopLeft";
Thread.Sleep(500);
TopLeft.Image = Resources.TopLeft;
label2.Text = "TopLeftAFTERSLEEP";
Thread.Sleep(500);
pattern[patternRightNow] = 1;
patternRightNow++;
}
if (a == TopRight)
{
TopRight.Image = Resources.TopRightLit;
label1.Text = "TopRight";
Thread.Sleep(500);
TopRight.Image = Resources.TopRight;
label2.Text = "TopRightAFTERSLEEP"; //FIGURE OUT HOW TO RESET PICTURE
Thread.Sleep(500);
pattern[patternRightNow] = 2;
patternRightNow++;
}
if (a == BottomLeft)
{
this.BottomLeft.Image = Resources.BottomLeftLit;
label1.Text = "BottomLeft";
Thread.Sleep(500);
this.BottomLeft.Image = Resources.BottomLeft;
label2.Text = "BottomLeftAFTERSLEEP";
Thread.Sleep(500);
pattern[patternRightNow] = 3;
patternRightNow++;
}
if (a == BottomRight)
{
this.BottomRight.Image = Resources.BottomRightLit;
label1.Text = "BottomRight";
Thread.Sleep(500);
this.BottomRight.Image = Resources.BottomRight;
label2.Text = "BottomRightAFTERSLEEP";
Thread.Sleep(500);
pattern[patternRightNow] = 4;
patternRightNow++;
}
} //Lits up the random PictureBoxes and sets them back to normal
This is Randomizer_Tick():
rivate void Randomizer_Tick(object sender, EventArgs e)
{
RandomImage();
patternRightNow = 0;
tickCount++;
Randomizer.Stop();
ClickCheck();
} //Use RandomImage() to lit up random PictureBoxes on 5 waves, wave 1 - 1 PictureBox, wave 2 - 2 PictureBoxes and so on.
This is ClickCheck():
private void ClickCheck()
{
TopLeft.Enabled = true;
TopRight.Enabled = true;
BottomLeft.Enabled = true;
BottomRight.Enabled = true;
if (tickCount == clickCount)
{
CheckIfWin();
Randomizer.Start();
}
} //Enables the PictureBoxes to be pressed, after the user input reaches the current wave's amount of PictureBoxes lit up, disable PictureBoxes again and start the randomizer
Instead of using timers, I advise you to look at Tasks. It's much easier to create such statemachines.
Fill a list with colors and play it. Wait until the user pressed enough buttons and check the results.
For example: (haven't tested it, it's just for example/pseudo code)
It might contain some typo's.
private List<int> _sequence = new List<int>();
private List<int> _userInput = new List<int>();
private Random _rnd = new Random(DataTime.UtcNow.Milliseconds);
private bool _running = true;
private bool _inputEnabled = false;
private TaskCompletionSource<object> _userInputReady;
public async void ButtonStart_Click(object sender, EventArgs e)
{
if(_running)
return;
while(_running)
{
// add a color/button
_sequence.Add(_rnd.Next(4));
// play the sequence
for(int color in _sequence)
{
// light-up your image, whatever
Console.WriteLine(color);
// wait here...
await Task.Delay(300);
// turn-off your image, whatever
}
// clear userinput
_userInput.Clear();
_userInputReady = new TaskCompletionSource<object>();
_inputEnabled = true;
// wait for user input.
await _userInputReady.Task;
// compare the user input to the sequence.
for(int i=0;i<_sequence.Count;i++)
{
if(_sequence[i] != _userInput[i])
{
_running = false;
break;
}
}
}
Console.WriteLine("Not correct");
}
// one handler for all buttons. Use the .Tag property to store 0, 1, 2, 3
public void ButtonClick(object sender, EventArgs e)
{
if(!_inputEnabled)
return;
var button = (Button)sender;
// add user input to the queue
_userInput.Add((int)button.Tag);
if(_userInput.Count >= _sequence.Count)
_userInputReady.SetResult(null);
}
I'm setting up a windowsform that pings all my IP's at work and changes the button.BackColor accordingly.
Ping pingClassxx = new Ping();
PingReply pingxx = pingClassxx.Send("192.168.xx.xx");
if (pingxx.Status == IPStatus.Success)
{
button1.BackColor = Color.Green;
button1.Text = "SQL Server | Online";
}
else
{
button1.BackColor = Color.Red;
button1.Text = "SQL Server | Offline";
}
Now I'm trying to do this to multiple machines so I went like this:
private void timer0_Tick(object sender, EventArgs e)
{
timer1.Stop();
int iCount0 = 0;
string[] arr = new string[8];
arr[0] = "192.168.x.xx"; //button0
arr[1] = "192.168.x.yy"; //button1
arr[2] = "192.168.x.zz"; //button2
arr[3] = "192.168.x.xy"; //button3
arr[4] = "192.168.x.xz"; //button4
arr[5] = "192.168.x.yx"; //button5
arr[6] = "192.168.yy.yz"; //button6
arr[7] = "192.168.x.ww"; //button7
for (int I = 0; I < arr.Length ; I++)
{
// Ping
string s = arr[I];
Console.WriteLine(s);
Ping pingClassx = new Ping();
PingReply pingx = pingClassx.Send(arr[I]);
if (pingx.Status == IPStatus.Success)
{
[What do I do here?].BackColor = Color.Green;
}
else
{
[What do I do here?]BackColor = Color.Red;
}
// Loading Bar
iCount2 += 1;
progressBar0.Value = iCount2 * 100 / 8;
label0.Text = iCount2 + "/8";
}
timer1.Start();
}
How can I loop this?
I could just repeat the code but I am sure there is a fancier way to do it.
If you want to Change the Color only Of Your Form Buttons then try This :
foreach(Button c in Form.Controls){
if (pingx.Status == IPStatus.Success)
{
c.BackColor = Color.Green;
}
else
{
c.BackColor = Color.Red;
}
}
What I'm trying to do is this:
I want the 4 pictureBoxes I got in the form to get the faces of card - turn them over I mean. a random card from the 4 will be chosen, turned over and show the face of the card being chosen also randomley.
Once a card is turned over, it cant be turend over again in the next timer interval, and once all cards had been turned over, a messageBox appears and once the user presses ok, it all restarts.
Problem is: the messageBox keeps appearing over and over again, because of the flag positive value. I don't know which variable should I use to prevent that from happening.
Relevant code:
//This function is the timer's function, it starts every time interval:
private void cardsChangingTimer_Tick(object sender, EventArgs e)
{
int chosenImage = rnd.Next(1, 17);
int chosenCard = rnd.Next(0, 4);
if (bucketArr[chosenCard] == 0)
{
bucketArr[chosenCard]++;
switch (chosenCard)
{
case 0:
card1Pic.Image = Image.FromFile("cards\\" + chosenImage + ".png");
break;
case 1:
card2Pic.Image = Image.FromFile("cards\\" + chosenImage + ".png");
break;
case 2:
card3Pic.Image = Image.FromFile("cards\\" + chosenImage + ".png");
break;
case 3:
card4Pic.Image = Image.FromFile("cards\\" + chosenImage + ".png");
break;
}
}
gameEnded = true;
for (int i = 0; i < bucketArr.Length; i++)
{
if (bucketArr[i] == 0)
{
gameEnded = false;
break;
}
}
if (gameEnded)
{
DialogResult dialog = MessageBox.Show("All 4 cards were turned over...");
if (dialog == DialogResult.OK)
{
card1Pic.Image = Image.FromFile("..\\..\\17.png");
card2Pic.Image = Image.FromFile("..\\..\\17.png");
card3Pic.Image = Image.FromFile("..\\..\\17.png");
card4Pic.Image = Image.FromFile("..\\..\\17.png");
}
gameEnded = false;
for(int i = 0; i < bucketArr.Length; i++)
bucketArr[i] = 0;
}
}
Thanks alot for any help...
The problem you are having is the timer is continuing to run while the dialog box is shown. Simply stop the timer before the MessageBox is shown then restart the timer after the box returns.
private void cardsChangingTimer_Tick(object sender, EventArgs e)
{
int chosenImage = rnd.Next(1, 17);
int chosenCard = rnd.Next(0, 4);
/// ... Rest of the code goes here
break;
}
}
if (gameEnded)
{
//Get a reference to the timer and stop it.
var timer = (Timer)sender;
timer.Stop();
DialogResult dialog = MessageBox.Show("All 4 cards were turned over...");
if (dialog == DialogResult.OK)
{
card1Pic.Image = Image.FromFile("..\\..\\17.png");
card2Pic.Image = Image.FromFile("..\\..\\17.png");
card3Pic.Image = Image.FromFile("..\\..\\17.png");
card4Pic.Image = Image.FromFile("..\\..\\17.png");
}
gameEnded = false;
for(int i = 0; i < bucketArr.Length; i++)
bucketArr[i] = 0;
//start the timer here after everything has been re-initialized.
timer.Start();
}
}
I want to access game objects (sprites) in my code in an Array but I have no idea how to do that, I am new to C#.
This is my testing code, but I am not getting any values:
void Start()
{
Sprite[] countries = Resources.LoadAll<Sprite>("MAPS");
sr = GetComponent<SpriteRenderer>();
names = new string[countries.Length];
for (int i = 0; i < names.Length; i++)
{
names[i] = countries[i].name;
//0 = red
//1 = green
if (UnityEngine.Random.Range(0, 2) == 0)
{
this.GetComponent<SpriteRenderer>().color = Color.red;
}
else
{
this.GetComponent<SpriteRenderer>().color = Color.green;
}
}
}
Instead of using this keyword:
if (UnityEngine.Random.Range(0, 2) == 0)
{
this.GetComponent<SpriteRenderer>().color = Color.red;
}
else
{
this.GetComponent<SpriteRenderer>().color = Color.green;
}
try to use countries[i]:
if (UnityEngine.Random.Range(0, 2) == 0)
{
countries[i].GetComponent<SpriteRenderer>().color = Color.red;
}
else
{
countries[i].GetComponent<SpriteRenderer>().color = Color.green;
}
I have dev express grid view, and trying to set column visibility run time, Some columns are not appearing in correct order i.e. RebateAmount i want to set to appear at 4th position but its appearing always on second position, any idea what's wrong in below code? i want all columns should be appear at position which i have set in visibility index.
if (currentColum.FieldName.Equals("TaxName"))
{
currentColum.Caption = #"abc";
}
else if (intGridType == 1 || intGridType == 0)//Both
{
if (currentColum.FieldName.Equals("PastCurrentCollectionTotal"))
{
currentColum.Visible = true;
currentColum.VisibleIndex = 15;
}
else if (currentColum.FieldName.Equals("PastCurrentCollectionVyajTotal"))
{
currentColum.Caption = #"Äyij";
currentColum.VisibleIndex = 16;
}
else if (currentColum.FieldName.Equals("PastCurrentCollectionNoticeFeeTotal"))
{
currentColum.Visible = true;
currentColum.VisibleIndex = 17;
}
else if (currentColum.FieldName.Equals("RebateAmount"))
{
currentColum.Visible = true;
currentColum.VisibleIndex = 18;
}
else if (currentColum.FieldName.Equals("PastCurrentCollectionTotalTotal"))
{
currentColum.Visible = true;
currentColum.VisibleIndex = 19;
}
else
currentColum.Visible = false;
}
else if (intGridType == 2)//Only Past
{
if (currentColum.FieldName.Equals("PastCollection"))
{
currentColum.Visible = true;
currentColum.VisibleIndex = 6;
}
else if (currentColum.FieldName.Equals("PastCollectionVyaj"))
{
currentColum.Visible = true;
currentColum.VisibleIndex = 7;
}
else if (currentColum.FieldName.Equals("PastCollectionNoticeFee"))
{
currentColum.Visible = true;
currentColum.VisibleIndex = 8;
}
else if (currentColum.FieldName.Equals("PastCollectionTotal"))
{
currentColum.Visible = true;
currentColum.VisibleIndex = 9;
}
else
currentColum.Visible = false;
System.Diagnostics.Debug.Print(currentColum.VisibleIndex.ToString() + currentColum.Name);
}
else if (intGridType == 3) //Only Current
{
if (currentColum.FieldName.Equals("CurrentCollection"))
{
currentColum.Visible = true;
currentColum.VisibleIndex = 10;
}
else if (currentColum.FieldName.Equals("CurrentCollectionVyaj"))
{
currentColum.Visible = true;
currentColum.VisibleIndex = 11;
}
else if (currentColum.FieldName.Equals("CurrentCollectionNoticeFee"))
{
currentColum.Visible = true;
currentColum.VisibleIndex = 12;
}
else if (currentColum.FieldName.Equals("CurrentCollectionTotal"))
{
currentColum.Visible = true;
currentColum.VisibleIndex = 13;
}
else if (currentColum.FieldName.Equals("RebateAmount"))
{
currentColum.Visible = true;
currentColum.VisibleIndex = 14;
}
else
currentColum.Visible = false;
}
Hide all columns and active ( Visible = true) one at a time in order you want