Getting random integer from an event handler - c#

I want to get a random integer and return it while whole code can access the number. So I have tried something like:
private int randomnumber
{
set
{
Random rand = new Random();
int randomnumber = rand.Next(0, 70);
}
Then how should I call it/ get the randomnumber? For example I have tried:
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(randomnumber.ToString());
}
Then it drops this error:
The property or indexer 'Word_Game.Form1.randomnumber' cannot be used
in this context because it lacks the get accessor

Instead of using a property for this it might be better to declare a normal variable:
private int randomnumber;
Then in your constructor/load method you can initialise it:
public YourConstructor()
{
Random rand = new Random();
randomnumber = rand.Next(0, 70);
}
You should then be able to use it in the click event handler.
If you wanted it to change every time it was accessed though then you could just use a get accessor:
private Random rand = new Random();
private int randomnumber
{
get
{
return rand.Next(0, 70);
}
}

Related

Edit the content of a text block in a list C# (WPF Application)

So I have five text blocks I've added to a list, and each one is supposed to get its own random number between one and 6.
I know I can just do a new int for each text block (int randomNumberOne, randomNumberTwo, etc) but I'm trying to see if I can figure out how to make a list and a for each loop to work.
Is there some way to edit the content of a TextBox in a list as it goes through? If there is, I haven't found any way to do so.
Here's my code so far.
List<TextBlock> randomBoxList = new List<TextBlock>();
public MainWindow()
{
InitializeComponent();
randomBoxList.Add(randomBoxOne);
randomBoxList.Add(randomBoxTwo);
randomBoxList.Add(randomBoxThree);
randomBoxList.Add(randomBoxFour);
randomBoxList.Add(randomBoxFive);
}
Random randomGenerator = new Random();
int randomNumber;
private void randomButton_Click(object sender, RoutedEventArgs e)
{
foreach (TextBlock textBlock in randomBoxList)
{
randomNumber = randomGenerator.Next(1, 7);
//Code to change randomBox content goes here.
}
}
If this is WPF, you should just be able to use textBlock.Text property like so:
public partial class MainWindow : Window
{
List<System.Windows.Controls.TextBlock> randomBoxList = new List<System.Windows.Controls.TextBlock>();
public MainWindow()
{
InitializeComponent();
randomBoxList.Add(randomBoxOne);
randomBoxList.Add(randomBoxTwo);
randomBoxList.Add(randomBoxThree);
randomBoxList.Add(randomBoxFour);
randomBoxList.Add(randomBoxFive);
}
Random randomGenerator = new Random();
int randomNumber;
private void randomButton_Click(object sender, RoutedEventArgs e)
{
foreach (System.Windows.Controls.TextBlock textBlock in randomBoxList)
{
randomNumber = randomGenerator.Next(1, 7);
textBlock.Text = randomNumber.ToString();
}
}
}

Why am I still getting an Error CS0236 (Field Initializer error)?

I followed this other stack overflow discussion on how to get a random integer from a minimum value to a maximum value but it doesn't seem to work correctly in my code:
Random r = new Random();
int posx = r.Next(1, 816);
private void BtnTeleport_MouseEnter(object sender, EventArgs e)
{
BtnTeleport.Location = new Point(LblMiss.Location.X+posx, 5);
}
but it gives me the error:
A field initializer cannot reference non static field, method, property 'Form1.r'
any clues as to why it does this?
To move those setting codes into the method:
private void BtnTeleport_MouseEnter(object sender, EventArgs e){Random r = new Random();int posx = r.Next(1, 816);BtnTeleport.Location = new Point(LblMiss.Location.X+posx, 5);}

Modifying randomly button location

I'm trying to change randomly the location of a button when the mouse is hover it. To do that, I'm using the following source code :
private int modifX()
{
int rdmx;
int x_max = this.Width;
Random rdm = new Random();
rdmx = rdm.Next(0, x_max);
return rdmx;
}
private int ModifY(){
// same with y_max = this.Height;
}
private void bt_win_MouseEnter(object sender, EventArgs e)
{
bt_win.Location = new Point(modifX(), modifY());
}
The problem is that my button's position is always on a straight line like that
How can I fix it? I tried to use bt_win.Location.X = modifX(); on the mouseEnter event But it seems that I can't handle Location.X or Location.Y
I don't really get what I'm doing wrong, anyone got an idea and could explain me what I'm doing wrong?
You need to use the same instance of the Random class.
When you create two instance of the Random class closely, they can share the same seed. So the same number will be generated.
private Random _rdm = new Random();
private int modifX()
{
int x_max = this.Width;
int rdmx = _rdm.Next(0, x_max);
return rdmx;
}
private int ModifY(){
// same with y_max = this.Height;
}
private void bt_win_MouseEnter(object sender, EventArgs e)
{
bt_win.Location = new Point(modifX(), modifY());
}

Generating Random Color Produces Same Color Each Time [duplicate]

