In a math game that I programming, my Windows Form has labels in it where the numbers appear for the sum.
When I click button1, they should change to other numbers, but they don't. The labels that should change are called lblNumber1 and lblNumber2.
Here is my code:
public partial class plussommen : Form
{
int counter = 0;
int correct = 0;
int incorrect = 0;
Random rand = new Random();
int number1, number2;
int answer;
string sum;
public plussommen()
{
InitializeComponent();
number1 = rand.Next(1, 50);
number2 = rand.Next(1, 50);
sum = number1 + " + " + number2 + " = ";
answer = number1 + number2;
}
private void plussommen_Load(object sender, EventArgs e)
{
if (counter < 5)
{
lblNumber1.Text = number1.ToString();
lblNumber2.Text = number2.ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
lblCorrect.Text = correct.ToString();
lblIncorrect.Text = incorrect.ToString();
if (textBox1.Text == answer.ToString())
{
MessageBox.Show("Answer correct!");
correct = correct + 1;
}
else
{
MessageBox.Show("Answer incorrect!");
incorrect = incorrect + 1;
}
if (counter < 5)
{
lblNumber1.Text = number1.ToString();
lblNumber2.Text = number2.ToString();
}
else
{
if (counter == 5)
{
MessageBox.Show("You've made five sums, choose another kind of sum.");
this.Close();
Form1 menu = new Form1();
menu.Show();
}
}
}
}
To change the value on the labels on every click, you need to generate new random numbers each time.
if (counter < 5)
{
number1 = rand.Next(1, 50);
number2 = rand.Next(1, 50);
lblNumber1.Text = number1.ToString();
lblNumber2.Text = number2.ToString();
}
In your code, you are not changing the values of number1 and number2 at any time after initialization. This is why they are not updating after every button click.
What you need to do is update the numbers and the answer after every click:
private void button1_Click(object sender, EventArgs e)
{
//...
if (counter < 5)
{
number1 = rand.Next(1, 50);
number2 = rand.Next(1, 50);
answer = number1 + number2;
lblNumber1.Text = number1.ToString();
lblNumber2.Text = number2.ToString();
}
//...
}
Related
can anyone help me please,,
i'm trying to display my array elements into textbox and listview
the listview works but the textbox shows my int 6 time, here is my code:
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ArrayList numbers = new ArrayList();
int[] myNumbers = new int[6];
Random rnd = new Random();
int randomNumber;
for (int i = 0; i < 6; i++)
{
do
{
randomNumber = rnd.Next(1, 49);
}
while (numbers.Contains(randomNumber));
numbers.Add(randomNumber);
}
numbers.Sort();
numbers.CopyTo(myNumbers);
//listView1.Items.Add(myNumbers.ToString);
foreach (int j in myNumbers)
{
listView1.Items.Add(j.ToString());
label1.Text += j.ToString();
int num1 = myNumbers[0];
int num2 = myNumbers[1];
int num3 = myNumbers[2];
int num4 = myNumbers[3];
int num5 = myNumbers[4];
int num6 = myNumbers[5];
textBox1.Text += num1;
textBox2.Text += num2;
textBox3.Text += num3;
textBox4.Text += num4;
textBox5.Text += num5;
textBox6.Text += num6;
}
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
textBox6.Text = "";
listView1.Clear();
label1.Text = "";
}
}
}
can anyone help me and tell me where am i going wrong?
You should do
textBox1.Text = num1;
not
textBox1.Text += num1;
Edit: You don't need loop...
you're setting the texts within the loop. So you're setting the values six times, which you can see because you're appending with +=. You could move this whole block to just after numbers.CopyTo(myNumbers); so each value is only set once. Also there's no need for +=.
int num1 = myNumbers[0];
int num2 = myNumbers[1];
int num3 = myNumbers[2];
int num4 = myNumbers[3];
int num5 = myNumbers[4];
int num6 = myNumbers[5];
textBox1.Text = num1.ToString();
textBox2.Text = num2.ToString();
textBox3.Text = num3.ToString();
textBox4.Text = num4.ToString();
textBox5.Text = num5.ToString();
textBox6.Text = num6.ToString();
There were few issue in your code.
You don't need both ArrayList numbers and int[] myNumbers, you can access List by index too.
You use so much magic number : 6, 1, 49. They could be replace with variable.
Before adding value to a listView, you can clear it. You don't have to foreach loop on myNumbers you can direcly add them with AddRange method.
The result of label1.Text+=j.ToString() is a bit undreadable as all numbers glued together resulting in a 123564132321.
tbResult.Text = string.Join(", ", numbers); will join then with a nice ", " as separator.
Finaly, if you you don't want to copy past N time the same line for textbox.text initialisation. You can find all the textbox that match a pattern.
var numbers = new List<int>();
while (numbers.Count < userInput)
{
var tempRnd = rnd.Next(lowerBound, upperBound);
if (!numbers.Contains(tempRnd))
{
numbers.Add(tempRnd);
}
}
numbers.Sort();
listView1.Items.Clear();
listView1.Items.AddRange(numbers.Select(x => new ListViewItem { Text = x.ToString() }).ToArray());
tbResult.Text = string.Join(", ", numbers);
int i = 0;
foreach (TextBox tb in this.Controls.OfType<TextBox>().Where(l => l.Name.StartsWith("GeneratedTB_")))
{
tb.Text = numbers[i].ToString();
i++;
}
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'm trying to make a dice game but I'm having problems with my dice variables and keeping track of the score for the current round.
Basically, there are four dice, and the round score is the total of the dice added together (you have a certain amount of rerolls per round).
But when I try to use the game, the round score is only showing one die's number, whichever one was most recently rolled (clicked).
Here is my code:
namespace DiceGame
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
int die1;
int die2;
int die3;
int die4;
int rollsRemaining = 6;
int scoreRound;
int scoreTotal;
int numberRound;
Random random;
Random rnd = new Random();
public MainWindow()
{
InitializeComponent();
Random random = new Random();
int die1 = random.Next(1, 7);
int die2 = random.Next(1, 7);
int die3 = random.Next(1, 7);
int die4 = random.Next(1, 7);
dieOne.Content = die1;
dieTwo.Content = die2;
dieThree.Content = die3;
dieFour.Content = die4;
int scoreRound = die1 + die2 + die3 + die4;
roundScore.Text = "Round Score: " + scoreRound;
}
private void dieOne_Click(object sender, RoutedEventArgs e)
{
Random random = new Random();
if (rollsRemaining != 0)
{
int die1 = random.Next(1, 7);
dieOne.Content = die1;
rollsRemaining = rollsRemaining - 1;
string string1 = rollsRemaining.ToString();
rollsLeft.Text = "Rolls Left: " + string1;
roundScore.Text = "Round Score: " + (die1 + die2 + die3 +die4);
}
else
{ }
}
private void dieTwo_Click(object sender, RoutedEventArgs e)
{
Random random = new Random();
if (rollsRemaining != 0)
{
int die2 = random.Next(1, 7);
dieTwo.Content = die2;
rollsRemaining = rollsRemaining - 1;
string string1 = rollsRemaining.ToString();
rollsLeft.Text = "Rolls Left: " + string1;
roundScore.Text = "Round Score: " + (die1 + die2 + die3 + die4);
}
else
{ }
}
private void dieThree_Click(object sender, RoutedEventArgs e)
{
Random random = new Random();
if (rollsRemaining != 0)
{
int die3 = random.Next(1, 7);
dieThree.Content = die3;
rollsRemaining = rollsRemaining - 1;
string string1 = rollsRemaining.ToString();
rollsLeft.Text = "Rolls Left: " + string1;
roundScore.Text = "Round Score: " + (die1 + die2 + die3 + die4);
}
else
{ }
}
private void dieFour_Click(object sender, RoutedEventArgs e)
{
Random random = new Random();
if (rollsRemaining != 0)
{
int die4 = random.Next(1, 7);
dieFour.Content = die4;
rollsRemaining = rollsRemaining - 1;
string string1 = rollsRemaining.ToString();
rollsLeft.Text = "Rolls Left: " + string1;
roundScore.Text = "Round Score: " + (die1 + die2 + die3 + die4);
}
else
{ }
}
private void newRound_Click(object sender, RoutedEventArgs e)
{
scoreTotal = scoreTotal + scoreRound;
totalScore.Text = "Total Score: " + scoreTotal;
rollsRemaining = 6;
rollsLeft.Text = "Rolls Left: " + rollsRemaining;
scoreRound = 0;
roundScore.Text = "Round Score: " + scoreRound;
Random random = new Random();
int die1 = random.Next(1, 7);
int die2 = random.Next(1, 7);
int die3 = random.Next(1, 7);
int die4 = random.Next(1, 7);
dieOne.Content = die1;
dieTwo.Content = die2;
dieThree.Content = die3;
dieFour.Content = die4;
}
}
}
you have local variables for the dices in your methods (die1, die2...) and also class data members with the same names (die1, die2...)
when you use a variable, first the compiler looks in the current scope (here it's your method) and only then searches in the outer scope (the class).
you initialized the numbers in the scope of the constructure with local variables so the data members are still 0.
when clicking a button you set another local variable (say die1) with a value and then add it up with the rest. so now die1 (the local) is added with die2,3,4 the data members (and they are 0). so you get just die1. same in the other buttons.
learn more about scopes here:
https://msdn.microsoft.com/en-us/library/ms973875.aspx
just for this case - remove the local variables and use only the data members.
public MainWindow()
{
InitializeComponent();
Random random = new Random();
die1 = random.Next(1, 7);
die2 = random.Next(1, 7);
die3 = random.Next(1, 7);
die4 = random.Next(1, 7);
//...
}
And similarily in newRound_Click
I'm trying to display 5 scores in an array, but unfortunately all I get in the message box for the results is 0.
Any help would be appreciated.
public partial class Form1 : Form
{
private int[] scoresArray = new int[5];
private int scoreTotal = 0;
private int scoreCount = 0;
public Form1()
{
InitializeComponent();
}
when the add button is clicked the scores are stored in the array up to 5 times.
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (txtScore.Text == "")
{
MessageBox.Show("Score is required", "Entry Error");
}
else
{
int score = Convert.ToInt32(txtScore.Text);
decimal average = 0;
if (score >= 0 && score <= 100)
{
if (scoreCount != 4)
{
scoreTotal += score;
scoresArray[scoreCount] = score;
scoreCount++;
average = scoreTotal / scoreCount;
}
else
{
MessageBox.Show("Array is full");
}
txtScoreTotal.Text = scoreTotal.ToString();
txtScoreCount.Text = (scoreCount + 1).ToString();
txtAverage.Text = average.ToString();
}
else
{
MessageBox.Show("Score must be greater than 0 and less than or equal to 100.", "Entry Error");
}
}
}
catch (FormatException)
{
MessageBox.Show("Please enter a valid number for the Score field.", "Entry Error");
}
txtScore.Focus();
}
private void btnDisplayScores_Click(object sender, EventArgs e)
{
string message = "";
for (int i = 0; i < scoresArray.Length; i++)
{
message = scoresArray[i].ToString() + "\n";
}
MessageBox.Show(message, "Scores");
}
You keep overwriting message in this loop:
for (int i = 0; i < scoresArray.Length; i++)
{
message = scoresArray[i].ToString() + "\n";
}
So it's only ever going to show the last value. You probably want to append to it instead:
for (int i = 0; i < scoresArray.Length; i++)
{
message += scoresArray[i].ToString() + "\n";
}
Hi so I'm just making a little tiny quiz and I was just wondering how I would calculate my score from the selected results in a combo box. I tried this and to test to see what my answer was I just displayed a messagebox, but the answer always turns out to be 0.
private void Button1_Click(object sender, EventArgs e)
{
if (ComboBox7.SelectedIndex == 2) //1
{
score1 = 1;
}
else
{
score1 = 0;
}
if (ComboBox8.SelectedIndex == 1) //2
{
score2 = 1;
}
else
{
score2 = 0;
}
if (ComboBox9.SelectedIndex == 2) //3
{
score3 = 1;
}
else
{
score3 = 0;
}
if (ComboBox10.SelectedIndex == 0) //4
{
score4 = 1;
}
else
{
score4 = 0;
}
if (ComboBox11.SelectedIndex == 0) //5
{
score5 = 1;
}
else
{
score5 = 0;
}
int scores;
int finalgrade;
scores = score1 + score2 + score3 + score4 + score5;
finalgrade = scores / 6;
MessageBox.Show(finalgrade.ToString());
}
If anyone could help me it'd be greatly appreciated.
The max score can be is 5, and since this is smaller than 6. 5/6 will always be 0 in integer division.
I'm trying to design a code where one guess a number. I defined the range which number to display in my listbox. I started to write Random(1,10) but if I enter 11, it still writes in my listbox. How can I just write the number selected from my range, which is 1-10?
Here is a part of my code:
private void btnOk_Click(object sender, EventArgs e)
{
string yourNumber;
yourNumber = textBox1.Text.Trim();
int returnNumber = RandomNumber(1, 10);
int.TryParse(textBox1.Text, out returnNumber);
listBox1.Items.Add(returnNumber);
}
Additional question
If I would like to display a range of number like for example 1-10, how could I do the following? The user will type 11 the program will not accept that.
I made something like this:
int returnNumber = RandomNumber(1, 10);
string yourNumber;
yourNumber = textBox1.Text.Trim();
if(Int32.TryParse(textBox1.Text>=1)) && (Int32.TryParse(textBox1.Text<=10));
{
listBox1.Items.Add(yourNumber);
textBox1.Text = string.Empty;
}
Something is wrong in the program.
Update
For Nathaniel, I tried this one:
int returnNumber=RandomNumber(1,10);
int counter=1;
int yourNumber;
Int32.TryParse(textBox1.Text.Trim(), out yourNumber);
if (yourNumber >=1 && yourNumber <= 10)
{
listBox1.Items.Add(yourNumber);
}
else
{
MessageBox.Show("Please enter a number between 1-10");
}
What I would like to do is design a program for guessing a number. So this is the first part.
Update
Here is my final code, can it be improved? I think the next thing I'll do is to limit the times the user types the input. That means, they can only guess the right number 3 times or 5 times. Not sure where to implement it
namespace Guessing_Game
{
public partial class Form1 : Form
{
private static int randomNumber;
private const int rangeNumberMin = 1;
private const int rangeNumberMax = 10;
public Form1()
{
InitializeComponent();
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
}
private int GenerateNumber(int min,int max)
{
Random random = new Random();
return random.Next(min, max);
}
private void btnOk_Click(object sender, EventArgs e)
{
int yourNumber = 0;
Int32.TryParse(textBox1.Text.Trim(), out yourNumber);
if (yourNumber>= rangeNumberMin && yourNumber<=rangeNumberMax)
{
listBox1.Items.Add(yourNumber);
if (yourNumber > randomNumber)
{
listBox2.Items.Add("No the Magic Number is lower than your number");
}
if (yourNumber < randomNumber)
{
listBox2.Items.Add("No, the Magic Number is higher than your number");
}
if(yourNumber==randomNumber)
{
listBox2.Items.Add("You guessed the Magic Number!");
btnRestart.Enabled = true;
}
}
else
{
MessageBox.Show("Please enter a number between " + rangeNumberMin + " to " + rangeNumberMax);
}
}
private void btnRestart_Click(object sender, EventArgs e)
{
listBox2.Items.Clear();
listBox1.Items.Clear();
textBox1.Text = null;
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
btnRestart.Enabled = false;
}
}
The line:
int returnNunmber = RandomNumber(1, 10);
does nothing, because in the next line returnNumber is used as an output variable and will be whatever number is in textBox1. Remove the
int.TryParse(textBox1.Text, out returnNumber);
line and it will add a random number from 1 to 10 to your listbox.
EDIT::::
To answer you additional question, try:
private void btnOk_Click(object sender, EventArgs e)
{
string yourNumber;
yourNumber = textBox1.Text.Trim();
int returnNumber;
int.TryParse(textBox1.Text, out returnNumber);
if( returnNumber < 1 || returnNumber > 10) {
returnNumber = RandomNumber(1, 10);
}
listBox1.Items.Add(returnNumber);
}
Some minor changes to your code, condensing a couple lines and adding the limit code, utilizing the list of guesses as the counter:
namespace Guessing_Game
{
public partial class Form1 : Form
{
private static int randomNumber;
private const int rangeNumberMin = 1;
private const int rangeNumberMax = 10;
private const int maxGuesses = 5;
public Form1()
{
InitializeComponent();
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
}
private int GenerateNumber(int min,int max)
{
Random random = new Random();
return random.Next(min, max);
}
private void btnOk_Click(object sender, EventArgs e)
{
int yourNumber = 0;
if (Int32.TryParse(textBox1.Text.Trim(), out yourNumber) &&
yourNumber>= rangeNumberMin && yourNumber<=rangeNumberMax)
{
listBox1.Items.Add(yourNumber);
if (yourNumber > randomNumber)
{
listBox2.Items.Add("No the Magic Number is lower than your number");
}
else if (yourNumber < randomNumber)
{
listBox2.Items.Add("No, the Magic Number is higher than your number");
}
else
{
listBox2.Items.Add("You guessed the Magic Number!");
textBox1.Enabled = false;
btnOk.Enable = false;
btnRestart.Enabled = true;
}
//Will stop on the 5th guess, but guards the case that there were more than 5 guesses
if(listBox1.Items.Count >= maxGuesses && yourNumber != randomNumber)
{
listBox2.Items.Add("You are out of guesses!");
textBox1.Enabled = false;
btnOk.Enable = false;
btnRestart.Enabled = true;
}
}
else
{
MessageBox.Show("Please enter a number between " + rangeNumberMin + " to " + rangeNumberMax);
}
}
private void btnRestart_Click(object sender, EventArgs e)
{
listBox2.Items.Clear();
listBox1.Items.Clear();
textBox1.Text = null;
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
btnRestart.Enabled = false;
textBox1.Enabled = true;
btnOk.Enable = true;
}
}
}
Editted to prevent the "You're out of guesses" message when the number is correctly guessed on the last guess.
Lets take that piece by piece:
int returnNumber = RandomNumber(1, 10);
There is no inbuilt RandomNumber function; note that with the Random class, the end value is exclusive, so for a number in a range, you'll need something like:
static readonly Random rand = new Random();
static int Random(int min, int max) {
if(max < min) throw new ArgumentOutOfRangeException("max");
lock(rand) {
return rand.Next(min, max + 1);
}
}
However, you then throw away this value completely:
int.TryParse(textBox1.Text, out returnNumber);
The use of out means that the previous value of returnNumber is ignored completely. I'm not sure what your intent is, but it seems like you just want to check the value:
if(int.TryParse(textBox1.Text, out returnNumber)
&& returnNumber >= 1 && returnNumber <= 10)
{
listBox1.Items.Add(returnNumber);
}
I've tried to look at the last example, but it really isn't clear what you are trying to do - can you clarify?
(edited after question edit and comments)
You would need a counter, which you increment for failed tries - something like:
using System;
using System.Drawing;
using System.Windows.Forms;
class MyForm : Form {
Button btn;
ListBox lst;
TextBox tb;
const int MaxTries = 3, MaxNumber = 10;
int targetNumber, guessCount = 0;
public MyForm() {
targetNumber = new Random().Next(1, MaxNumber + 1);
Text = "Guess a number";
Icon = SystemIcons.Question;
Controls.Add(lst = new ListBox {Dock=DockStyle.Fill});
Controls.Add(btn = new Button {Text="Guess",Dock=DockStyle.Top});
Controls.Add(tb = new TextBox {Dock=DockStyle.Top});
btn.Click += btn_Click;
}
void btn_Click(object sender, EventArgs e) {
int userNumber;
if (int.TryParse(tb.Text.Trim(), out userNumber)) {
if (userNumber < 1 || userNumber > MaxNumber) {
lst.Items.Add("Did I mention... between 1 and " + MaxNumber);
} else {
if (userNumber == targetNumber) {
lst.Items.Add("Well done! You guessed well");
btn.Enabled = false; // all done
} else {
lst.Items.Add(targetNumber < userNumber
? "Try a bit lower" : #"It is bigger than that");
if (++guessCount >= MaxTries) {
btn.Enabled = false;
lst.Items.Add("Oops, should have picked more wisely");
}
}
}
} else {
lst.Items.Add("Nice; now give me a number");
}
}
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyForm());
}
}