Random number generator with strings - c#

I have some code that sends a number that is pre-calculated to an Arduino.
instead of a pre-calculated number, I want a random number between a range of number, for example between the numbers 1 to 20, the random number is 18,
after the random number is found put it in a string so I can work with it.
I've tried many things on stack overflow but things are too complicated and I work with C#.
the code below is what I have right now,
I would prefer that it will send that random number to the Arduino
namespace MyLaserTurret
{
public partial class Form1 : Form
{
public Stopwatch watch { get; set; }
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
watch = Stopwatch.StartNew();
port.Open();
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
writeToPort(new Point(e.X, e.Y));
}
public void writeToPort(Point coordinates)
{
if (watch.ElapsedMilliseconds > 15)
{
watch = Stopwatch.StartNew();
port.Write(String.Format("X{0}Y{1}",
(coordinates.X / (Size.Width / 180)),
(coordinates.Y / (Size.Height / 180))));
}
}
}
}

To create a random number as a string you use this code
private Random random = new Random();
public string RandomNumber(int min, int max)
{
return random.Next(min, max).ToString();
}
Please note that it is probably best practice to declare a "Random random = new Random();" as a class property because when a Random is created too closely together they will just keep having the same value

Related

I want to create a program that automatically updates the maximum value when I press the button

I'm sorry to ask you a basic question first. It hasn't been long since I learned C#.
private void numberButton_Click(object sender, EventArgs e)
{
Random rand = new Random();
int randNumber = rand.Next(1, 1000);
randomNumber.Text = randNumber.ToString();
bestScoreLabel.Text = randomNumber.Text;
}
How can I implement the function so that the maximum value of the bestScoreLabel is automatically updated when I click the number button as shown in the picture above?
Currently, the code is configured as above, but the problem occurs that the maximum and current values are the same output.
The idea is to have a variable to keep tracking the max number.
private static int _maxNumber = 0;
private void numberButton_Click(object sender, EventArgs e){
Random rand = new Random();
int randNumber = rand.Next(1, 1000);
randomNumber.Text = randNumber.ToString();
if (_maxNumber < randNumber)
{
_maxNumber = randNUmber;
}
bestScoreLabel.Text = _maxNumber.ToString();
}

c# - "Loop-animation" through a string list

I'm building a very simple C# WPF Application. What the app does is that when I press a button it shows a value randomly from an string list.
What I would like to achieve is a animation where it quickly scrolls through all the values from the list (displaying in a label) and then start to slow down and stop on a random string from the list. Almost as a "spinning/scrolling/flashing wheel of text".
I'm still very new to programming (second day of C# learning) so would be glad if someone could point me in the right direction. Loop with timer?
List<string> randomStrings = new List<string>();
public MainWindow()
{
InitializeComponent();
randomString.Add("Abcd");
randomString.Add("Water");
randomString.Add("Moon");
randomString.Add("Pizza");
randomString.Add("Winter");
randomString.Add("Orange");
MyRandomStrings.ItemsSource = randomString; //Showing which strings in box.
}
public void GetRandomString()
{
Random r = new Random();
int index = r.Next(randomString.Count);
string myRandomString = randomString[index]; //Fetch a random string
Result.Content = myRandomString; //Sets the label. I want this to be "animated".
}
private void Button_Click(object sender, RoutedEventArgs e)
{
GetRandomString();
}
You could use a Task.Delay to create a delay and still create sequential code instead of a statemachine or timers etc.
Here is an example:
It uses a Label and a Button on a WindowsForm. So with a little ajustment, you can make it work on your configuration.
public partial class MainWindow : Form
{
private List<string> _randomStrings = new List<string>();
private Random _rnd = new Random(DateTime.UtcNow.Millisecond);
public MainWindow()
{
InitializeComponent();
_randomStrings.Add("Abcd");
_randomStrings.Add("Water");
_randomStrings.Add("Moon");
_randomStrings.Add("Pizza");
_randomStrings.Add("Winter");
_randomStrings.Add("Orange");
}
private async void button1_Click(object sender, EventArgs e)
{
// determine the rollcount. (some initial rolls for the rolling effect)
int rollCount = 50 + _rnd.Next(_randomStrings.Count);
int index = 0;
// roll it.......
for (int i = 0; i < rollCount; i++)
{
// just use a modulo on the i to get an index which is inside the list.
index = i % _randomStrings.Count;
// display the current item
label1.Text = _randomStrings[index];
// calculate a delay which gets longer and longer each roll.
var delay = (250 * i / rollCount);
// wait some. (but don't block the UI)
await Task.Delay(delay);
}
MessageBox.Show($"and.... The winner is... {_randomStrings[index]}");
}
}

