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());
}
Related
In UWP i would like to give my button a random location on my screen when it is clicked on.
My code looks like this:
private void DeclareHere()
{
Random randomGenerator = new Random();
int iRndX = randomGenerator.Next(1, 640);
int iRndY = randomGenerator.Next(1, 360);
btnRandom.Margin.Left.Equals(iRndX);
btnRandom.Margin.Top.Equals(iRndY);
}
private void btnRandom_Click(object sender, RoutedEventArgs e)
{
DeclareHere();
}
What is it that i'm missing? Would help if you could explain how you accomplished the solution to this.
Equals is just a comparison operator.
ex:
bool isEqual = btnRandom.Margin.Left.Equals(iRndY);
You need to assign margin values
So, you should change this:
btnRandom.Margin.Left.Equals(iRndX);
btnRandom.Margin.Top.Equals(iRndY);
with this:
btnRandom.Margin = new Thickness { Left = iRndX, Top = iRndY};
My program creates 5 different labels with a cube form and they just drop down. When I press on them, they come invisible. I want to check if all of them are invisible, but don't know how to do so. Tried going through this site, found a solution with bool, but it just doesn't work my way. Also when my labels appear,you can see only 4 of them.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Label [] kubeliai = new Label [5];
int poz = 100;
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < kubeliai.Length; i++)
{
kubeliai[i] = new Label();
Controls.Add(kubeliai[i]);
Random pos = new Random();
kubeliai[i].Top = 50;
kubeliai[i].Left = poz;
poz += pos.Next(50, 200);
kubeliai[i].BackColor = Color.Red;
kubeliai[i].Height = 20;
kubeliai[i].Width = 20;
kubeliai[i].Click += new EventHandler(kubelio_clickas);
}
Timer kritimo_laikrodis = new Timer();
kritimo_laikrodis.Interval = 10;
kritimo_laikrodis.Tick += new EventHandler(laikrodis);
kritimo_laikrodis.Enabled = true;
}
void kubelio_clickas (object sender, EventArgs e)
{
((Label)sender).Visible = false;
}
void laikrodis (object sender, EventArgs e)
{
for (int i = 0; i < kubeliai.Length; i++)
{
kubeliai[i].Top += 1;
if (kubeliai.All.Visible == false) // this is an error
{
kubeliai[i].Visible = true;
kubeliai[i].Top = 50;
Random pos = new Random();
poz += pos.Next(50, 200);
}
}
}
Using Linq you can check if all are invisible in this way
var areAllInvisible = kubeliai.All(l => l.Visible == false);
if (areAllInvisible)
{
// do something
}
when my labels appear you can see only 4 of them.
That's because the way you are picking random numbers is picking the same numbers each time and you are therefore placing your labels on top of each other. Read the first paragraph of the Random() documentation:
Different Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of random numbers. This problem can be avoided by using a single Random object to generate all random numbers.
Use new Random() once in your class definition like this:
Label [] kubeliai = new Label [5];
Random pos = new Random();
And remove it everywhere else in your program.
I am kinda stuck and I need help.
My goal is to make a little "game". It should have 3 pictureboxes and it should randomly display/change numbers (pictures) 1 to 6 every 0,5sec. When I hit STOP, it should stop the numbers and I should get points (score) based on nubmers. 3 same numbers = +10 points, 2 same numbers = +5 points, no same numbers = -5 points. Then it should display highest score achieved (Max Score).
http://i.imgur.com/kubQBST.png
Please, give me some tips what to do.
Thanks a lot, regards Peter
You can use a Timer with random something like this :
Random rnd1 = new Random(Environment.TickCount);
Image[] Images = new Image[6];
int[] CurrentStatus = new int [3];
Images[0] = Image.FromFile("FileNameFornumber1");
Images[1] = Image.FromFile("FileNameFornumber2");
Images[2] = Image.FromFile("FileNameFornumber3");
Images[3] = Image.FromFile("FileNameFornumber4");
Images[4] = Image.FromFile("FileNameFornumber5");
Images[5] = Image.FromFile("FileNameFornumber6");
//change numbers every tick
private Timer_TickHandler(object sender, EventArgs e)
{
this.CurrentState[0] = rnd1.Next(1, 6);
this.CurrentState[1] = rnd1.Next(1, 6);
this.CurrentState[2] = rnd1.Next(1, 6);
this.PictureBox1.Image = Images[this.CurrentStatus[0]-1];
this.PictureBox2.Image = Images[this.CurrentStatus[1]-1];
this.PictureBox3.Image = Images[this.CurrentStatus[2]-1];
}
you have to write an event for the stop button to deactivate the timer and calculate the score based on the CurrentStatus Array and I think the calculation alg must be like this :
int score = this.CurrentStatus.Sum();
if (this.CurrentStatus[0] == this.CurrentStatus[1] && this.CurrentStatus[1] == this.CurrentStatus[2])
score +=10;
else
{
for (int i=0; i<3; i++)
{
for (int j=i+1; j<3; j++)
{
if (this.CurrentStatus[i] == this.CurrentStatus[j])
{
score+=5;
break;
}
}
}
}
for start make random picture on button press.
How add images into resources
For example
public partial class Form1 : Form
{
List<Bitmap> picturesList = new List<Bitmap>(); //Array of pictures
Random random = new Random();
public Form1()
{
InitializeComponent();
//Load all pictures from resources into array
picturesList.Add(Properties.Resources.pic1);
picturesList.Add(Properties.Resources.pic2);
picturesList.Add(Properties.Resources.pic3);
//Set random image into picture box
RandomChangeImage();
}
public void RandomChangeImage()
{
//Generate random number. (random index between 0 - array.count )
int randomIndex = random.Next(0, picturesList.Count);
//Set random image from array
YourPictureBoxName.Image = picturesList[randomIndex];
}
}
Now you can use RandomChangeImage(); in your code. Aflter you done you can continue with timer.
Now add Timer from toolbox into designer.
Double click on timer.
It generated this
private void timer1_Tick(object sender, EventArgs e)
{
//Call random change image
RandomChangeImage();
}
in you buttonstart_Click call timer1.Start(); for example
private void btnStart_Click(object sender, EventArgs e)
{
timer1.Start();
}
if you want change tick in timer you can use
timer1.Interval = 500; for 0.5s. where you want.
if you want stop timer use
timer1.Stop();
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.
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);
}
}