Entering an "If" statement where it shouldn't [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
This code should monitor the user's keystrokes and stops him if s\he types a the wrong character .Yet when it comes to the if statement where it should compare to charecter everything just goes wrong
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;
using System.Diagnostics;
using System.Threading;
using System.Collections;
using System.IO;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
void Rest()
{
counter = -1;
txt1.Enabled = true;
txt2.Enabled = true;
txt3.Enabled = true;
txt4.Enabled = false;
txt5.Enabled = true;
btn2.Enabled = false;
btn1.Enabled = true;
pass = "";
txt4.Clear();
Dic.Clear();
turns = 0;
}
string path;
int counter = -1;
string pass;
Dictionary<char, letterInfo> Dic;
int turns = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (counter < pass.Length) { MessageBox.Show("WrongInput(Shorter) !!! "); Rest(); }
else
{
turns++;
if (turns == Convert.ToInt32(txt1.Text))
{
MessageBox.Show("Test is Done ");
/*Writting files */
Rest();
}
}
}
counter++;
if (counter >= pass.Length) { MessageBox.Show("WrongInput !!!exceded length "); Rest(); }
if ((char)e.KeyValue != pass[counter]) { MessageBox.Show("WrongInput !!!Wrong charecter " + ((char)e.KeyValue).ToString() + " " + pass[counter].ToString()); Rest(); }
if (Dic.ContainsKey((char)e.KeyValue))
{
Dic[(char)e.KeyValue].start.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
else
{
Dic.Add((char)e.KeyValue, new letterInfo());
Dic[(char)e.KeyValue].start.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
Dic[(char)e.KeyValue].end.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
private void button1_Click(object sender, EventArgs e)
{
string start = "";
string end = "";
string letter = "";
string all;
foreach (KeyValuePair<char, letterInfo> pair in Dic)
{
start = start + " " + pair.Value.start[0];
end = end + " " + pair.Value.end[0];
letter = letter + " " + pair.Key;
}
all = letter + "\n" + start + "\n" + end;
MessageBox.Show(all);
}
private void button2_Click(object sender, EventArgs e)
{
try
{
txt1.Enabled = false;
txt2.Enabled = false;
txt3.Enabled = false;
txt4.Enabled = true;
txt5.Enabled = false;
btn2.Enabled = true;
btn1.Enabled = false;
pass = txt2.Text;
path = txt3.Text;
counter = Convert.ToInt32(txt1.Text);
Dic = new Dictionary<char, letterInfo>();
/* if (!File.Exists(path))
{
MessageBox.Show("Error..File not found");
Rest();
}Code to handle the xls files */
}
catch (Exception s)
{ MessageBox.Show(s.Message); }
}
}
}
This is the function where the problem occurs
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (counter < pass.Length)
{
MessageBox.Show("WrongInput(Shorter) !!! "); Rest();
}
else
{
turns++;
if (turns == Convert.ToInt32(txt1.Text))
{
MessageBox.Show("Test is Done ");
/*Writting files */
Rest();
}
}
}
counter++;
if (counter >= pass.Length)
{
MessageBox.Show("WrongInput !!!exceded length "); Rest();
}
if ((char)e.KeyValue != pass[counter])
{
MessageBox.Show("WrongInput !!!Wrong charecter "+((char)e.KeyValue).ToString()+" "+pass[counter].ToString()); Rest();
}
if (Dic.ContainsKey((char)e.KeyValue))
{
Dic[(char)e.KeyValue].start.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
else
{
Dic.Add((char)e.KeyValue, new letterInfo());
Dic[(char)e.KeyValue].start.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
}
And those are the problematic if statements
counter++;
if (counter >= pass.Length)
{
MessageBox.Show("WrongInput !!!exceded length "); Rest();
}
if ((char)e.KeyValue != pass[counter])
{
MessageBox.Show("WrongInput !!!Wrong charecter "+((char)e.KeyValue).ToString()+" "+pass[counter].ToString()); Rest();
}

You enter into if (counter >= pass.Length) because:
counter = -1; //starts at -1
pass = ""; //starts at empty string (length of zero)
Neither of these variables change in your code until:
counter++; //counter is now 0
counter is now equal to pass.Length. So the if statement is true and "WrongInput !!!exceded length " is printed.
You dont set the value of pass until button 2 is clicked. So on each keypress event that is fired, the pass value is empty.
In if ((char)e.KeyValue != pass[counter]) you are trying to compare the key entered, with the character number in pass. pass is empty and counter increments until you hit button 2. So e.Keyvalue will not equal pass[counter] every time.

Related

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.

From C# To Arduino using Serial.Port

Hi guys I need your help with my project. I have a 2 textboxes (type string) in a C# program and i need to send this numbers to Arduino using a Serial.Port. So far i got to send one of the values to arduino but it doesn't work very well if I enter "1200" arduino reads and show: 1,2,0,0 i need "1200". How i send 2 values from C# to Arduino? How the arduino will read these values (x and y)?
C#
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;
using System.IO.Ports; // necessário para ter acesso as portas
namespace interfaceArduinoVS2013
{
public partial class Form1 : Form
{
string RxString;
public Form1()
{
InitializeComponent();
timerCOM.Enabled = true;
}
private void atualizaListaCOMs()
{
int i;
bool quantDiferente; //If there are more ports
i = 0;
quantDiferente = false;
//if there are new ports
if (comboBox1.Items.Count == SerialPort.GetPortNames().Length)
{
foreach (string s in SerialPort.GetPortNames())
{
if (comboBox1.Items[i++].Equals(s) == false)
{
quantDiferente = true;
}
}
}
else
{
quantDiferente = true;
}
//it was't detected difference
if (quantDiferente == false)
{
return;
}
//clean comboBox
comboBox1.Items.Clear();
//add all the COMs in the list
foreach (string s in SerialPort.GetPortNames())
{
comboBox1.Items.Add(s);
}
//select the first position
comboBox1.SelectedIndex = 0;
}
private void timerCOM_Tick(object sender, EventArgs e)
{
atualizaListaCOMs();
}
private void btConectar_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen == false)
{
try
{
serialPort1.PortName = comboBox1.Items[comboBox1.SelectedIndex].ToString();
serialPort1.Open();
}
catch
{
return;
}
if (serialPort1.IsOpen)
{
btConectar.Text = "Desconectar";
comboBox1.Enabled = false;
}
}
else
{
try
{
serialPort1.Close();
comboBox1.Enabled = true;
btConectar.Text = "Conectar";
}
catch
{
return;
}
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if(serialPort1.IsOpen == true) // if the port is open
serialPort1.Close(); //close
}
private void btEnviar_Click(object sender, EventArgs e)
{
if(serialPort1.IsOpen == true) //porta está aberta
serialPort1.Write(textBoxX.Text); //send the text from textboxX
serialPort1.Write(textBoxY.Text);
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
RxString = serialPort1.ReadExisting(); //read data from serial
this.Invoke(new EventHandler(trataDadoRecebido));
}
private void trataDadoRecebido(object sender, EventArgs e)
{
textBoxReceber.AppendText(RxString);
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
Arduino Script
void setup()
{
Serial.begin(9600);
}
void loop()
{
if(Serial.available())
{
char c = Serial.read();
Serial.println(c);
}
}
Reading data through serial port and separating them using strings.
In C#
Add a unique character to starting of 1st box data.
Add a unique character to starting of 2nd box data.
Add a unique character to ending of 2nd box data.
Append two strings and send as single string.
I had a VB example:
Dim WithEvents ADRport As SerialPort = New System.IO.Ports.SerialPort("COM1", 9600, Parity.None, 8, StopBits.One)
msg = "$" & box1.Text & "#" & box2.Text & "*" & vbCrLf
ADRport.Write(msg)
In Arduino:
//--- Wait for the message starting -----
while(Serial.read()!='$');
while (!flag)
{
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
mstr += inChar;
//Serial.write(inChar);
// if the incoming character is a end of line, set a flag
if (inChar == '*')
{
flag = true;
}
}
Seperate strings using
int 1start = int(mstr.indexOf('$'));
int 2start = int(mstr.indexOf('#',numstart+1));
int 2end = int(mstr.indexOf('*'));
text1 = mstr.substring(1start+1,2start);
text2 = mstr.substring(2start+1,2end);
text1.trim();
text1.trim();
Then display it onn lcd/serialport:
lcd.setCursor(0,0);
lcd.print(msg);
Please note that '$' will not get added to the string.
This is what i did, and it worked:
C#
serialPort1.WriteLine(eixver.Text.ToString()+";"+ eixHor.Text.ToString());
Arduino:
int val;
int h, v;
String cont;
void setup() {
Serial.begin(9600);
}
void loop() {
while(Serial.available())
{
char caracter = Serial.read();
cont.concat(caracter);
delay(5);
}
if(cont!="")
{
// Serial.println(cont);
v=cont.substring(0, cont.indexOf(';')).toInt();
h=cont.substring(cont.indexOf(';')+1, cont.length()).toInt();
Serial.print("v=");
Serial.print(v);
Serial.print(" - h=");
Serial.print(h);
cont="";
}
}
I think, this is good for you. C# part:
Connect();
if (serialPort1.IsOpen)
{
double MyInt = ToDouble(lblMixerCase.Text);
byte[] b = GetBytes(MyInt);
serialPort1.Write(b, 0, 1);
double MyInt2 = ToDouble(txtRPM.Text);
byte[] z = GetBytes(MyInt2);
serialPort1.Write(z, 0, 1);
if (MyInt2>1600)
{
MessageBox.Show("Please enter RPM value between 0 and 1600");
}
double MyInt3 = ToDouble(lblCaseRpmSecond.Text);
byte[] p = GetBytes(MyInt3);
serialPort1.Write(p, 0, 1);
double MyInt4 = ToDouble(lblRpmCaseThree.Text);
byte[] s = GetBytes(MyInt3);
serialPort1.Write(s, 0, 1);
serialPort1.Close();
Arduino part:
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
if (Serial.available() > 0) {
// read the incoming byte:
n = Serial.read();
if (i < 3)
{
number[i] = n;
switch (number[0])
{
case 1:
if (i == 2)
{
switch(number[1])
{
case 1:
openClose();
break;
case 2:
openCloseTwice();
break;
case 3:
openCloseThree();
break;
default:
openCloseIwanted(number[1], number[2]);
break;
}
}
break;
case 2:
if (i == 2)
{
switch(number[1])
{
case 1:
openClose();
break;
case 2:
openCloseTwice();
break;
case 3:
openCloseThree();
break;
default:
openCloseIwanted(number[1], number[2]);
break;
}
}
break;
case 3:
if (i == 2)
{
openCloseIwanted(number[1], number[2]);
}
break;
default:
if (i == 2)
{
openCloseIwanted(number[1], number[2]);
}
break;
}
i++;
if (i == 3)
{
asm volatile (" jmp 0"); //For reset Arduino
}
}
else
{
i = 0;
}
}

Creating a Counter for user input 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.

Right to left typing in text box?

I have a Currency Textbox with a mask.
Mask is shown in textbox as --------.--
So user types in digits over the mask.
Now customer says he does not want to type in letter from left to right.
He wants to type from right to left.
Similar to what we have in calculator.
Now I tried changing the textbox's righttoleft property but that does not help my cause.
In the end I am stuck with handling the key event to manually change the position.
I am able to change the position but getting stuck completing the logic.
Here's how my code looks like :
void Textbx_KeyDown(object sender, KeyEventArgs e)
{
String temp = T.Text;
string temp2 = T.Text;
int CursorIndex = T.SelectionStart - 1;
for (int i = 0; i <= CursorIndex; i++)
{
if (i == 7)
{
temp2 = temp2.Insert(i, temp[i + 2].ToString());
temp2 = temp2.Remove(i, 2);
//i = i + 2;
}
else if (CursorIndex == i)
{
temp2 = temp2.Remove(i, 1);
temp2 = temp2.Insert(i, temp[i + 1].ToString());
}
else
{
// T.Text = T.Text.Insert(i + 1, "_");
temp2 = temp2.Insert(i, temp[i + 1].ToString());
temp2 = temp2.Remove(i + 1, 1);
}
}
T.Text = temp2;
// T.Text = T.Text.Insert(CursorIndex-1, temp[CursorIndex].ToString());
if (CursorIndex != -1)
T.SelectionStart = CursorIndex - 1;
}
Is there a better way to do this? If not how should I go about completing the logic?
There is a property for that in the textbox:
T.RightToLeft = RightToLeft.Yes
I have written this code for you; please try it:
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
{
string mychar = "000000";
string mtxt;
int mypos = 6;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
maskedTextBox1.Text = mychar;
}
private void maskedTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
mtxt = mtxt + e.KeyChar;
mypos--;
mychar = mychar.Remove(mypos, mtxt.Length);
mychar = mychar.Insert(mypos, mtxt);
maskedTextBox1.Text = mychar;
}
}
}
try this using a maskedTextBox.
set TextMaskFormat Property = IncludePrompt
private void maskedTextBox1_Click(object sender, EventArgs e)
{
maskedTextBox1.SelectionStart = maskedTextBox1.Mask.Length + 1;
}
private void maskedTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != (char) Keys.Back)
{
String a = maskedTextBox1.Text + e.KeyChar;
maskedTextBox1.Text = a.Substring(1, a.Length - 1);
maskedTextBox1.SelectionStart = maskedTextBox1.Mask.Length + 1;
}
}
private void maskedTextBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
{
maskedTextBox1.Text = "_" + maskedTextBox1.Text;
maskedTextBox1.SelectionStart = maskedTextBox1.Mask.Length + 1;
}
}