how to make checkboxes work in accordance with labels c#(yahtzee)

This is my form running, i want to code the checkboxes so that they can hold the picture of their specific dice
Image[] diceImages;
int[] dice;
Random rand;
#endregion
#region Initialization
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
diceImages=new Image[7];
diceImages[0] = Properties.Resources.dice_face_0;
diceImages[1] = Properties.Resources.dice_face_1;
diceImages[2] = Properties.Resources.dice_face_2;
diceImages[3] = Properties.Resources.dice_face_3;
diceImages[4] = Properties.Resources.dice_face_4;
diceImages[5] = Properties.Resources.dice_face_5;
diceImages[6] = Properties.Resources.dice_face_6;
dice = new int[5] { 0, 0, 0, 0, 0 };
rand = new Random();
}
#endregion
private void btnRoll_Click(object sender, EventArgs e)
{
for (int i = 0; i < dice.Length; i++)
dice[i] = rand.Next(1, 7);
Array.Sort(dice);
lblDie1.Image = diceImages[dice[0]];
lblDie2.Image = diceImages[dice[1]];
lblDie3.Image = diceImages[dice[2]];
lblDie4.Image = diceImages[dice[3]];
lblDie5.Image = diceImages[dice[4]];
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void chk4_CheckedChanged(object sender, EventArgs e)
{
}
i have created 5 checkboxes with names chk1-5, i have tried fitting the code in but it doesn't work, could someone help me make this code work.
While your question is pretty unclear as to how you actually want your UI to look like, what might help is the use of UserControls:
You could make a new UserControl named DiceControl that combines one dice image and its corresponding CheckBox. You can then put multiple instances of that control on your form in the designer as if it were just one control. That might help you align stuff the way you want.
All you need to do is create methods/properties on the DiceControl that allow you to get/set the current image and the current hold status.

how to run a method in csharp exactly ten times and then go to another method

How to run a method exactly ten times in csharp?
I'm writing a c#/xaml windows8 app, and I want to run some method for button exatcly 10 times, and when it is called 10th time, I want it to go on to another method that will execute itself.
My button in XAML leads to this method I want to use ten times, to get 10 different images every time (I still haven't figured how to get different images every time because if-else loop in this method is infinite):
public void LoadImage_Click_1(object sender, RoutedEventArgs e)
{
Random rand = new Random();
int pic = rand.Next(1,0)
myImage.Source = new BitmapImage(new Uri("ms-appx:///img/" + pic +".jpg"));
}
and after it runs for the 10th time I want to use another method on the same button
As mentioned, this can be accomplished using a simple counter.
private volatile int _loadImageCount = 0;
public void LoadImage_Click_1(object sender, RoutedEventArgs e)
{
_loadImageCount += 1;
if (_loadImageCount > 10)
{
UpdateImage();
}
else
{
UpdateRandomImage();
}
}
private void UpdateRandomImage()
{
Random rand = new Random();
int pic = rand.Next(1,0)
myImage.Source = new BitmapImage(new Uri("ms-appx:///img/" + pic +".jpg"));
}
private void UpdateImage()
{
...
}
int numberOfExecutions=0;
public void LoadImage_Click_1(object sender, RoutedEventArgs e)
{
if(numberOfExecutions < 10)
{
Random rand = new Random();
int pic = rand.Next(1,0);
myImage.Source = new BitmapImage(new Uri("ms-appx:///img/" + pic +".jpg"));
}
else
MessageBox.Show("Dududu!");
numberOfExecutions++;
}

Random numbers in C#

I get the error below when I try to run the application I am sure its something simple but I dont see it. What I am trying to do it when I click a button I have labeled Play. I want to call a method called randomnumber. Then I want the results to be displayed in lblPickFive_1.
I have 2x2,Pick5,and powerball. Each random number is to be displayed in its own label I created.
For now I am just looking to get past the one of generating a random number and having it displayed in the one label then I will move onto the rest. And I am sure post more questions if I cant figure out the rest.
Error 1 No overload for method 'RandomNumber' takes '0' arguments
using System;
using System.Windows.Forms;
namespace LotteryTickets
{
public partial class Form1 : Form
{
/// <summary>
/// no-args Constructor
/// </summary>
public Form1()
{
InitializeComponent();
}
#region "== Control Event Handlers =="
private void Form1_Load(object sender, EventArgs e)
{
ClearWinningNumbers();
}
#endregion "== End Control Event Handlers =="
#region "== Methods ==";
/// <summary>
/// Clears the text inside the winning number "balls"
/// </summary>
private void ClearWinningNumbers()
{
this.lblPickFive_1.Text = "";
this.lblPickFive_2.Text = "";
this.lblPickFive_3.Text = "";
this.lblPickFive_4.Text = "";
this.lblPickFive_5.Text = "";
this.lblTwoByTwo_1.Text = "";
this.lblTwoByTwo_2.Text = "";
this.lblPowerball_1.Text = "";
this.lblPowerball_2.Text = "";
this.lblPowerball_3.Text = "";
this.lblPowerball_4.Text = "";
this.lblPowerball_5.Text = "";
this.lblPowerball_PB.Text = "";
}
#endregion "== End Methods ==";
private void cblTwoByTwo_2_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void cblTwoByTwo_1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void btnPlay_Click(object sender, EventArgs e)
{
RandomNumber();
}
private void lblPickFive_1_Click(object sender, EventArgs e)
{
}
private void RandomNumber(int min, int max)
{
int num = new Random().Next(min, max);
lblPickFive_1.Text = num.ToString();
}
}
}
First, you shouldn't be newing up a random number generator every time you want a new random number. You should set the generator as a static or member variable and refer to it for each new number.
Second, you have to pass a min and a max to your RandomNumber method.
Well, your code doesn't match the error, but look at this:
private void btnPlay_Click(object sender, EventArgs e)
{
RandomNumber();
}
private void RandomNumber(int min, int max)
{
int num = new Random().Next(min, max);
lblPickFive_1.Text = num.ToString();
}
RandomNumber has two parameters, min and max. You haven't specified any in the call inside btnPlay_Click. That's what the compiler is complaining about. Change the call to something like:
RandomNumber(5, 10);
Even when that's fixed, you shouldn't create a new instance of Random each time. As it happens, it's unlikely to cause problems in this particular case as it's triggered by a user action, but you should read my article on random numbers to see what the problem is and how to avoid it.
You need to pass in values:
private void btnPlay_Click(object sender, EventArgs e)
{
RandomNumber();
}
should be:
private void btnPlay_Click(object sender, EventArgs e)
{
RandomNumber(0, 50000);
}
Your RandomNumber method takes two arguments.
If you want to call the method, you need to pass two arguments.
You're calling RandomNumber(); in btnPlay_Click but the RandomNumber method requires min and max.
Setup one Random object and initialize it once.
class Form1
{
...
Random rnd = new Random();
}
then to use it every time it is needed
void RandomNumber(int min, int max)
{
int num = rnd.Next(min, max);
...
}
What happens everytime you call new() it re-seeds the random number and you may end up with the same numbers over and over. I have had this happend to me and it killed me

Categories

Resources