C# using a message box(yes/no) to restart my game [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am creating a minefield style game as a task and I am wondering if there is a quick easy way to restart my game. When the character walks on to a bomb, I have a message box pop up saying 'game over, try again?' with a Yes and No option. I want the No option to close the game and I want the Yes option to restart the game to its original state that it is opened in. Any ideas?
This is the message box code when it executes:
private void checkBomb( int X, int Y)
{
if (bombs[X, Y])
{
this.BackColor = Color.Red;
downBtn.Enabled = false;
upBtn.Enabled = false;
leftBtn.Enabled = false;
rightBtn.Enabled = false;
showBombs();
// Dialog box with two buttons: yes and no.
//
DialogResult result1 = MessageBox.Show("Game Over! Try again?",
"Game Over",
MessageBoxButtons.YesNo);
}
else
{
countBombs(X, Y);
}
}

I think you would be able to do the following:
MessageBoxResult result = MessageBox.Show("Game Over! Try again?",
"Game Over",
MessageBoxButtons.YesNo);
if (result == MessageBoxResult.No)
{
System.Windows.Application.Current.Shutdown();
}
if (result == MessageBoxResult.Yes)
{
//Restart your game
}

According to the MSDN website,
https://msdn.microsoft.com/en-us/library/system.windows.forms.application.restart(v=vs.110).aspx
You can use Restart() method if "Yes" is clicked, and Close() if "No" is clicked

Related

