C# tic tac toe help! beginner [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 7 years ago.
Improve this question
I am a complete beginner at c# and i am making a tic tac toe game. I am having trouble understanding what is wrong with this code for my click property for each picture box i have 9 it breaks when i run it on visual studious:
private void pbxSquare0_Click(object sender, EventArgs e)
{
PictureBox pct = (PictureBox)sender;
int pic = Convert.ToInt32((pct.Name).Substring(10,1));
count++;
//switching the condition for each picture box
switch (pic)
{
case 1:
{
if (pict1 == 0) { pict1++; pbxSquare0.BackgroundImage = pictr; }
else if (pict1 == 2) { pbxSquare0.Enabled = false; } break;
}
case 2:
{
if (pict2 == 0) { pict2++; pbxSquare1.BackgroundImage = pictr; }
else if (pict2 == 2) { pbxSquare1.Enabled = false; } break;
}
case 3:
{
if (pict3 == 0) { pict3++; pbxSquare2.BackgroundImage = pictr; }
else if (pict3 == 2) { pbxSquare2.Enabled = false; } break;
}
case 4:
{
if (pict4 == 0) { pict4++; pbxSquare3.BackgroundImage = pictr; }
else if (pict4 == 2) { pbxSquare3.Enabled = false; } break;
}
case 5:
{
if (pict5 == 0) { pict5++; pbxSquare4.BackgroundImage = pictr; }
else if (pict5 == 2) { pbxSquare4.Enabled = false; } break;
}
case 6:
{
if (pict6 == 0) { pict6++; pbxSquare5.BackgroundImage = pictr; }
else if (pict6 == 2) { pbxSquare5.Enabled = false; } break;
}
case 7:
{
if (pict7 == 0) { pict7++; pbxSquare6.BackgroundImage = pictr; }
else if (pict7 == 2) { pbxSquare7.Enabled = false; } break;
}
case 8:
{
if (pict8 == 0) { pict8++; pbxSquare7.BackgroundImage = pictr; }
else if (pict8 == 2) { pbxSquare7.Enabled = false; } break;
}
case 9:
{
if (pict9 == 0) { pict9++; pbxSquare8.BackgroundImage = pictr; }
else if (pict9 == 2) { pbxSquare8.Enabled = false; } break;
}
default: break;

This isn't complete code but I do see a problem:
You are using the component name to figure out what box was clicked. (Bad idea--you should be using the Tag property!) However, the boxes are labeled 0 to 8 in that switch statement--but the box number extracted from the name is in the 1 to 9 range.
Whether this causes a crash I do not know--you don't have complete code to see what happens.
Also, look at lists or arrays to hold your boxes--there's no reason for a switch statement here.

Related

How can I read a specific key in c# being anywhere in the program. c#

I'm a beginner programer that have started programming a week ago. As part of the learning to consolidate knowledge, I try to recreate my Toothbrush program. I want to dependent the program on two keys PowerButton and OptionButton.
Here's the code:
Console.WriteLine("Hello!");
int powerButtonCount = 0;
int optionButtonCount = 0;
if (Console.ReadKey().KeyChar == 'p')
{
powerButtonCount++;
while (powerButtonCount >= 1)
{
if (Console.ReadKey().KeyChar == 'o')
{
optionButtonCount++;
switch (optionButtonCount)
{
case 1:
Console.WriteLine("Sensitive");
while (powerButtonCount == 2 && optionButtonCount == 1)
{
Console.WriteLine("Brushing in Sensitive mode!");
}
break;
case 2:
Console.WriteLine("Gum Care");
while (powerButtonCount == 2 && optionButtonCount == 2)
{
Console.WriteLine("Brushing in Gum Care mode!");
}
break;
case 3:
Console.WriteLine("Intense");
while (powerButtonCount == 2 && optionButtonCount == 3)
{
Console.WriteLine("Brushing in Intense mode!");
}
break;
case 4:
Console.WriteLine("Daily Clean");
while (powerButtonCount == 2 && optionButtonCount == 4)
{
Console.WriteLine("Brushing in Daily Clean mode!");
}
break;
case 5:
Console.WriteLine("Whiten");
while (powerButtonCount == 2 && optionButtonCount == 5)
{
Console.WriteLine("Brushing in Whiten mode!");
}
break;
}
}
else if (powerButtonCount == 3)
{
powerButtonCount = 0;
Console.WriteLine("Good Bye!");
}
}
}
What I came across is problem that I can't read input from user in realtime. After my testing, seems like I'm able to jump between switches, but when I want to initialize "Brushing thing" C# doesn't read 'p'.

How do I access a variable from a switch statement? [duplicate]

This question already has answers here:
Switch variable to use externally
(5 answers)
Closed 8 months ago.
I have just started learning C# with one of brackey's tutorials, and I have tried to make a simple quiz. I have tried everything I could have thought to do (basically deleting instances of the variables I was having trouble with), and I can't find anything online that I can understand or implement into my current scenario.
using System;
namespace Learning_C_
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Are you ready to solve some math equations?");
// I'm not sure what this indent is
if (Console.ReadLine() == "Yes")
{
Console.WriteLine("Definitely Generating Math Equations");
} else {
Console.WriteLine("Well thats too bad... You have too anyways");
}
Console.Write("Solve for x\n5x + 5 = 25\nx = ");
int ans01 = Convert.ToInt32(Console.ReadLine());
bool correct01 = false;
switch (ans01) {
case 4:
bool correct01 = true;
Console.WriteLine("Wow, you got it correct!\nThat's 1/3");
break;
default:
bool correct01 = false;
Console.WriteLine("Oops! You got that one incorrect...\n0/3");
break;
}
Console.Write("Solve\n75 + 2 * 12.5 = ");
int ans02 = Convert.ToInt32(Console.ReadLine());
bool correct02 = false;
switch (ans01){
case 100:
bool correct02 = true;
if(correct01 == true){
Console.WriteLine("Wow, you got it correct!\nThat's 2/3");
} else {
Console.WriteLine("Wow, you got it correct!\nThat's 1/3");
}
break;
default:
bool correct02 = false;
if (correct01 == true)
{
Console.WriteLine("Oops! You got that one incorrect...\n1/3");
}
else
{
Console.WriteLine("Oops! You got that one incorrect...\n0/3");
}
break;
}
Console.Write("Simplify\n5(4n + 3) = 23\nAnswer: ");
string ans03 = Convert.ToString(Console.ReadLine());
switch (ans03){
case "n = 1":
if(correct01 == true || correct02 == true){
Console.WriteLine("Wow, you got it correct!\nThat's 2/3");
} else if (correct01 == true && correct02 == true){
Console.WriteLine("Wow, you got it correct!\nThat's 3/3, congrats! You aced this test!");
}
break;
default:
if (correct01 == true || correct02 == true)
{
Console.WriteLine("Oops! You got that one incorrect...\n1/3");
}
else if(correct01 == true && correct02 == true){
Console.WriteLine("Oops! You got that one incorrect...\n2/3");
}
break;
}
// Wait before closing
Console.ReadKey();
}
}
}
My issue is I can't seem to reference these correct01 and 02 variables so that I can display the correct amount of points. I'm not sure if this is because they are defined in the switch statement but I can't seem to use them anywhere else. VS Code is also complaining that they are not used in the switch statement themselves.
Overall, I need a way to reference the correct01 and 02 variables from inside the switch statements.
Because you had decalred two variable with the same name.
Remove the bool that is in the switch statement
bool correct01 = false;
switch (ans01){
case 4:
correct01 = true;
Console.WriteLine("Wow, you got it correct!\nThat's 1/3");
break;
default:
correct01 = false;
Console.WriteLine("Oops! You got that one incorrect...\n0/3");
break;
}