This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 7 years ago.
I am trying to create a dynamically added array of user-controls where each one will have a random color assigned to it to make the user more able to differentiate it from others, but when I do that it produces pattern of colors. It will create 10 of the user-controls with the same color then it will change the color for the next 10, I want each separate one to have a different color.
The code for the user-control:
public partial class EquationBox : UserControl
{
public EquationBox()
{
InitializeComponent();
this.panel4.BackColor = RandomColor();
}
private void button1_Click(object sender, EventArgs e)
{
this.Visible = false;
this.textBox1.Text = "";
}
private Color RandomColor()
{
Random rnd = new Random();
/*KnownColor[] names = (KnownColor[])Enum.GetValues(typeof(KnownColor));
KnownColor randomColorName = names[r.Next(names.Length)];
Color randomColor = Color.FromKnownColor(randomColorName);
return randomColor;*/
Color randomColor = Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256));
return randomColor;
}
}
The Code for form1:
public partial class Form1 : Form
{
public static EquationBox[] EquationBoxArray = new EquationBox[100];
public Form1()
{
InitializeComponent();
for (int x = 0; x < 100; x++)
{
EquationBoxArray[x] = new EquationBox();
EquationBoxArray[x].Parent = flowLayoutPanel1;
EquationBoxArray[x].Visible = false;
}
}
private void add_line_Click(object sender, EventArgs e) //Add Line
{
for(int x = 0; x < 100; x++)
{
if(!EquationBoxArray[x].Visible)
{
EquationBoxArray[x].Visible = true;
EquationBoxArray[x].Refresh();
break;
}
}
}
private void clear_Click(object sender, EventArgs e) //Clear Lines
{
for (int x = 0; x < 100; x++)
{
EquationBoxArray[x].Visible = false;
EquationBoxArray[x].ResetText();
}
}
private void Form1_SizeChanged(object sender, EventArgs e) //Window Size Changed
{
}
}
Thanks in advance, any help would be much appreciated!
The Random class is only a pseudo-random number generator, controlled by the seed parameter in the constructor. To achieve a better distribution of random numbers, try putting the creation of the Random object outside of the loop, or seed it with a different value each time.
For example
public partial class EquationBox
{
private static Random rnd;
static EquationBox()
{
rnd = new Random();
}
public EquationBox()
{
this.panel4.BackColor = GetRandomColor();
}
private Color GetRandomColor()
{
Color randomColor = Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256));
return randomColor;
}
}
You need to create global Random instance, or use another it constructor
https://msdn.microsoft.com/en-us/library/system.random(v=vs.110).aspx
More the Random to a field, then use it in the RandomColor function, as below.
Random _rnd = new Random();
private Color RandomColor()
{
Color randomColor = Color.FromArgb(_rnd.Next(256), _rnd.Next(256), _rnd.Next(256));
return randomColor;
}
This fixes it because Random uses a seed to initialize the pseudorandom number generator, which is the number of milliseconds since the computer was started. Therefore, if you create more than one Random in the same millisecond, it will start with the same seed.
you should only use one instance of Random Class.The problem could be because you are creating new instance of Random every time you call RandomColor .
You can move it to another class
public class MyRandom
{
private static Random _randColor=new Random();
private Color GetRandomColor()
{
Color randomColor = Color.FromArgb(rnd.Next(256), rnd.Next(256), rnd.Next(256));
return randomColor;
}
}
and in your user control call it using
public EquationBox()
{
InitializeComponent();
this.panel4.BackColor = MyRandom.GetRandomColor();
}
Your error comes from creating the Random Number Generator everytime you need a new random colour. The RNG is usually seeded with the current time and because you are creating new ones very quickly the get the same seed.
public partial class EquationBox
{
static Random rnd = new Random();
public EquationBox()
{
InitializeComponent();
lock (rnd)
{
this.panel4.BackColor = Color.FromArgb(rnd.Next(257), rnd.Next(257), rnd.Next(257));
}
}
}
Random.Next is not thread safe, so I have a lock around it. Also it returns a value LESS than the max parameter. So you most likely want to pass 257 instead of 256.

Get a random card and change the label

I'm just fooling around in Windows Forms and wish to click a button and then give a player 2 random cards, but when I click the button the label is empty. How do i pass the value to the string?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void DealTheCardsButton_Click(object sender, EventArgs e)
{
TheCards theCards = new TheCards();
CardOneLabel.Text = theCards.card1;
}
}
public class TheCards
{
public TheCards()
{
Cards = new List<string>();
Cards.Add("1");
Cards.Add("2");
Cards.Add("3");
Cards.Add("4");
}
public List<string> Cards { get; set; }
public string card1;
public string card2;
public string cardTest = "hej";
public void GiveTwoRandomCardsFromCardsList()
{
Random random = new Random();
int slumptal = random.Next(0, 4);
card1 = Cards[1];
bool flag = false;
while (!flag)
{
Random random2 = new Random();
int slumptal2 = random2.Next(0, 4);
if (slumptal != slumptal2)
{
card2 = Cards[slumptal2];
flag = true;
}
}
}
}
If I call to change the CardOneLabel.Text to a string with a hardcoded value in it it works. It seems like the randomizing doesn't change the value of string card1 and string card2. As it is now, when I click on the button the label changes its value to nothing (empty).
How can i change the label value to a random card value?
You never call the GiveTwoRandomCardsFromCardsList method. Try this:
private void DealTheCardsButton_Click(object sender, EventArgs e)
{
TheCards theCards = new TheCards();
theCards.GiveTwoRandomCardsFromCardsList();
CardOneLabel.Text = theCards.card1;
}
By the way, don't create a new Random object for every random number you require. This might even give you the same random number due to how the pseudo-random number generator depends on the current time. Just use the same Random instance over and over again. It will give you a new random number every time.
Also, you will sometimes get the same card twice. I'll leave it to the OP to figure out how to always get two different cards, if that's the idea.
But when I click the button the label is empty. How do i pass the
value to the string?
When you try to assign the value
CardOneLabel.Text = theCards.card1;
The constructor of that class TheCards is not initiating the card1 variable to anything, you are retrieving an empty string.
The constructor below, is adding to the list Cards but nothing else is taking place.. Do you have additional code your not showing?
public TheCards()
{
Cards = new List<string>();
Cards.Add("1");
Cards.Add("2");
Cards.Add("3");
Cards.Add("4");
}
Your CardOneLabel is empty when you press the button because you are literally reading an empty string. Try calling your GiveTwoRandomCardsFromCardsList() method before assigning.

Categories