I have two issues that I'm not sure how to fix.
diceThrow() is supposed to randomly roll a die and come up with an answer 1-6 multiple times, but only comes up with one 1-6 answer and only does that. i.e. (6, 6, 6, 6, 6, 6, etc)
and for rollDice(), I'm not sure if I just poorly defined "i" or maxRolls, but it should be that when i > maxRolls, the program should end and reset.
Any advice on how to fix either of these is greatly appreciated, thanks!
//somewhere else in code
int maxRolls = RollsNumber();
int throwresult = diceThrow();
int i;
//*******************************
private void rollButton_Click(object sender, EventArgs e)
{
rollDice();
wagerTextBox.Text = null;
wagerTextBox.Text = scoreTextBox.Text;
diceThrow();
MessageBox.Show(Convert.ToString(throwresult));
if (maxRolls < i)
{
MessageBox.Show("You got too greedy.");
//reset the form
}
}
// Decides the maximum number of rolls before the player loses
static public int RollsNumber()
{
Random rolls = new Random();
return rolls.Next(1, 10);
}
// Throws the dice
static public int diceThrow()
{
Random dice = new Random();
return dice.Next(1, 7);
}
private void rollDice()
{
for (i = 0; i <= maxRolls; i++)
{
int wager = Convert.ToInt32(wagerTextBox.Text);
int score = wager * 100;
scoreTextBox.Text = Convert.ToString(score);
}
}
}
}
You are using same seed with the Random.
As msdn states in Random class
The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random.
A simple way in your case is to not create new Random each time.
// Throws the dice
static Random diceRandom = new Random();
static public int diceThrow()
{
return diceRandom .Next(1, 7);
}
Related
I am trying to make a program that I Believe has to make use of recursion. In short: create a program that will throw a Dice. If it lands on a 6, two Dices are created and rolled, and so on until no more 6 are rolled.
The problem is not creating a new or true random object, but the recursive Dices.
The recursion method looks like this:
public static int Recursion(int a)
{
Random m = new Random();
if (a < 6)
{
return a;
}
else
{
a = m.Next(1, 7);
return Recursion(a) * 2;
}
}
Possibly something like this?
public static int Roll() {
return Roll(new Random(), 1);
}
public static int Roll(Random random, int diceCount) {
int sum = 0;
for (int dice = 1; dice <= diceCount; ++dice) {
int rolled = random.Next(1, 7);
if (rolled == 6) {
sum += Roll(random, 2)
}
else
{
sum += rolled;
}
}
return sum;
}
So, first I roll one die/dice. If it is not 6, then I accept its value as the result. If it is six, then I remove that die/dice, and replace it with two other I roll. Then, for each of the new ones I follow the same rule, until all the dice on the table is rolled and none of them is 6. Now I sum all the value of dice. This is what this recursive algorithm does. Note, that - however it has infinitely low chance - you can play this until the end of times, since there is always chance of rolling 6, so you can possibly roll only 6's until you die.
You can make it more object oriented by creating a dice object:
using System;
using System.Collections.Generic;
class Dices
{
public class Dice
{
private static Random roler = new Random();
private int roledNumber;
public int Role()
{
roledNumber = roler.Next(6) + 1 ;
return roledNumber;
}
public int Number
{
get { return roledNumber; }
}
}
static void Main(string[] args)
{
List<Dice> allDices = new List<Dice>();
Dice firstDice = new Dice();
allDices.Add(firstDice);
if (firstDice.Role() == 6) createDices(allDices);
}
static void createDices(List<Dice> dices)
{
Dice first = new Dice();
dices.Add(first);
if (first.Role() == 6) createDices(dices);
Dice second = new Dice();
dices.Add(second);
if (second.Role() == 6) createDices(dices);
}
}
I want to generate 10 'random' numbers, but they have to be unique. I have tried something, but is there someone who can help me out with something better?
My code:
List<int> ran = new List<int>();
Random rnd = new Random();
public static int randomValue;
int tempRandom;
public int randomNum()
{
if(ran.Count == 0)
{
ran.Add(0);
ran.Add(1);
ran.Add(2);
ran.Add(3);
ran.Add(4);
ran.Add(5);
ran.Add(6);
ran.Add(7);
}
tempRandom = rnd.Next(0, ran.Count);
randomValue = ran[randomValue];
ran.RemoveAt(tempRandom);
return randomValue;
}
Is this what you're trying to say? If not, please specify how you mean further. This code should give you a number between 1-10 that hasn't been already used. This code will only work 10 times.
Random rnd = new Random();
List<int> usedNumbers = new List<int>();
public int RandomNum(){
int number;
do {
number = rnd.Next(1, 10);
} while(usedNumbers.IndexOf(number) == -1);
usedNumbers.Add(number);
return number;
}
Straight answer to your question (not regarding if you actually want what you are asking for):
Random.Range( int.MinValue, int.MaxValue );
This simply produces a random int in the range of all integers. For 10 numbers, the probability of duplicates is so little that every number will be unique.
This is my random unique numbers generator I try to create for my cards software. It generates numbers and write into array OK. I have problem with the loop here. when integer i reaches 29, it stops growing and code cycles infinitely and never reaches 30, which would stop the loop.
Without the if statement it works, but it won't fill the range needed.
fixed the code, now works OK, the initial value in array was the problem. now I ged needed 0-29 values
public partial class Form1 : Form
{
int[] rndCards = new int[30];
public Form1()
{
InitializeComponent();
richTextBox1.Text = #"random numbers";
}
private void button1_Click(object sender, EventArgs e)
{
int i = 0;
rndCards = new int[30];
richTextBox1.Clear();
Random rnd = new Random();
while (i < 30)
{
int cardTest = rnd.Next(0, 30);
while (rndCards.Contains(cardTest))
{
cardTest++;
if (cardTest == 31)
{
cardTest = 1;
}
}
rndCards[i] = cardTest;
i++;
}
i = 0;
while (i < 30)
{
rndCards[i] = rndCards[i] -1;
richTextBox1.Text += rndCards[i] + ", ";
i++;
}
}
}
You problem lies in the simple fact that the array already contains the number 0 when you create it (because each item of an array is initialized to the default value for its member's type) That's why you should start your i from 1 and not zero.
int i = 1;
Alternative Simpler Approach:
You can do this as a simple random number generation:
Random rnd = new Random();
rndCards = Enumerable.Range(0, 30).OrderBy(x => rnd.Next()).ToArray();
foreach(var card in rndCards)
{
// do something
}
rnd.Next(0,30) would return a random number from 0-29.
From the documentation for Random.Next(Int32, Int32):
The Next(Int32, Int32) overload returns random integers that range from minValue to maxValue – 1. However, if maxValue equals minValue, the method returns minValue.
Use int cardText = rnd.Next(0, 31);, and this should solve your issue.
The upper bound is exclusive (C# Random.Next - never returns the upper bound?).
int cardTest = rnd.Next(0, 31);
Its roll the dice application. I want to sum up the dice results and present them to the user. Currently the dice image will change after I click the button "Click to roll the die".
However, When I rolled the dice 1, result will not be add (+0) and when i rolled dice 2, the result will only (+1). I have no idea what's wrong with my code:
public partial class PigForm : Form
{
Image[] diceImages;
int[] dice;
Random roll;
private void rollDieBotton_Click(object sender, EventArgs e)
{
RollDice();
}
private void RollDice()
{
for (int i = 0; i < dice.Length; i++)
{
var currentRoll = roll.Next(0, 6);
dice[i] += currentRoll;
dicePictureBox.Image = diceImages[currentRoll];
playersTotal.Text = String.Format("{0}", dice[i]);
}
}
private void PigForm_Load(object sender, EventArgs e)
{
diceImages = new Image[6];
diceImages[0] = Properties.Resources.Alea_1;
diceImages[1] = Properties.Resources.Alea_2;
diceImages[2] = Properties.Resources.Alea_3;
diceImages[3] = Properties.Resources.Alea_4;
diceImages[4] = Properties.Resources.Alea_5;
diceImages[5] = Properties.Resources.Alea_6;
dice = new int[1] { 0 };
roll = new Random();
}
}
A few remarks on your code:
Why use an array if it will always contain one integer? This also makes the for loop quite useless. Use a plain integer and remove the loop.
The Next() method of the Random class has two parameters. The first is inclusive lower-bound, the second one is exclusive upper-bound. Meaning in your case that the 0 will be a possible number, while 6 will never occur. (MSDN page: Random.Next Method (Int32, Int32))
Here's a slight modification of your code:
public partial class PigForm : Form
{
Image[] diceImages;
int dice;
Random roll;
private void rollDieBotton_Click(object sender, EventArgs e)
{
RollDice();
}
private void RollDice()
{
var currentRoll = roll.Next(1, 7);
dice += currentRoll;
dicePictureBox.Image = diceImages[currentRoll-1];
playersTotal.Text = String.Format("{0}", dice);
}
private void PigForm_Load(object sender, EventArgs e)
{
diceImages = new Image[6];
diceImages[0] = Properties.Resources.Alea_1;
diceImages[1] = Properties.Resources.Alea_2;
diceImages[2] = Properties.Resources.Alea_3;
diceImages[3] = Properties.Resources.Alea_4;
diceImages[4] = Properties.Resources.Alea_5;
diceImages[5] = Properties.Resources.Alea_6;
dice = 0;
roll = new Random();
}
}
var currentRoll = roll.Next(0, 6)
This will generate a random number from 0 to 5, inclusive. You probably want to generate from 1 to 6:
var currentRoll = roll.Next(1, 7)
Reference: Random.Next Method (Int32, Int32)
Edit:
dicePictureBox.Image = diceImages[currentRoll - 1]
First of all, having an integer array for your dice is pointless because you need only one number which also means that you do not need a loop for it because it will never iterate for a second time.
Secondly your random goes from zero to five included and you want it to be from 1 to 6.
Your code with a few edits:
var currentRoll = roll.Next(1, 7);
dice = currentRoll; // there should not be += operator because the result of the next roll will be absurd
dicePictureBox.Image = diceImages[currentRoll - 1]; // -1 because your array is zero-based which means that it starts from 0
That is how the random class really works. The initial value which in your case is 1, is included, but the one in the ending is not, so what you need is 1,7 because it will return a number between 1 and 6 included.
You are allowing the currentRoll variable be anything between [0, 6]. That includes 0 but excludes 6. You should probably change to var currentRoll = roll.Next(1, 7);
Edit for comment: Then for accessing your array values(which is zero indexed) you should subtract one from your roll result.
As others have pointed out, Random.Next(a, b) generates a random number between a inclusive and b exclusive.
While it would be easy to just do
var currentRoll = roll.Next(1, 7);
that would break the array access line you have two lines later.
Instead, your best bet would be to modify the addition line, to do
dice[i] += currentRoll + 1;
Take a look at the documentation of the Random.Next(int, int) method:
http://msdn.microsoft.com/en-us/library/2dx6wyd4%28v=vs.110%29.aspx
There you will find that the lower bound is inclusive and the upper bound is exclusive.
Hence Next(0,6) means that you get a 0, 1, 2, 3, 4 or 5.
I did not exactly understand what your problem is but I did spot something that looks wrong.
Try changing:
dice[i] += currentRoll;
With:
dice[i] += currentRoll+1;
I'm creating a simple game (Yatzee) in C#. I have created an array which holds 5 different dice
int[] dice = new int[5];
Now, I want to create a method that throw one of these five dices. Which die that should be thrown, should be passed in as an argument in that method. So this is how I tried:
public void throwDice(int x)
{
Random r1 = new Random(6);
r1.x;
}
What I believe is happening, is that the method takes in an argument x, that randomly should throw the dice to be a number between 1-6. But I'm getting error with when I write saying : r1.x;
So, why I'm asking here, is if I could get some guidance. Am I on the right track here, or am I totally lost?
You are using the Random object wrong. The constructor parameter is a seed. You need r1.Next(6)+1.
See the related post for details: How do I generate a random int number in C#?.
What you probably want to do is this:
Random rnd = new Random();
int[] dice = new int[5];
void ThrowDie(int x)
{
dice[x] = rnd.Next(6)+1;
}
r1 is an instance of a Random class. x is a parameter of your throwDice method.
That does not mean your r1 must have a field called x.
I think you are looking for something like;
Random r1 = new Random();
public int throwDice()
{
return r1.Next(1, 6);
}
Rememer, in Random.Next method lowerbound is inclusive but upperbound is exclusive.
Here is another approach to this matter:
public class RandomDice
{
private const int NUMBER_OF_DICE = 5;
private const int MAX_DICE_VALUE = 6;
private static readonly Random Rng = new Random();
public List<int> NumberList = new List<int>();
private static IEnumerable<int> GetRandomNumbers()
{
while (true)
yield return Rng.Next(1, MAX_DICE_VALUE + 1);
}
internal void AddDice()
{
NumberList.Clear();
NumberList.AddRange(GetRandomNumbers().Take(NUMBER_OF_DICE).ToList());
}
}