Insurance Question Skipping Issue - Unity C#

I'm making a sort of quiz game using C# in Unity where the questions have to come in a certain order after pressing a button. My issue is that questions are being skipped, and instead of questions going in order 1, 2, 3, 4; they're instead going like 1, 4 thereby skipping questions 2 and 3 entirely.
I'm not at all familiar with C# or Unity, and even with coding, I'd say I have an intermediate understanding with it. So I'm not exactly understanding what the issue is. I've tried googling it but I haven't seen anything that related to my issue.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ClickingButtons : MonoBehaviour
{
public Button LeftButton;
public Button RightButton;
public Text LeftText;
public Text RightText;
public Text PlaceholderText;
int i = 0;
public void Start()
{
LeftText.text = "Male";
RightText.text = "Female";
PlaceholderText.text = "Are you a male or a female?";
}
public void SetTextLeft(string text)
{
if (i == 0 )
{
i++;
LeftText.text = "Yes";
PlaceholderText.text = "Are you married?";
RightText.text = "No";
}
if (i == 1){
i++;
PlaceholderText.text = "Do you have any kids?";
}
}
public void SetTextRight(string text)
{
if (i == 0)
{
i++;
LeftText.text = "Yes";
PlaceholderText.text = "Are you married?";
RightText.text = "No";
}
if (i == 1){
i++;
PlaceholderText.text = "Do you have any kids?";
}
}
}
This is where I believe where the problem lies:
public void Start()
{
LeftText.text = "Male";
RightText.text = "Female";
PlaceholderText.text = "Are you a male or a female?";
}
public void SetTextLeft(string text)
{
if (i == 0 )
{
i++;
LeftText.text = "Yes";
PlaceholderText.text = "Are you married?";
RightText.text = "No";
}
if (i == 1){
i++;
PlaceholderText.text = "Do you have any kids?";
}
}
public void SetTextRight(string text)
{
if (i == 0)
{
i++;
LeftText.text = "Yes";
PlaceholderText.text = "Are you married?";
RightText.text = "No";
}
if (i == 1){
i++;
PlaceholderText.text = "Do you have any kids?";
}
}
I'm sure the issue is an easy one to fix, but I'm just not understanding it.
This looks like a logical problem to me.
public void SetTextLeft(string text)
{
if (i == 0 )
{
i++;
}
if (i == 1)
{
i++;
}
}
I removed the question-specific code to call out the issue, but you check if i == 0 and then increment within that if statement. Then you do another if statement checking if i == 1. You can kind of see that the logical problem in that.
Here's the pseudo-logic
i = 0
if i == 0
i = 1
if i == 1
i = 2
etc...
So the logic will continue incrementing i until there are no more if statements.
What you likely want is a switch-case statement or if-else statements. Here's two examples:
switch(i)
{
case 0:
i++;
// show question 0
break;
case 1:
i++;
// show question 1
break;
case 2:
i++;
// show question 2
break;
}
or you can use an if-else like this
if (i == 0)
{
i++;
// show question 0;
}
else if (i == 1)
{
i++;
// show question 1;
}
else if (i == 2)
{
i++;
// show question 2;
}
I think the i++ is causing all your if conditions to be considered true.
Use an else if or better a switch statement.
I would also rename i to something indicating its purpose, e.g. _questionNumber.
Switch-case
public void SetTextLeft(string text)
{
switch (i)
{
case 0:
LeftText.text = "Yes";
PlaceholderText.text = "Are you married?";
RightText.text = "No";
break;
case 1:
PlaceholderText.text = "Do you have any kids?";
break;
default:
throw new Exception("unexpected question number");
}
}
If-else
public void SetTextLeft(string text)
{
if (i == 0)
{
i++;
LeftText.text = "Yes";
PlaceholderText.text = "Are you married?";
RightText.text = "No";
}
else if (i == 1)
{
i++;
PlaceholderText.text = "Do you have any kids?";
}
}

