Sign in to follow this  
durtyduval

C# Windows App

Recommended Posts

durtyduval    122
working on a little guessing game that i made in a console app. now im making it into a windows app i have it working so far, but when i guess a number, it keeps generating a new number each time i click the button to submit the guess
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ProgrammingAssign4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnGuess_Click(object sender, EventArgs e)
        {
            int randomNumber = GetRandomNumber();
            int counter = 0;
            int guess;

            guess = int.Parse(txtGuess.Text);

            lblAnswer.Text = randomNumber.ToString();

                counter++;


                if (guess < randomNumber)
                {
                    counter++;
                    this.BackColor = System.Drawing.Color.Red;
                    this.lblHigh.Visible = false;
                }
                else if (guess > randomNumber)
                {
                    counter++;
                    this.lblHigh.Visible = true;
                    this.BackColor = System.Drawing.Color.Blue;
                }
                else if (guess == randomNumber)
                {
                    counter++;
                    string name = ("It took you " + counter + " guesses to get it correct");
                    MessageBox.Show(name);
                }
            
        }

        private static int GetRandomNumber()
        {
            Random random = new Random();
            int randomNumber = random.Next(1, 10) + 1;
            return randomNumber;
        }
    }
}

Share this post


Link to post
Share on other sites
Boder    938
That's because you call GetRandomNumber() each time the button is clicked, you need to store the random number as part of the class, not within the function, and only generate the number once.

Share this post


Link to post
Share on other sites
smitty1276    560
Quote:
Original post by durtyduval
nevermind i got it working, i had to put the random number in the form1 event handler


We went through this at least 5 times in the other thread you created, and it was the same problem that you had here. The problem was that you generated the random number in an event handler for the button click. I'm assuming you meant to say that you put the random number generation in the Form1 constructor.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this