Hi

I made a code where user can guess the number. Now I would like to implement the number of tries and I would like that the user will only guess til 3 times. It seems I'm quite lost here.
I tried to declare it as constructors but not sure what's next.
Any idea?

Thanks

namespace Guessing_Game
{
public partial class Form1 : Form
{
private static int randomNumber;
private const int rangeNumberMin = 1;
private const int rangeNumberMax = 10;
private int numTries;
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;
}
}

Recommended Answers

All 5 Replies

I will concentrate on your question here.
Put all the code inside your OK_Click handler in a new method :
private void Guess()
Inside the OKClick put the following: (just a suggestion here)

const int MaxTries = 3;

            for (int Tries = 1; Tries <= MaxTries; Tries++)
            {
                Guess();
            }
            // Do here something when number of guesses is exceeded

Please put your code in code tags.

This doesn't start a new game properly, and has a few other issues but it should get you started. I didn't know if you wanted to disable the button, close the app, etc.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;

namespace daniweb
{
  public partial class frmRandomNumber : DevExpress.XtraEditors.XtraForm
  {
    private const int rangeMax = 10;
    private const int rangeMin = 1;
    private const int tries = 3;
    private RandomNumberGame _game;

    public frmRandomNumber()
    {
      InitializeComponent();
    }

    private void frmRandomNumber_Load(object sender, EventArgs e)
    {
      DoNewGame(false);
    }

    private void simpleButtonGuess_Click(object sender, EventArgs e)
    {
      int guess;
      if (!int.TryParse(textEditGuess.Text, out guess))
      {
        MessageBox.Show("Invalid number!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
        textEditGuess.Focus();
        return;
      }
      else
      {
        if (_game.NumberOfTriesRemaining > 0)
        {
          RandomNumberGame.GuessResult result = _game.Guess(guess);
          switch (result)
          {
            case RandomNumberGame.GuessResult.Lower:
              MessageBox.Show("The number is lower than your guess", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
              break;
            case RandomNumberGame.GuessResult.Higher:
              MessageBox.Show("The number is higher than your guess", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
              break;
            case RandomNumberGame.GuessResult.YouGotIt:
              MessageBox.Show("You got it!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
              break;
            default:
              throw new InvalidEnumArgumentException("result", (int)result, typeof(RandomNumberGame.GuessResult));
          }
        }
      }
      
      if (_game.Solved || (_game.NumberOfTriesRemaining == 0))
        DoNewGame(true);
    }

    private void DoNewGame(bool Prompt)
    {
      if (Prompt && (MessageBox.Show("Would you like to play a new game?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Information) != DialogResult.Yes))
        return;
      _game = new RandomNumberGame(rangeMin, rangeMax, tries);
    }

  }

  internal class RandomNumberGame
  {
    public enum GuessResult { Lower, Higher, YouGotIt }
    private int _lowValue;
    private int _highValue;
    private int _randomValue;
    private int _numberOfTries;
    private int _numberOfTriesRemaining;

    private bool _solved;

    public int LowValue
    {
      get { return _lowValue; }
    }
    public int HighValue
    {
      get { return _highValue; }
    }
    public int RandomValue
    {
      get { return _randomValue; }
    }
    public int NumberOfTries
    {
      get { return _numberOfTries; }
    }
    public int NumberOfTriesRemaining
    {
      get { return _numberOfTriesRemaining; }
    }
    public bool Solved
    {
      get { return _solved; }
    }
    private RandomNumberGame()
    {
      _lowValue = default(int);
      _highValue = default(int);
      _randomValue = default(int);
      _numberOfTries = default(int);
      _solved = default(bool);
    }
    public RandomNumberGame(int LowValue, int HighValue, int NumberOfTries)
      : this()
    {
      if (LowValue >= HighValue)
        throw new ArgumentException("The low value must be less than the high value");

      _randomValue = new Random().Next(LowValue, HighValue);
      _highValue = HighValue;
      _lowValue = LowValue;
      _numberOfTries = NumberOfTries;
      _numberOfTriesRemaining = NumberOfTries;
    }
    public GuessResult Guess(int Number)
    {
      if (_numberOfTries == 0)
        throw new InvalidOperationException("You have ran out of guesses!");

      _numberOfTriesRemaining--;

      if (Number > this.RandomValue)
        return GuessResult.Lower;
      else if (Number == this.RandomValue)
      {
        _solved = true;
        return GuessResult.YouGotIt;
      }
      else if (Number < this.RandomValue)
        return GuessResult.Higher;
      else
        throw new Exception();
    }
  }
}

I will concentrate on your question here.
Put all the code inside your OK_Click handler in a new method :
private void Guess()
Inside the OKClick put the following: (just a suggestion here)

const int MaxTries = 3;

            for (int Tries = 1; Tries <= MaxTries; Tries++)
            {
                Guess();
            }
            // Do here something when number of guesses is exceeded

Please put your code in code tags.

Hi ddanbe

Thanks for the suggestions. Does that matter where shall I put the new method?

Thanks

Hi sknake,

Thanks for the suggestion I'll give it a try and will post the result. In my code, I had made the restart button which also clears the game and start a new one.

hi ddanbe
I'm not really sure if I understand the creating a new method.
That means like this:

private void btnOk_Click(object sender, EventArgs e)
  {            
     .....
         private void Guess()
          const int MaxTries = 3;
          for (int Tries = 1; Tries <= MaxTries; Tries++)
         {
           Guess();
         }
   }

It seems I'm getting an error. Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.