C# checking if expression is brackets valid [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
The expression:
"( a[i]+{-1}*(8-9) )"
should return true since it is valid to write syntax like this. Every left bracket has a right closer in the correct place and all brackets are at legal positions.
I tried to do this via one stack and I know where I'm wrong but I want to know a relevant way to solve this.
thx!
My poor poor wrong code:
string expression = "( a[i]+{-1}*(8-9) ) ";
Stack<char> expStack = new Stack<char>();
List<char> rightBracketsHolder = new List<char>();
for (int i = 0; i < expression.Length; i++)
{
if (expression[i] == '{')
{
expStack.Push('}');
Console.Write("}" + " ");
}
else if (expression[i] == '(')
{
expStack.Push(')');
Console.Write(")" + " ");
}
else if (expression[i] == '[')
{
expStack.Push(']');
Console.Write("]" + " ");
}
}
Console.WriteLine();
for (int i = 0; i < expression.Length; i++)
{
if (expression[i] == '}')
{
rightBracketsHolder.Add('}');
Console.Write(expression[i] + " ");
}
else if (expression[i] == ')')
{
rightBracketsHolder.Add(')');
Console.Write(expression[i] + " ");
}
else if (expression[i] == ']')
{
rightBracketsHolder.Add(']');
Console.Write(expression[i] + " ");
}
}
Console.WriteLine();
bool stackResult = checkValidity(expStack, rightBracketsHolder);
if (stackResult)
Console.WriteLine("Expression is Valid.");
else
Console.WriteLine("\nExpression is not valid.");
Console.ReadKey();
}
private static bool checkValidity(Stack<char> expStack, List<char> leftBracketsHolder)
{
Console.WriteLine();
int length = leftBracketsHolder.Count;
for (int i = 0; i < length; i++)
{
if (expStack.Peek().ToString().Contains(leftBracketsHolder.ToString()))
{
leftBracketsHolder.Remove(expStack.Peek());
expStack.Pop();
}
}
if (expStack.Count == 0 && leftBracketsHolder.Count ==0)
{
return true;
}
return false;
}
}
This code will solve your purpose -
static void Main(string[] args)
{
bool error = false;
var str = "( a[i]+{-1}*(8-9) )";
Stack<char> stack = new Stack<char>();
foreach (var item in str.ToCharArray())
{
if (item == '(' || item == '{' || item == '[')
{
stack.Push(item);
}
else if(item == ')' || item == '}' || item == ']')
{
if (stack.Peek() != GetComplementBracket(item))
{
error = true;
break;
}
}
}
if (error)
Console.WriteLine("Incorrect brackets");
else
Console.WriteLine("Brackets are fine");
Console.ReadLine();
}
private static char GetComplementBracket(char item)
{
switch (item)
{
case ')':
return '(';
case '}':
return '{';
case ']':
return '[';
default:
return ' ';
}
}
You need to pop things off the stack as the closing occurs. Try the following code. It will push an open brace/bracket/parenthesis on the stack and the first thing then it will be popped from the stack by a corresponding close. Otherwise it is invalid. If you have no opens on the stack when a close is encountered, it is invalid. If you have any extra opens when you are complete it is invalid.
I also used a switch statement instead of an if statement just because I thought it was easier to read.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string expression = "( a[i]+{-1}*(8-9) ) ";
bool stackResult = checkValidity(expression);
if (stackResult)
Console.WriteLine("Expression is Valid.");
else
Console.WriteLine("\nExpression is not valid.");
}
private static bool checkValidity(string expression)
{
Stack<char> openStack = new Stack<char>();
foreach (char c in expression)
{
switch (c)
{
case '{':
case '(':
case '[':
openStack.Push(c);
break;
case '}':
if (openStack.Count == 0 || openStack.Peek() != '{')
{
return false;
}
openStack.Pop();
break;
case ')':
if (openStack.Count == 0 || openStack.Peek() != '(')
{
return false;
}
openStack.Pop();
break;
case ']':
if (openStack.Count == 0 || openStack.Peek() != '[')
{
return false;
}
openStack.Pop();
break;
default:
break;
}
}
return openStack.Count == 0;
}
}