Unity3D with C# - Using Input field to answer question [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm creating a unity quiz game using input fields.
How can I use text from an input field to match with an answer in a c# script?
hijinxbassist's example is good, however, i made an example that includes the other parts as well, like adding event listeners and declaring the fields.
Checking for single correct answer:
public Button submitAnswerBtn; // assign a UI button object in editor
public InputField answerInput; // assign a UI inputfield object in editor
private string a1_right_answer = "foo"; // make it public and edit the answer in editor if you like
private void Awake()
{
// add event listener when button for submitting answer is clicked
submitAnswerBtn.onClick.AddListener(() => {
// validate the answer
if(answerInput.text.ToLower() == a1_right_answer) {
// success
Debug.Log("Correct");
} else {
Debug.Error("Wrong");
}
});
Checking for multiple correct answers:
public Button submitAnswerBtn; // assign a UI button object in editor
public InputField answerInput; // assign a UI inputfield object in editor
private string[] a1_right_answers = { "foo", "bar", "foo1", "bar1" }; // multiple right answers
private bool is_right_answer = false; // default value
private void Awake()
{
// add event listener when button for submitting answer is clicked
submitAnswerBtn.onClick.AddListener(() => {
// loop through all the right answers
for (int i = 0; i < a1_right_answers.Length; i++)
{
// validate the answer
if(answerInput.text.ToLower() == a1_right_answers[i]) {
// success
is_right_answer = true;
break;
}
}
// check if the user got the right or wrong answer
if(is_right_answer) {
Debug.Log("Correct");
is_right_answer = false; // reset for next guess
}
else {
Debug.Log("Wrong");
// no need to reset 'is_right_answer' since its value is already default
}
});
I am not sure which part of this problem you are stuck on, but I will attempt to answer.
I think the most important thing when comparing an input field with a stored answer is to make sure the comparison is case insensitive. You can do this by converting both texts to either lowercase or uppercase.
var usersAnswer = answerInputField.text.ToLower();
var actualAnswer = "Some Answer".ToLower();
if (usersAnswer == actualAnswer)
{
Debug.Log("You got it right!");
}

Two functions on same MouseClickEvent C# [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm having some difficulty making two separate functions inside the same MouseClick Eventhandler on a checkbox in C# using Winforms.
If the user clicks the checkbox it's supposed to come a warning for the user to verify the action. If the user un-checks the checkbox a different warning will show for the user to verify the action.
My code is the following:
private bool alreadyClicked = false;
private void myCheckbox_MouseClick(object sender, MouseEventArgs e)
{
if (!myCheckbox.Checked && !alreadyClicked)
{
DialogResult d1 = MessageBox.Show("Some text1", "Some title1", MessageBoxButtons.YesNo);
if (d1 == DialogResult.Yes)
{
myCheckbox.Checked = true;
alreadyClicked = true;
}
else
{
myCheckbox.Checked = false;
}
}
if (myCheckbox.Checked && alreadyClicked)
{
DialogResult d2 = MessageBox.Show("Some text2", "Some title2", MessageBoxButtons.YesNo);
if (d2 == DialogResult.Yes)
{
myCheckbox.Checked = false;
alreadyClicked = false;
}
else
{
myCheckbox.Checked = true;
}
}
}
The problem is that the second if-statement checking if the checkbox is checked and if the "alreadyClicked"-variable is true triggers when the user verifies the first action (to check the checkbox), which happens due to the "alreadyClicked"-variable being true before the event closes. I'm stuck and would appreciate any help.
Thanks in advance.
Well let's look at the two if statements.
When the checkbox is first clicked and the first messagebox will be answered with yes, you set the checkbox and the alreadyClicked variable to true. Right afterwards in the second if statement you check if those two values are true. Which they are of course because we just set them to true. Therefore the second if statement will be true and the second message will be displayed.
To prevent this behaviour you could use an else if (myCheckbox.Checked && alreadyClicked) after the first if statement. In that case the second if statement will only be processed, when the first one results to false.
You could also consider if the bool variable alreadyClicked is really adding any value here. As of my understanding it always has the same value as the checkbox itself.

Close current form if dialog results for dialogbox is cancel

I have a Form (frmcustlist).
At one time on this list i scan the list using a dataset and check if it now 0 (no customers left).
At this stage i have an input box pop up (dialog) to ask a new customer name.
If they press OK everything is fine. I also have validation on the box for the input.
However if they press CANCEL, i can get it to escape out of the dialog, but not close frmcustlist that the dialog was called from.
using (inputbox ipfirst = new inputbox("Enter Customer First Name:", "", ""))
{
if (ipfirst.ShowDialog() == DialogResult.OK)
{
newfirstname = ipfirst.answer;
}
else
{
this.Close();
}
}
Now, this.close() doesn't work at all.. so i used return; which stops it going on to ask for the last name and date of birth.. but i want it to stop asking questions (like return) AS WELL as close frmcustlist.
...
Thanks for any advice you can give.
ps. this appears in a few places, but is called in frmcustlist_load as well.. i dont know if that is going to make a difference or not!
Answer was made by STEVE in comments.
As frmcustlist was called itself as a Dialog, i just ended up having to give that dialog a Cancel result.
Final Code that works:
using (inputbox ipfirst = new inputbox("Enter Customer First Name:", "", ""))
{
if (ipfirst.ShowDialog() == DialogResult.OK)
{
newfirstname = ipfirst.answer;
}
else
{
DialogResult = DialogResult.Cancel;
return;
}
}

C# Stop the flow of the program and reset it without restarting

I am writing a simple WindowsForm program with radiobuttons, buttons, and a customary implemented InputBox.
Relevant program logic: I click one of the radiobutons from the groupbox -> enable button -> clicking button initiates custom inputbox asking for 1 value and Yes/Cancel buttons.
|
V
If Yes button clicked -> proceed with logic flow
If Cancel button clicked -> popup window appears ("Your input was cancelled, do you want to exit application?") with yes/no buttons
|
V
If Yes button clicked -> Exit the program
If No button clicked -> apply the same logic as if Reset button is clicked, which would reset the whole program without restarting it <---------This is what I am trying to achieve (all relevant methods are provided below)
What is the problem?
When I simply click Reset button, it applies all needed actions and stops, waiting for my further input. This is the exact result I am trying to achieve when I click No button in the popup window I mentioned above.
However, this is not the case. During the debug mode, after I clicked No button, it goes through the entire logic of the Reset button like I wanted, BUT right after that, it goes into the IF statement (marked in my buttonGetWorkHours_Click method). I don't want that, I want it to stop the flow after applying the logic of Reset button and waiting for my input (radiobutton/button click).
What I tried
I have searched through several threads here in SO and tried implementing several suggestions. The results of these suggestions are commented out inside inputBoxProcedure method. Also, I was looking for similar posts, which would give me the right idea. But they state that it is impossible without reloading. Based on that thread, I thought about implementing extra variable to use for checking if reset logic was running, but seems unnecessarily complicated.
ULTIMATE QUESTION:
I saw a test executable, so I know it is POSSIBLE, unlike what posts and threads were saying. Can you please point me in a right direction of how to proceed with it?
Relevant code snippet methods
For the sake of saving everyone's time I will include only methods relevant to my question.
private void buttonGetWorkHours_Click(object sender, EventArgs e)
{
if (radioButtonJobStatusFull.Checked)
{
inputBoxProcedure("Enter the total hours worked by the full time employee for the week", "40");
}
else if (radioButtonJobStatusPart.Checked)
{
inputBoxProcedure("Enter the total hours worked by the part time employee for the week", "30");
}
//if, else if, else, unrelated to the lines above
if() //<----------------the logic goes here after going through the whole Reset button logic
{}
else if()
{}
else()
{}
}
private void buttonReset_Click(object sender, EventArgs e)
{
//clear all radiobutton selections
//set all strings to empty
//disable several buttons and groupboxes
//hide several labels
}
private void inputBoxProcedure(string text, string defaulttext)
{
InputBoxResult result = InputBox.Show(text, "Hours Entry", defaulttext, new InputBoxValidatingHandler(inputBox_Validating));
if (result.OK)
{
labelHoursWorked.Text = result.Text.Trim();
}
else
{
if (MessageBox.Show("Input was cancelled. Do you wish to quit the application?", "Input Cancelled", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
{
Close();
}
else
{
buttonReset_Click(this, new EventArgs());
//Form fr = new Form();
//fr.Show();
//this.Close();
//Application.Restart();
}
}
}
Try changing the inputBoxProcedure to this:
private bool inputBoxProcedure(string text, string defaulttext)
{
InputBoxResult result = InputBox.Show(text, "Hours Entry", defaulttext, new InputBoxValidatingHandler(inputBox_Validating));
if (result.OK)
{
labelHoursWorked.Text = result.Text.Trim();
}
else
{
if (MessageBox.Show("Input was cancelled. Do you wish to quit the application?", "Input Cancelled", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
{
Close();
}
else
{
buttonReset_Click(this, new EventArgs());
//Form fr = new Form();
//fr.Show();
//this.Close();
//Application.Restart();
return false; // Added
}
}
return true; // Added
}
Notice that the return type void becomes bool and that two lines of return have been added.
In buttonGetWorkHours_Click change:
if (radioButtonJobStatusFull.Checked)
{
inputBoxProcedure("Enter the total hours worked by the full time employee for the week", "40");
}
else if (radioButtonJobStatusPart.Checked)
{
inputBoxProcedure("Enter the total hours worked by the part time employee for the week", "30");
}
Into:
if (radioButtonJobStatusFull.Checked)
{
if (!inputBoxProcedure("Enter the total hours worked by the full time employee for the week", "40"))
return;
}
else if (radioButtonJobStatusPart.Checked)
{
if (!inputBoxProcedure("Enter the total hours worked by the part time employee for the week", "30"))
return;
}
In this way, after a reset, the funtion inputBoxProcedure will return false. When the function returns false the function buttonGetWorkHours_Click will return and thus prevent further excecution.
I hope this helps.

How can i close all forms and processes(explorer) windows when i quit my program?

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("Are you Sure you want to Exit. Click Yes to Confirm and No to continue", "WinForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
e.Cancel = true;
}
else
{
Application.Exit();
}
}
Application.Exit(); for some reason make me to click twice YES before the program quit.
And It dosent close explorer windows like this:
Process.Start("explorer", String.Format("/select,{0}", t));
This explorer keep open when i quit my program.
Well, technically these windows do not belong to your application, so they should not be closed.
EDIT, regarding the comment: the solution provided below won't work, sorry, my mistake :)
If you really want to control explorer windows you've opened you can collect the return value of the Start method ( http://msdn.microsoft.com/en-us/library/53ezey2s.aspx ), and then call the Kill method on each of them ( http://msdn.microsoft.com/en-us/library/system.diagnostics.process.kill.aspx ). Remember to check if they still exist as the user might have closed them on their own.
Simple example for one window:
class Form
{
//...
private Process explorerWindow = null;
}
//...
this.explorerWindow = Process.Start("explorer", String.Format("/select,{0}", t));
//... (in OnFormClosing)
if (this.explorerWindow != null && !this.explorerWindow.HasExited)
{
this.explorerWindow.Kill();
}
Do similar, but with the List. You could also hook up to the OnExited event and remove particular processes from the list, when they disappear (f.e. because the user closed them).

Categories

Resources