How to enable GetAsyncKeyState using char? - c#

Good morning, I would like to "enable" the functions from GetAsyncKeyState from a button that is a char
ps. I am making a AutoClicker for game. (sorry for bad English xd)
example:
private void siticoneButton5_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 27)
{
siticoneButton5.Text = "Zbinduj";
keyRegisteringBool = false;
}
if (keyRegisteringBool)
{
siticoneButton5.Text = "Bind: " + e.KeyChar.ToString();
char bind = e.KeyChar;
keyRegisteringBool = false;
}
}
//here i have a void with a function
int min = Convert.ToInt32(materialSingleLineTextField1.Text);
int max = Convert.ToInt32(materialSingleLineTextField2.Text);
Random rand = new Random();
int cps = rand.Next(min, max);
while (true)
{
if (GetAsyncKeyState() < 0) //here I want to start this by key down a char.
{
bot.Mouse.LeftButtonClick();
Thread.Sleep(1000 / cps);
}
}
```
Thanks in advace

Related

How do I use a random number I generated in a separate sum

I'm a complete beginner and trying to create a Times Table game app that asks the user to input a number, generates a multiplication sum, and then checks if it's the write answer to deliver a congratulations message and then adds the score.
I've managed to generate the random number, but when I input the correct answer I get the Incorrect message which makes me think that the random number is not pulling through to the second button. Any help much appreciated!
Button 1
private void button1_Click(object sender, EventArgs e)
{
userInput = Convert.ToInt32(textBox1.Text);
if (userInput >= 1 && userInput <= 10)
{
Random rNum = new Random(); //uses built in function Random()
int rrNum = rNum.Next(1, 12); // creates a number between 1 and 12
label5.Text = (Convert.ToString(rrNum) + " x " + userInput);
}
}
Button 2
private void button2_Click(object sender, EventArgs e)
{
userAnswer = Convert.ToInt32(textBox2.Text);
Random rNum = new Random();
int rrNum = rNum.Next(1, 12);
if (userAnswer == userInput * rrNum)
{
label8.Text = "Congratulations!";
pictureBox1.Enabled = true;
pictureBox1.Visible = true;
}
else
{
label8.Text = ("Incorrect, try again!");
}
}

How to add space between bytes in textbox?

I have one textbox which gets only bytes and I want to add space between every bytes.
What I have done so far?
public int a=0;
public char c;
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
c = e.KeyChar;
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
a = textBox2.TextLength % 3;
if (c != 0x08 && a==2)
{
a = textBox2.TextLength % 3;
int selectionIndex = textBox2.SelectionStart;
textBox2.Text = textBox2.Text.Insert(selectionIndex, " ");
textBox2.SelectionStart = selectionIndex + 1; // restore cursor position
}
}
I add space with this code but if I delete some bytes it doesn't add space.
I think there is some issue in 'if' condition.
For example I write 'abcdef' it adds space and write
ab cd ef
then I delete 'cdef' and space it works properly in here.
I write again 'cdef' it doesn't work and result will be like that
abcde f
How can I fix this issue?
I solve the problem with this code.
private void textBox5_TextChanged(object sender, EventArgs e)
{
int selectionIndex = textBox5.SelectionStart;
int chars = textBox5.Text.Length;
int a = chars % 3;
if (a == 2 && c!=0x08)
{
textBox5.Text = textBox5.Text.Insert(selectionIndex, " ");
textBox5.SelectionStart = selectionIndex + 1; // restore cursor position
}
if (chars > 1)
{
if (a == 0 && c == 0x08)
{
textBox5.Text = textBox5.Text.Remove(chars - 1);
textBox5.SelectionStart = selectionIndex + 1;
}
}
}

Hint system to tell a random false selection

I'm making a c# windows form application in which there are five buttons each corresponding to a number 1-5 and the user guesses a random number out of those. I need to implement a hint which would tell the user a random false selection. How would I do this?
public partial class frmGuessANumber : Form
{
int number;
public frmGuessANumber()
{
InitializeComponent();
Random rnd = new Random();
number = rnd.Next(1, 6);
}
private void SelectionMade(object sender, EventArgs e)
{
Button selection = (Button)sender;
int guess = Convert.ToInt32(selection.Text);
if (guess == number)
{
DisableButtons();
lblMessage.Text = "Congratulations! " + guess + " is correct!";
lblMessage.Visible = true;
}
else
{
DisableButtons();
lblMessage.Text = "Sorry! " + guess + " isn't the right answer.";
lblMessage.Visible = true;
}
}
private void lblHint_MouseHover(object sender, EventArgs e)
{
Random rnd = new Random();
int wrongSelection = rnd.Next(2, 6);
if (number == 1)
lblHint.Text = "The number is not " + wrongSelection;
else
lblHint.Text = "The number is not " + (number - 1);
}
private void DisableButtons()
{
btnGuess1.Enabled = false;
btnGuess2.Enabled = false;
btnGuess3.Enabled = false;
btnGuess4.Enabled = false;
btnGuess5.Enabled = false;
}
}
You could
1) enumerate the possible numbers using Enumerable.Range
2) then take all except the correct solution (in your case number). You can use the Where method
3) then you would randomly pick a number from this set as a hint. You can use the ElementAt method
Random rnd = new Random();
int CorrectAnswer = rnd.Next(1, 6);
int hint = Enumerable.Range(1,6).Where(x=>x != CorrectAnswer ).ElementAt(rnd.Next(1,5));
Since the user has been deleted, I will just leave the answer for future people with a similar problem:

C# BlackJack - same card dealt to player & cpu? [closed]

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 8 years ago.
Improve this question
i'm working on a little black jack game for no apparent reason, and I've run into an issue and i can't figure out where i'm going wrong, the only thing i can imagine is that the 'new card' method is being called twice, too quickly...
The problem is that it's giving the same card to both players :/
Here is my code
Thank you! :)
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 BlackJack_Reworked
{
public partial class BlackJack : Form
{
public BlackJack()
{
InitializeComponent();
}
class myVars
{
public static int cardsDrawn = 0;
public static int playerX = 230;
public static int playerY = 160;
public static int cpuX = 230;
public static int cpuY = 60;
public static int playerCardValue = 0;
public static int cpuCardValue = 0;
}
private PictureBox[] card = new PictureBox[100];
private void makeCard(string pickedCard, int x)
{
card[myVars.cardsDrawn] = new PictureBox();
if (x == 0)
{
card[myVars.cardsDrawn].Location = new Point(myVars.playerX, myVars.playerY);
myVars.playerX += 15;
}
if (x == 1)
{
card[myVars.cardsDrawn].Location = new Point(myVars.cpuX, myVars.cpuY);
myVars.cpuX += 15;
}
card[myVars.cardsDrawn].Image = (Image)Properties.Resources.ResourceManager.GetObject(pickedCard);
card[myVars.cardsDrawn].Size = new Size(72, 96);
card[myVars.cardsDrawn].Parent = this;
card[myVars.cardsDrawn].BringToFront();
card[myVars.cardsDrawn].Update();
myVars.cardsDrawn++;
checkScores(false);
}
private void newCard(int x)
{
Random cardPicker = new Random();
int cardChoice = cardPicker.Next(1, 13);
int houseChoice = cardPicker.Next(1, 4);
string house = null;
switch (houseChoice)
{
case 1:
house = "Hearts";
break;
case 2:
house = "Diamonds";
break;
case 3:
house = "Spades";
break;
case 4:
house = "Clubs";
break;
}
if (x == 0)
{
makeCard(house + Convert.ToString(cardChoice), 0);
myVars.playerCardValue += cardChoice;
}
if (x == 1)
{
makeCard(house + Convert.ToString(cardChoice), 1);
myVars.cpuCardValue += cardChoice;
}
}
private bool feelingLucky()
{
Random Dice = new Random();
if (myVars.cpuCardValue >= 20) { return false; }
if (myVars.cpuCardValue <= 16) { return true; }
if (myVars.cpuCardValue >= 17 && myVars.cpuCardValue <= 18) if (Dice.Next(1, 5) == 1) { return true; }
if (myVars.cpuCardValue == 19) if (Dice.Next(1, 10) == 1) { return true; }
return false;
}
private void updateHandValues()
{
lblPlayerHand.Text = "Player: " + myVars.playerCardValue.ToString();
lblCPUhand.Text = "CPU: " + myVars.cpuCardValue.ToString();
}
private void checkScores(bool stand)
{
if (stand == true)
{
if (myVars.playerCardValue <= 21 && myVars.playerCardValue > myVars.cpuCardValue)
{
MessageBox.Show("Win!");
btnNewGame.Visible = true;
}
else if (myVars.cpuCardValue <= 21 && myVars.cpuCardValue > myVars.playerCardValue)
{
btnNewGame.Visible = true;
MessageBox.Show("Lose!");
}
}
else
{
if (myVars.playerCardValue > 21)
{
MessageBox.Show("Bust!");
btnNewGame.Visible = true;
}
if (myVars.cpuCardValue > 21)
{
MessageBox.Show("Win!");
btnNewGame.Visible = true;
}
}
}
private void newGame()
{
for(int x = 0; x < myVars.cardsDrawn; x++) { card[x].Dispose(); }
myVars.cpuCardValue = 0;
myVars.playerCardValue = 0;
myVars.cpuX = 230;
myVars.playerX = 230;
btnNewGame.Visible = false;
newCard(0); newCard(1);
}
private void btnNewGame_Click(object sender, EventArgs e)
{
newGame();
}
private void btnHit_Click(object sender, EventArgs e)
{
newCard(0); newCard(1);
updateHandValues();
}
private void btnStand_Click(object sender, EventArgs e)
{
if (feelingLucky() == true) newCard(1);
else checkScores(true);
}
}
}
EDIT Here's the code to my new and working version with help from these nice guys below, just in case someone finds it useful, thanks everyone!
Here are the card picture files you'll need to add to your project's resources for this code to work.
I know my logic probably isn't great, but i feel like I've learnt from this little project, hopefully someone else might too, now, time to conjure up something new.. thanks stackoverflow.
Playing Card Pictures Download
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Text.RegularExpressions;
namespace BlackJack_Reworked
{
public partial class BlackJack : Form
{
public BlackJack()
{
InitializeComponent();
}
private PictureBox[] Card = new PictureBox[52];
static List<string> Deck = new List<string>();
class myVars
{
public static int playerX = 230;
public static int cpuX = 230;
public static int playerCardValue = 0;
public static int cpuCardValue = 0;
public static int cardsDrawn = 0;
}
private void newDeck()
{
Deck.Clear();
for (int x = 0; x < myVars.cardsDrawn; x++)
{
Card[x].Dispose();
}
for (int x = 0; x < 52; x++)
{
int cardSuite = (x / 13) + 1;
int faceValue = (x % 13) + 1;
string Suite = null;
switch (cardSuite)
{
case 1:
Suite = "Hearts";
break;
case 2:
Suite = "Diamonds";
break;
case 3:
Suite = "Spades";
break;
case 4:
Suite = "Clubs";
break;
}
Deck.Add(Suite + Convert.ToString(faceValue));
}
Extensions.Shuffle(Deck);
myVars.cardsDrawn = myVars.cpuCardValue = myVars.playerCardValue = 0;
myVars.cpuX = myVars.playerX = 230;
}
private void handCard(string recipient)
{
Random Random = new Random(); Extensions.Shuffle(Deck);
string pickedCard = Deck[Random.Next(Deck.Count)];
int cardvalue = Convert.ToInt32(Regex.Replace(pickedCard, "[^0-9]", ""));
Card[myVars.cardsDrawn] = new PictureBox();
if (recipient == "player") {
Card[myVars.cardsDrawn].Location = new Point(myVars.playerX, 160); myVars.playerX += 15;
myVars.playerCardValue += cardvalue;
}
if (recipient == "cpu") {
Card[myVars.cardsDrawn].Location = new Point(myVars.cpuX, 60); myVars.cpuX += 15;
myVars.cpuCardValue += cardvalue;
}
Card[myVars.cardsDrawn].Image = (Image)Properties.Resources.ResourceManager.GetObject(pickedCard);
Card[myVars.cardsDrawn].Size = new Size(72, 96);
Card[myVars.cardsDrawn].Parent = this;
Card[myVars.cardsDrawn].BringToFront();
Card[myVars.cardsDrawn].Update();
Deck.Remove(pickedCard); myVars.cardsDrawn++; updateHandValues();
}
private void updateHandValues()
{
lblPlayerHand.Text = "Player: " + myVars.playerCardValue.ToString();
lblCPUhand.Text = "CPU: " + myVars.cpuCardValue.ToString();
}
private void newGame()
{
lblBlackJack.Text = "♠ Blackjack ♥";
btnNewGame.Visible = false;
newDeck(); handCard("player"); handCard("cpu");
}
private void checkCards()
{
if (playerWins() == true)
{
lblBlackJack.Text = "♠ You Win! ♥";
btnNewGame.Visible = true;
}
else if (playerWins() == false)
{
lblBlackJack.Text = "♠ Dealer Wins! ♥";
btnNewGame.Visible = true;
}
}
private void tieBreak()
{
if (myVars.cpuCardValue == myVars.playerCardValue && myVars.cpuCardValue >= 17)
{
lblBlackJack.Text = "♠ Tie! ♥";
btnNewGame.Visible = true;
}
else { checkCards(); }
}
private bool? playerWins()
{
if(myVars.cpuCardValue == 21 || myVars.playerCardValue > 21) { return false; }
if(myVars.playerCardValue == 21 || myVars.cpuCardValue > 21) { return true; }
else { return null; }
}
private bool cpuShouldPlay(bool stand)
{
Random Dice = new Random();
if (stand == false)
{
if (myVars.cpuCardValue <= 15) { return true; }
if (myVars.cpuCardValue >= 20 && myVars.cpuCardValue <= 21 && myVars.cpuCardValue > myVars.playerCardValue) { return false; }
if (myVars.cpuCardValue == 19 && myVars.cpuCardValue < myVars.playerCardValue) { return true; } else { return false; }
}
else
{
if(myVars.cpuCardValue < myVars.playerCardValue)
{
return true;
}
else { return false; }
}
}
private void btnNewGame_Click(object sender, EventArgs e)
{
newGame();
}
private void btnHit_Click(object sender, EventArgs e)
{
handCard("player"); if(cpuShouldPlay(false) == true) handCard("cpu"); checkCards();
}
private void btnStand_Click(object sender, EventArgs e)
{
if (cpuShouldPlay(true) == true) handCard("cpu"); tieBreak();
}
}
public static class Extensions
{
public static void Shuffle<T>(this IList<T> list)
{
Random rng = new Random();
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
}
If you're playing from single deck rules, you must use a 'bag' or 'no replacement' model of random value source. Initially , fill the bag with all 52 possible cards. Then each iteration, pick one card at random from what remains in the bag, removing it from the bag. When the bag is empty, refill it.
Do note that when picking a random card from a bag that has n remaining items, your random value, being the index of the item in the bag to take, must be no larger than n-1 (assuming indicies run from 0 to n-1).
However, there are models of blackjack where multiple decks are shuffled together; many casinos play like this. From Wikipedia Blackjack, rules of play at casinos:
At a casino blackjack table, the dealer faces five to seven playing positions from behind a semicircular table. Between one and eight standard 52-card decks are shuffled together.
In this above model, it is certainly possible for the same card to be dealt twice in a row; however, depending on how many decks are shuffled together, this can happen only a limited number of times.
If I understand your code correctly, you currently model a blackjack shoe that has an infinite number of decks shuffled together.
Random.Next method generates random number from current time stamp and previously generated number (known as 'seed'). As you are create new object of Random everytime, it initializes with same seed. In your case, timestamp and seed doesn't change to 'Next' method of Random.
If you use single object of Random for all your operation, seed will change for each call of 'next'.
Second: You need to keep track of which cards are already drawn, so I've create a shoe list. I will remove the cards which are already used, just like real table.
NOTE: create a new shoe, when your number of cards are let's say 20.
List<string> aShoe = new List<string>(); //shoe contains 4 to 8 decks. Depending upon blackjack version.
int numberOfDeckPerShoe = 4;
private void CreateNewDeck()
{
for(int i =0;i <numberOfDeckPerShoe;i++)
for(int j=0;j<52;j++)
{
int cardFace = (j%13)+1;
int cardSuite = (j/13) + 1;
string Suite = null;
switch (cardSuite)
{
case 1:
Suite = "Hearts";
break;
case 2:
Suite = "Diamonds";
break;
case 3:
Suite = "Spades";
break;
case 4:
Suite = "Clubs";
break;
}
aShoe.add(Suite + Convert.ToString(cardFace));
}
}
Random cardPicker = new Random(); //This is change
private void newCard(int x)
{
int cardChoice = 0;
int houseChoice = 0;
string cardDrawn = "";
int cardToDraow = cardPicker.Next(0,aShoe.length);
cardDrawn = card aShoe[cardToDraow];
card.removeAt(cardToDraow);
if (x == 0)
{
makeCard(cardDrawn, 0);
myVars.playerCardValue += cardChoice;
}
if (x == 1)
{
makeCard(cardDrawn, 1);
myVars.cpuCardValue += cardChoice;
}
}
You are declaring a new Random() within the new card method.
If the method is being called twice, and very quickly, the seed's that are automatically generated (Based on time I believe) will be so close that they will generate pretty much the same number.
The best thing to do would be to create your instance of random outside of the method, and pass the random in each time, that way you will not get the same number each call.

variable doesn't increment/decrement on my code

if (getchar == '+') {
answer = getnum1+getnum2; // if the random operation is add, it will add
addtemp++; // <---- disregard this
if (answer == getanswer) // the answer from my textbox which is
{ // user-input it is stored on "getanswer"
correct++; // it is compared if its correct or wrong
addcomp++;
}
else { wrong++; }
}
else if (getchar == '-') {
subtemp++;
answer = nextValue - nextValue1;
if (answer == getanswer) {
correct++;
subcomp++;
}
else { wrong++; }
}
else if (getchar == '*') {
multemp++;
answer = nextValue * nextValue1;
if (answer == getanswer) {
correct++;
mulcomp++;
}
else { wrong++; }
}
else if (getchar == '/') {
divtemp++;
answer = nextValue / nextValue1;
if (answer == getanswer) {
correct++;
divcomp++;
}
else { wrong++; }
}
else if (getchar == '%') {
modtemp++;
answer = nextValue % nextValue1;
if (answer == getanswer) {
correct++;
modcomp++;
}
else { wrong++; }
}
C# programming HELP! Now whenever i press the button "SCORES" it is a MessageBox.Show(correct or wrong) , the values are wrong. it sometimes increment corrected but just once or twice.Is there something wrong with my code?
///////////////////////////////////////////////////////////
ENTIRE CODE for #boncodigo
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 A1_ALS_Noroña
{
public partial class Form1 : Form
{
int minV=0, maxV=0,ques=0,tempques=1;
int addtemp, subtemp, multemp, divtemp, modtemp;
int addcomp, subcomp, mulcomp, divcomp, modcomp;
int answer,getanswer;
int getnum1, getnum2;
char getchar;
char[] select = new char[5];
int count=0;
int correct, wrong;
public Form1()
{
InitializeComponent();
}
private void bttnstart_Click(object sender, EventArgs e)
{
bttnanswer.Enabled = true;
grpbox1.Enabled = false;
bttnanswer.Enabled = true;
lblnum1.Visible = true;
lblnum2.Visible = true;
lbloperator.Visible = true;
bttnstop.Enabled = true;
bttnscore.Enabled = true;
bttnstart.Enabled = false;
Random random = new Random();
int nextValue = random.Next(minV, maxV);
int nextValue1 = random.Next(minV, maxV);
lblnum1.Text = nextValue.ToString();
lblnum2.Text = nextValue1.ToString();
var rand = new Random();
char num = select[rand.Next(count)];
lbloperator.Text = Convert.ToString(num);
}
private void txtboxmin_TextChanged(object sender, EventArgs e)
{
minV = Convert.ToInt32(txtboxmin.Text);
}
private void txtbxmax_TextChanged(object sender, EventArgs e)
{
maxV = Convert.ToInt32(txtbxmax.Text);
}
private void bttnexit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void bttnstop_Click(object sender, EventArgs e)
{
MessageBox.Show("APPLICATION STOP! The application will restart.");
Application.Restart();
}
private void bttnanswer_Click(object sender, EventArgs e)
{
tempques++;
Random random = new Random();
int nextValue = random.Next(minV,maxV);
int nextValue1 = random.Next(minV, maxV);
lblnum1.Text = nextValue.ToString();
var rand = new Random();
char num = select[rand.Next(count)];
lbloperator.Text = Convert.ToString(num);
lblnum2.Text = nextValue1.ToString();
getnum1 = Convert.ToInt32(lblnum1.Text);
getnum2 = Convert.ToInt32(lblnum2.Text);
getanswer = Convert.ToInt32(txtbxans.Text);
getchar = Convert.ToChar(lbloperator.Text);
if (getchar == '+')
{
answer = getnum1 + getnum2;
addtemp++;
if (answer == getanswer)
{
correct++;
addcomp++;
}
else
{
wrong++;
}
}
else if (getchar == '-')
{
subtemp++;
answer = nextValue - nextValue1;
if (answer == getanswer)
{
correct++;
subcomp++;
}
else
{
wrong++;
}
}
else if (getchar == '*')
{
multemp++;
answer = nextValue * nextValue1;
if (answer == getanswer)
{
correct++;
mulcomp++;
}
else
{
wrong++;
}
}
else if (getchar == '/')
{
divtemp++;
answer = nextValue / nextValue1;
if (answer == getanswer)
{
correct++;
divcomp++;
}
else
{
wrong++;
}
}
else if (getchar == '%')
{
modtemp++;
answer = nextValue % nextValue1;
if (answer == getanswer)
{
correct++;
modcomp++;
}
else
{
wrong++;
}
}
}
private void txtbxques_TextChanged(object sender, EventArgs e)
{
ques = Convert.ToInt32(txtbxques.Text);
}
private void chkbxtimer_CheckedChanged(object sender, EventArgs e)
{
rdoeasy.Enabled = true;
rdomed.Enabled = true;
rdohard.Enabled = true;
}
private void chkboxAdd_CheckedChanged(object sender, EventArgs e)
{
if (chkboxAdd.Checked == true)
{
select[count] = '+';
count++;
}
else if (chkboxAdd.Checked == false)
{
Array.Clear(select, 0, select.Length);
count--;
}
}
private void chkboxSub_CheckedChanged(object sender, EventArgs e)
{
if (chkboxSub.Checked == true)
{
select[count] = '-';
count++;
}
else if (chkboxSub.Checked == false)
{
Array.Clear(select, 0, select.Length);
count--;
}
}
private void chkboxMul_CheckedChanged(object sender, EventArgs e)
{
if (chkboxMul.Checked == true)
{
select[count] = '*';
count++;
}
else if (chkboxMul.Checked == false)
{
Array.Clear(select, 0, select.Length);
count--;
}
}
private void chkboxDiv_CheckedChanged(object sender, EventArgs e)
{
if (chkboxDiv.Checked == true)
{
select[count] = '/';
count++;
}
else if (chkboxDiv.Checked == false)
{
Array.Clear(select, 0, select.Length);
count--;
}
}
private void chkboxMod_CheckedChanged(object sender, EventArgs e)
{
if (chkboxMod.Checked == true)
{
select[count] = '%';
count++;
}
else if (chkboxMod.Checked == false)
{
Array.Clear(select, 0, select.Length);
count--;
}
}
private void bttnscore_Click(object sender, EventArgs e)
{
MessageBox.Show("Correct Answer"+correct);
}
}
}
One thing in advance: I don't know where your bug is. Here's just a couple of tips that I think it would make sense if you think about them, in order to avoid similar bugs in the future:
If I had to review this code, my major issue would be with the amount of repeating code, where very similar multi-line long patterns are copied over and over. I think in the whole code you don't call any method, but implement stuff right away in the event-handlers, thereby repeating yourself and multiplying the potential for bugs. Let's look at this code:
if (chkboxSub.Checked == true)
{
select[count] = '-';
count++;
}
else if (chkboxSub.Checked == false)
{
Array.Clear(select, 0, select.Length);
count--;
}
apart from the bug with count when you have added several operators to the select-array, this code repeats several times. Let's extract the code into a method and make the bits that change parameterizable:
void AddOrRemoveOperator(bool isChecked, char operatorChar) {
if (isChecked) {
select[count] = operatorChar;
count++;
}
else {
Array.Clear(select, 0, select.Length);
count--;
}
}
Now you can call that method many times, e.g. like:
AddOrRemoveOperator(chkboxSub.Checked, '-');
Next point would be lack of .NET Base Class Library knowledge (BCL). E.g., wouldn't it be easier to use a List<T> instead of an array?
The above method becomes:
void AddOrRemoveOperator(bool isChecked, char operatorChar) {
if (isChecked) {
select.Add(operatorChar);
}
else {
select.Clear();
}
}
An Observation: All operators except the add one use the values nextValue, nextValue1 while the add one uses getnum1 and 2. Is that intended?
Short of extracting the code blocks in bttnanswer_Click into their own class, you can also extract the repeating code into a method:
void PerformComparison(Func<int> answerProvider,
ref int operatorCount,
ref int operatorSpecificCorrectCount)
{
var answer = answerProvider();
operatorCount++;
if (answer == getanswer) {
correct++;
operatorSpecificCorrectCount++;
}
else {
wrong++;
}
}
That code would still drive me mad (because the class you have programmed lacks cohesion), but we have fought code duplication. Now you can call the method e.g. like that:
if (getchar == '+')
{
PerformComparison(()=>getnum1 + getnum2, ref addtemp, ref addcomp);
}
There are many techniques to morph code into forms that are more easily testable and maintainable (refactoring), we have only used extract method so far. For more techniques the book Refactoring: Improving the Design of Existing Code is still highly recommendable.
It might be a float precision issue (maybe your user is entering 3 and the program calculates 2.9999999). Debug your code and identify one case when it is not adding correctly.

Categories