Hide password text

I have a textbox using UseSystemPasswordChar, so it will not display the password that the user enters. The issue is that the password is still able to be read by something like Spy++. I'm looking for a way to hide this like they do in the password fields in the Services.msc > Log On tab.
Here is what I've got so far.
You can improve this by having some unique events to indicate whether a pressed key has been accepted, if InputFilter or RealText has been changed, etc...
Another great thing to improve would be the default usage of InputFilter, because working with char and Keys doesn't really work for many special keys. For example - at the moment, if you press Alt+F4 when the PasswordBox is in focus, it will type in 's'... So there's a bag of bugs to fix.
And lastly, there's probably a more elegant way to handle capital vs non-capital letters input than what I did there.
So here it is:
public class PasswordBox : TextBox
{
private string _realText;
public string RealText
{
get { return this._realText; }
set
{
var i = this.SelectionStart;
this._realText = value ?? "";
this.Text = "";
this.Text = new string('*', this._realText.Length);
this.SelectionStart = i > this.Text.Length ? this.Text.Length : i;
}
}
private Func<KeyEventArgs, bool> _inputFilter;
public Func<KeyEventArgs, bool> InputFilter
{
get { return this._inputFilter; }
set { this._inputFilter = value ?? (e => true); }
}
public PasswordBox()
{
this.RealText = "";
this.InputFilter = e => "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".Any(c => c == e.KeyValue);
}
protected override void OnKeyDown(KeyEventArgs e)
{
e.SuppressKeyPress = true;
switch (e.KeyCode)
{
case Keys.Back:
if (this.SelectionStart > 0 || this.SelectionLength > 0)
{
this.RealText = this.SelectionLength == 0
? this.RealText.Remove(--this.SelectionStart, 1)
: this.RealText.Remove(this.SelectionStart, this.SelectionLength);
}
break;
case Keys.Delete:
if (this.SelectionStart == this.TextLength)
{
return;
}
this.RealText = this.RealText.Remove(this.SelectionStart, this.SelectionLength == 0 ? 1 : this.SelectionLength);
break;
case Keys.X:
case Keys.C:
case Keys.V:
if (e.Control)
{
return;
}
goto default;
case Keys.Right:
case Keys.Left:
case Keys.Up:
case Keys.Down:
case Keys.Shift:
case Keys.Home:
case Keys.End:
e.SuppressKeyPress = false;
base.OnKeyDown(e);
break;
default:
if (e.Control)
{
e.SuppressKeyPress = false;
base.OnKeyDown(e);
break;
}
if (this.InputFilter(e))
{
var c = (char)e.KeyValue;
if (e.Shift == IsKeyLocked(Keys.CapsLock))
{
c = char.ToLower(c);
}
this.RealText = this.RealText.Remove(this.SelectionStart, this.SelectionLength)
.Insert(this.SelectionStart, c.ToString());
this.SelectionStart++;
}
break;
}
}
}
So try something like this
private string realpass = "";
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (Char) Keys.Back)
realpass += realpass.Substring(0, realpass.Length - 2);
realpass += e.KeyChar.ToString();
textBox1.Text = "";
for (int i = 0; i < realpass.Length; i++)
textBox1.Text += "*";
}
You should not use your own dialog if you intend to collect Windows/domain user credentials. You should use what Windows provides via PInvoke or simply use a wrapper like this,
http://weblogs.asp.net/hernandl/archive/2005/11/21/usercredentialsdialog.aspx
and this,
http://credentials.codeplex.com/

Categories

Resources