Why am i getting nonstop message boxes?

So i working on a breakout game and so far everything has been going well, but when i make the the ball picturebox go off screen i seem to getting an unlimited amount of message boxes.
here is the code snippet
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
{
List<Brick> bricks = new List<Brick>();
Ball _ball;
Paddle _paddle;
DateTime startTime = DateTime.Now;
DateTime startTime2 = DateTime.Now;
float ballVelocityX = 0;
float ballVelocityY = -1;
float ballSpeed = 20;
public Form1()
{
InitializeComponent();
timer1.Enabled = true;
timer2.Enabled = true;
startTime = DateTime.Now;
System.Media.SoundPlayer sndPlayer;
sndPlayer = new System.Media.SoundPlayer(Properties.Resources._01_Calm_1);
foreach (PictureBox brick in panel1.Controls)
{
if (brick.Name != "ball" && brick.Name != "paddle")
bricks.Add(new Brick(brick));
else if (brick.Name == "ball")
_ball = new Ball(brick);
else if (brick.Name == "paddle")
_paddle = new Paddle(brick);
//sndPlayer.Play();
}
}
private void gameTimer_Tick(object sender, EventArgs e)
{
checkBrickCollision();
checkPaddleCollision();
checkBallScreenBounds();
ball.SetBounds(ball.Location.X + (int)(ballVelocityX * ballSpeed),
ball.Location.Y + (int)(ballVelocityY * ballSpeed),
ball.Size.Width, ball.Size.Height);
paddle.SetBounds(Cursor.Position.X - panel1.Location.X, paddle.Location.Y,
paddle.Size.Width, paddle.Size.Height);
}
private void checkBallScreenBounds()
{
if (_ball.BallRectangle.Location.X + 25 > panel1.Size.Width)
ballVelocityX *= -1;
else if (_ball.BallRectangle.Location.X < 0)
ballVelocityX *= -1;
else if (_ball.BallRectangle.Location.Y < 0)
ballVelocityY *= -1;
else if (_ball.BallRectangle.Location.Y > panel1.Size.Height)
ballOffScreen();
}
private void ballOffScreen()
{
new_start();
Startnew startnew = new Startnew();
startnew.Show();
this.Close();
}
private void new_start()
{
TimeSpan elapsedTime = DateTime.Now - startTime2;
DialogResult result;
result = MessageBox.Show("Your total time is " + ":" + elapsedTime.Minutes + elapsedTime.Seconds
+ " would you like to play aigan?", "Application1", MessageBoxButtons.YesNo);
if (result == DialogResult.No)
{
Form1 form1 = new Form1();
form1.Show();
}
else if (result == DialogResult.Yes)
{
this.Close();
}
//MessageBox.Show("Total time is " + elapsedTime.Minutes + ":" + elapsedTime.Seconds);
}
private void checkPaddleCollision()
{
int tmpBallVelocityX = _paddle.CheckPaddleMovement();
if (_ball.BallRectangle.IntersectsWith(_paddle.PaddleRectangle))
{
ballVelocityX = tmpBallVelocityX;
ballVelocityY *= -1;
}
}
private void checkBrickCollision()
{
Rectangle ballRectangle = _ball.BallRectangle;
foreach (Brick brick in bricks)
if (brick.IntersectWith(ballRectangle))
{
bricks.Remove(brick);
ballVelocityX *= -1;
ballVelocityY *= -1;
break;
}
}
private void panel1_MouseEnter(object sender, EventArgs e)
{
Cursor.Hide();
}
private void panel1_MouseLeave(object sender, EventArgs e)
{
Cursor.Show();
}
public void Form_closse(object sender, FormClosedEventArgs e)
{
//ProgramInfo.ProgramState = State.Splash_Screen;
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void timer1_tick(object sender, EventArgs e)
{
LabelTime.Text = "It is " + DateTime.Now;
}
private void timer2_tick(object sender, EventArgs e)
{
TimeSpan elapsedTime = DateTime.Now - startTime;
labelElapsedTime.Text = "Time Elapsed " + elapsedTime.Minutes + ":" + elapsedTime.Seconds;
}
}
}
` #**EDIT**#`
`**because things were getting a bit confusing i posted all my code.**`
ive done this with a button and it works fine and all, but i need to pop up only once. is there any way to only have it called once?
if new_start() is part of Form1,
Following line looks like culprit, but more code is required for closer look.
if (result == DialogResult.No)
{
Form1 form1 = new Form1();
form1.Show(); //This line is creating endless messagebox on selecting NO
}
UPDATE Based on information in comments,
you can control the new_start function with flag
private bool checkNewGame = false;
private void new_start()
{
if(checkNewGame) return;
checkNewGame = true;
TimeSpan elapsedTime = DateTime.Now - startTime2;
DialogResult result;
result = MessageBox.Show("Your total time is " + ":" + elapsedTime.Minutes + elapsedTime.Seconds
+ " would you like to play aigan?", "Application1", MessageBoxButtons.YesNo);
if (result == DialogResult.No)
{
Form1 form1 = new Form1();
form1.Show();
}
else if (result == DialogResult.Yes)
{
checkNewGame = true;
this.Close();
}
UPDATE 2
Instead of
if (result == DialogResult.No)
{
Form1 form1 = new Form1();
form1.Show(); //This line is creating endless messagebox on selecting NO
}
do something like
if (result == DialogResult.No)
{
this.Clear(); // Create new function Clear, and clear all the Form state.
}
void clear()
{
... //RESET all form state
}
Most likely the code that supposed to restart the game does not clear "ball-Off-Screen" condition and your game immediately goes to end of game.
Note: Debugging should immediately show the reason of the behavior...

Categories