Thursday, January 17, 2013

5.9.1. Random numbers


In a management program, it is unusual to allow things to happen at random. But games are often one of the most complete programming exercises, and for a game itself is often desirable to have some randomness, so that each match is not exactly like the previous one.

Generating random numbers using C# is not difficult: we must create an object of type "Random" and then we will call "Next" to obtain values ​​between two extremes:

// We create an object of type Random
Random generator = new Random();

// And the we generate a value between two desired limits
// (second limit is not included)
int randomNumber = generator.Next(1, 101);

Also, a very simple way to obtain a "quasi-random" number between 0 and 999 is to obtain the milliseconds in the current time:

int falseRandom = DateTime.Now.Millisecond;

This simple way is not useful if we need two random numbers at the same time, as the would be obtained it the same millisecond, so they would have the same value. If we need two random numbers, we would use "Random" and we would call "Next" twice.

Let's see an example, which displays two random numbers between 1 and 10:

/*---------------------------*/
/*  C# Example #56:          */
/*  example56.cs             */
/*                           */
/*  Random numbers           */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example56
{

  public static void Main()
  {
    Random generator = new Random();
    int randomNumber = generator.Next(1, 11);
    Console.WriteLine("A number between 1 y 10: {0}",
      randomNumber);
    int randomNumber2 = generator.Next(1, 11);
    Console.WriteLine("Another: {0}", randomNumber2);
  }
 
}


Suggested exercises:
·       (5.9.1.1) Create a program that generates a random number between 1 and 100. The user will have 6 chances to guess it.
·       (5.9.1.2) Improve the hangman program proposed in paragraph 4.4.8, so that the word to guess is not entered by a second user, but chosen at random from an array of words (city names, for example).
·       (5.9.1.3) Create a program that "draws" asterisks in 100 random positions on the screen. To help you write in any coordinates, you can use a two-dimensional array (with sizes 24 for the height and 79 for the width), which you will fill first and then draw on the screen.

No comments:

Post a Comment