How to assign a variable/integer to a image? [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm super new to c# and i have got a problem i have been trying to figure out for the past couple of days anyways i am trying to make a blackjack game but i cant figure out for the life of me how to associate the images of the random cards that show up in the picture box's to a variable/integer so i can make a function to add the values of the cards, if y'all could give me some ideas that would be great!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
namespace pokerapp
{
public partial class pokergame : Form
{
//Card Varibles
int card1 = 10;
int card2 = 10;
int card3 = 10;
int card4 = 10;
int card5 = 10;
int card6 = 10;
int card7 = 10;
int card8 = 10;
int card9 = 10;
int card10 = 10;
int card11 = 10;
int card12 = 10;
int card13 = 10;
int card14 = 10;
int card15 = 10;
int card16 = 10;
int card17 = 10;
int card18 = 10;
int card19 = 10;
int card20 = 10;
int card21 = 9;
int card22 = 9;
int card23 = 9;
int card24 = 9;
int card25 = 8;
int card26 = 8;
int card27 = 8;
int card28 = 8;
int card29 = 7;
int card30 = 7;
int card31 = 7;
int card32 = 7;
int card33 = 6;
int card34 = 6;
int card35 = 6;
int card36 = 6;
int card37 = 5;
int card38 = 5;
int card39 = 5;
int card40 = 5;
int card41 = 4;
int card42 = 4;
int card43 = 4;
int card44 = 4;
int card45 = 3;
int card46 = 3;
int card47 = 3;
int card48 = 3;
int card49 = 2;
int card50 = 2;
int card51 = 2;
int card52 = 2;
public pokergame()
{
InitializeComponent();
}
Random random = new Random();
List<Image> images = new List<Image>();
public void button1_Click(object sender, EventArgs e)
{
pictureBox1.Image = images[random.Next(0, images.Count - 1)];
pictureBox2.Image = images[random.Next(0, images.Count - 1)];
pictureBox14.Image = images[random.Next(0, images.Count - 1)];
pictureBox13.Image = images[random.Next(0, images.Count - 1)];
button2.Enabled = true;
button1.Enabled = false;
}
public void pokergame_Load(object sender, EventArgs e)
{
pictureBox3.Visible = false;
pictureBox4.Visible = false;
pictureBox5.Visible = false;
pictureBox6.Visible = false;
pictureBox7.Visible = false;
pictureBox8.Visible = false;
pictureBox9.Visible = false;
pictureBox10.Visible = false;
pictureBox11.Visible = false;
pictureBox12.Visible = false;
//label1.Text = Form1.textBox1.text;
button1.Enabled = true;
button2.Enabled = false;
images.Add(pokerapp.Properties.Resources._1);
images.Add(pokerapp.Properties.Resources._2);
images.Add(pokerapp.Properties.Resources._3);
images.Add(pokerapp.Properties.Resources._4);
images.Add(pokerapp.Properties.Resources._5);
images.Add(pokerapp.Properties.Resources._6);
images.Add(pokerapp.Properties.Resources._7);
images.Add(pokerapp.Properties.Resources._8);
images.Add(pokerapp.Properties.Resources._9);
images.Add(pokerapp.Properties.Resources._10);
images.Add(pokerapp.Properties.Resources._11);
images.Add(pokerapp.Properties.Resources._12);
images.Add(pokerapp.Properties.Resources._13);
images.Add(pokerapp.Properties.Resources._14);
images.Add(pokerapp.Properties.Resources._15);
images.Add(pokerapp.Properties.Resources._16);
images.Add(pokerapp.Properties.Resources._17);
images.Add(pokerapp.Properties.Resources._18);
images.Add(pokerapp.Properties.Resources._19);
images.Add(pokerapp.Properties.Resources._20);
images.Add(pokerapp.Properties.Resources._21);
images.Add(pokerapp.Properties.Resources._22);
images.Add(pokerapp.Properties.Resources._23);
images.Add(pokerapp.Properties.Resources._24);
images.Add(pokerapp.Properties.Resources._25);
images.Add(pokerapp.Properties.Resources._26);
images.Add(pokerapp.Properties.Resources._27);
images.Add(pokerapp.Properties.Resources._28);
images.Add(pokerapp.Properties.Resources._29);
images.Add(pokerapp.Properties.Resources._30);
images.Add(pokerapp.Properties.Resources._31);
images.Add(pokerapp.Properties.Resources._32);
images.Add(pokerapp.Properties.Resources._33);
images.Add(pokerapp.Properties.Resources._34);
images.Add(pokerapp.Properties.Resources._35);
images.Add(pokerapp.Properties.Resources._36);
images.Add(pokerapp.Properties.Resources._37);
images.Add(pokerapp.Properties.Resources._38);
images.Add(pokerapp.Properties.Resources._39);
images.Add(pokerapp.Properties.Resources._40);
images.Add(pokerapp.Properties.Resources._41);
images.Add(pokerapp.Properties.Resources._42);
images.Add(pokerapp.Properties.Resources._43);
images.Add(pokerapp.Properties.Resources._44);
images.Add(pokerapp.Properties.Resources._45);
images.Add(pokerapp.Properties.Resources._46);
images.Add(pokerapp.Properties.Resources._47);
images.Add(pokerapp.Properties.Resources._48);
images.Add(pokerapp.Properties.Resources._49);
images.Add(pokerapp.Properties.Resources._50);
images.Add(pokerapp.Properties.Resources._51);
images.Add(pokerapp.Properties.Resources._52);
}
int hitButtonClickCount = 0;
public void button2_Click(object sender, EventArgs e)
{
Random random = new Random();
if (hitButtonClickCount == 0)
{
pictureBox3.Visible = true;
pictureBox3.Image = images[random.Next(0, images.Count - 1)];
//pictureBox3.Location = new Point(86, 130);
hitButtonClickCount++;
}
else if (hitButtonClickCount == 1)
{
pictureBox4.Visible = true;
pictureBox4.Image = images[random.Next(0, images.Count - 1)];
//pictureBox4.Location = new Point(100, 140);
hitButtonClickCount++;
}
else if (hitButtonClickCount == 2)
{
pictureBox5.Visible = true;
pictureBox5.Image = images[random.Next(0, images.Count - 1)];
// pictureBox5.Location = new Point(241, 197);
hitButtonClickCount++;
}
else if (hitButtonClickCount == 3)
{
pictureBox6.Visible = true;
pictureBox6.Image = images[random.Next(0, images.Count - 1)];
// pictureBox5.Location = new Point(241, 197);
hitButtonClickCount++;
}
else if (hitButtonClickCount == 4)
{
pictureBox7.Visible = true;
pictureBox7.Image = images[random.Next(0, images.Count - 1)];
// pictureBox5.Location = new Point(241, 197);
hitButtonClickCount++;
button2.Enabled = false;
}
}
private void button3_Click(object sender, EventArgs e)
{
pictureBox1.Image = null;
pictureBox2.Image = null;
pictureBox3.Image = null;
pictureBox4.Image = null;
pictureBox5.Image = null;
pictureBox6.Image = null;
pictureBox7.Image = null;
pictureBox8.Image = null;
pictureBox9.Image = null;
pictureBox10.Image = null;
pictureBox11.Image = null;
pictureBox12.Image = null;
pictureBox13.Image = null;
pictureBox14.Image = null;
pictureBox3.Visible = false;
pictureBox4.Visible = false;
pictureBox5.Visible = false;
pictureBox6.Visible = false;
pictureBox7.Visible = false;
pictureBox8.Visible = false;
pictureBox9.Visible = false;
pictureBox10.Visible = false;
pictureBox11.Visible = false;
pictureBox12.Visible = false;
button1.Enabled = true;
button2.Enabled = false;
hitButtonClickCount = 0;
}
public void Points()
{
if (pictureBox1.Image == images[0])
{
label3.Text = "1/10";
}
}
private void button4_Click(object sender, EventArgs e)
{
button2.Enabled = false;
button4.Enabled = false;
}
}
}

First off, try and do some reading up on arrays and Lists. This will help shorten your code and make it easier for you to read.
With your question.
Try putting the cards in an array. and then pick a random number instead of a random image. Use this random number to select the correct corresponding card image and card value. You will only need to ensure that they are correctly lined up with each other.
You can access the addresses of a list the same way you would an array.
List.Items[random_int]

Related

Design an algorithm for guessing a card number

I am making a card guessing game.there are 100 cards place in 10rows and 10 columns each card with a number and user have to find a number he is thinking of. i want to devise an algorithm to determine whether a given number is written on one of the cards by turning up less than 20 cards.I hav created the buttons dynamically, now im having hard time making a logic to search through them.This is my code.
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
int rememberlast = 0, move = 0;
object savelastobject;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
int sizee = 50, where = 0;
this.Height = 0;
this.Width = 0;
var generatedNum = new List<int>();
var random = new Random();
while (generatedNum.Count < 100)
{
var tempo = random.Next(0, 100);
if (generatedNum.Contains(tempo)) continue;
generatedNum.Add(tempo);
}
char[] text2 = text.ToCharArray();
for (int x = 0; x < 10; x++)
{
for (int y = 0; y < 10; y++)
{
Button ta = new Button();
ta.Name = x.ToString()+y.ToString();
ta.Width = sizee;
ta.Height = sizee;
ta.Tag = generatedNum[where];
where++;
ta.BackColor = Color.Red;
ta.Location = new Point(70 * y, 70 * x);
Controls.Add(ta);
ta.Click += new System.EventHandler(this.button_Click);
this.Width += 90 * x / 13;
this.Height += 90 * x / 8;
}
}
}
private void button_Click(object sender, EventArgs e)
{
Control me = (Control)sender;
rememberlast = int.Parse(me.Tag.ToString());
savelastobject = me;
me.Text = me.Tag.ToString();
me.Enabled = true;
me.BackColor = Color.Gray;
move++;
label2.Text = move.ToString();
me.Enabled = true;
me.Text = me.Tag.ToString();
me.BackColor = Color.Gray;
me.Refresh();
Thread.Sleep(1000);
if (move == 20)
{
MessageBox.Show("Total Moves Consumed");
Application.Restart();
}
if (me.Tag.ToString() == textBox1.Text)
{
//Control him = (Control)savelastobject;
//him.BackColor = Color.LightBlue;
me.BackColor = Color.LightBlue;
MessageBox.Show("You Win");
Application.Restart();
}
}
}
}

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in InAirSignature.exe

I am doing a program with Emgu.CV in C#
and i receive this error when compiling
An unhandled exception of type 'System.IO.FileNotFoundException'
occurred in InAirSignature.exe
Additional information: Could not load file or assembly 'Emgu.CV.UI,
Version=2.9.0.1922, Culture=neutral, PublicKeyToken=7281126722ab4438'
or one of its dependencies. The system cannot find the file specified.
any ideas how to solve?
for my coding, a webcam is needed.
below is my coding.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.GPU;
using Emgu.Util;
using Emgu.CV.Structure;
using Emgu.CV.UI;
using Emgu.CV.CvEnum;
using System.Diagnostics;
using System.Windows.Forms.DataVisualization.Charting;
using Emgu.CV.ML.Structure;
using Emgu.CV.ML;
using System.IO;
namespace InAirSignature
{
public partial class Main : Form
{
private Capture capture;
private Rectangle roi;
private Bgr redOrGreen;
private const int NUMBERS_OF_FRAMES = 90,
NUMBERS_OF_SIGN = 6,
NUMBERS_OF_FEATURES = 3, // X Y Averange
FEATURE_X = 0,
FEATURE_Y = 1,
TEST = NUMBERS_OF_SIGN - 1,
NUMBERS_OF_NEURONS = 15;
private const int frameHeight = 640;
private const int frameWidth = 480;
private List<Image<Gray, Byte>> imgGrayBuffer = new List<Image<Gray, Byte>>();
private List<int> pointX = new List<int>();
private List<int> pointY = new List<int>();
private int[][][] pointsOfSign, distanceBetweenPoints;
private double[] finalAverage;
private int[][] pointsOfSignReference;
private int[] distanceBetweenPointsForRefenceAndTest;
private int[] classes = {0,0,0,0,1,1,1,1,1,1};
private int resultMode = 0;
private int recordSign = 0;
private bool record = false;
private int counter = 0;
private Stopwatch stopWatch;
private const string SYSTEM_MESSAGE = "System Message: ",
WELCOME_MESSAGE = "Welcome! ";
Matrix<int> layerSize;
MCvANN_MLP_TrainParams parameters;
ANN_MLP network;
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Form /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#region Form
public Main()
{
InitializeComponent();
#region Initialize graph
chartX.Series.Add("X1");
chartX.Series.Add("X2");
chartX.Series.Add("X3");
chartX.Series.Add("X4");
chartX.Series.Add("X5");
chartX.Series.Add("Xtest");
chartX.Series.Add("Xref");
chartY.Series.Add("Y1");
chartY.Series.Add("Y2");
chartY.Series.Add("Y3");
chartY.Series.Add("Y4");
chartY.Series.Add("Y5");
chartY.Series.Add("Ytest");
chartY.Series.Add("Yref");
chartX.Series["X1"].Color = Color.Blue;
chartX.Series["X2"].Color = Color.Green;
chartX.Series["X3"].Color = Color.Red;
chartX.Series["X4"].Color = Color.Pink;
chartX.Series["X5"].Color = Color.Purple;
chartX.Series["Xtest"].Color = Color.Aqua;
chartX.Series["Xref"].Color = Color.BlueViolet;
chartY.Series["Y1"].Color = Color.Blue;
chartY.Series["Y2"].Color = Color.Green;
chartY.Series["Y3"].Color = Color.Red;
chartY.Series["Y4"].Color = Color.Pink;
chartY.Series["Y5"].Color = Color.Purple;
chartY.Series["Ytest"].Color = Color.Aqua;
chartY.Series["Yref"].Color = Color.BlueViolet;
chartX.Series["X1"].ChartType = SeriesChartType.FastLine;
chartX.Series["X2"].ChartType = SeriesChartType.FastLine;
chartX.Series["X3"].ChartType = SeriesChartType.FastLine;
chartX.Series["X4"].ChartType = SeriesChartType.FastLine;
chartX.Series["X5"].ChartType = SeriesChartType.FastLine;
chartX.Series["Xtest"].ChartType = SeriesChartType.FastLine;
chartX.Series["Xref"].ChartType = SeriesChartType.FastLine;
chartY.Series["Y1"].ChartType = SeriesChartType.FastLine;
chartY.Series["Y2"].ChartType = SeriesChartType.FastLine;
chartY.Series["Y3"].ChartType = SeriesChartType.FastLine;
chartY.Series["Y4"].ChartType = SeriesChartType.FastLine;
chartY.Series["Y5"].ChartType = SeriesChartType.FastLine;
chartY.Series["Ytest"].ChartType = SeriesChartType.FastLine;
chartY.Series["Yref"].ChartType = SeriesChartType.FastLine;
#endregion
#region Initialize Neural Network
layerSize = new Matrix<int>(new int[] { NUMBERS_OF_FEATURES, NUMBERS_OF_NEURONS, 1 });
parameters = new MCvANN_MLP_TrainParams();
parameters.term_crit = new MCvTermCriteria(10, 1.0e-8);
parameters.train_method = Emgu.CV.ML.MlEnum.ANN_MLP_TRAIN_METHOD.BACKPROP;
parameters.bp_dw_scale = 0.1;
parameters.bp_moment_scale = 0.1;
network = new ANN_MLP(layerSize, Emgu.CV.ML.MlEnum.ANN_MLP_ACTIVATION_FUNCTION.SIGMOID_SYM, 1.0, 1.0);
#endregion
#region Initialize camera
capture = new Capture();
capture.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT, frameHeight);
capture.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_WIDTH, frameWidth);
#endregion
initializeData();
roi = new Rectangle(338, 2, 300, 300);
redOrGreen = new Bgr(Color.Red);
lblSM.Text = SYSTEM_MESSAGE + WELCOME_MESSAGE;
updateResult();
updateGraph();
Application.Idle += processFrame;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
capture.Stop();
}
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Button /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#region Button
private void btnSign_Click(object sender, EventArgs e)
{
stopWatch = Stopwatch.StartNew();
record = true;
redOrGreen = new Bgr(Color.LightGreen);
if (sender == btnSign1)
recordSign = 1;
else if (sender == btnSign2)
recordSign = 2;
else if (sender == btnSign3)
recordSign = 3;
else if (sender == btnSign4)
recordSign = 4;
else if (sender == btnSign5)
recordSign = 5;
else
recordSign = 6;
}
private void btnPredict_Click(object sender, EventArgs e)
{
float predicted = predict(new int[,] { { distanceBetweenPointsForRefenceAndTest[0], distanceBetweenPointsForRefenceAndTest[1], distanceBetweenPointsForRefenceAndTest[2] } }, network);
string result;
if (predicted < Convert.ToDouble(lblThreshold.Text))
result = "Success";
else
result = "Fail";
lblSM.Text = SYSTEM_MESSAGE + "Matching result - " + result + ", value: " + predicted.ToString();
}
private void btnSave_Click(object sender, EventArgs e)
{
try
{
if (tbId.Text == "")
throw new Exception();
saveSignReference();
network.Save(tbId.Text);
lblSM.Text = SYSTEM_MESSAGE + "Saved";
}
catch
{
lblSM.Text = SYSTEM_MESSAGE + "ID blank";
}
}
private void btnLoad_Click(object sender, EventArgs e)
{
try
{
if (tbId.Text == "")
throw new Exception();
loadSignReference();
network.Load(tbId.Text);
lblSM.Text = SYSTEM_MESSAGE + "Loaded";
btnVerify.Enabled = true;
btnSave.Enabled = true;
cbAuto.Enabled = true;
updateGraph();
}
catch
{
lblSM.Text = SYSTEM_MESSAGE + "Invalid ID";
}
}
private void btnTrainNN_Click(object sender, EventArgs e)
{
btnVerify.Enabled = true;
btnSave.Enabled = true;
cbAuto.Enabled = true;
trainNN();
}
private void btnClear_Click(object sender, EventArgs e)
{
initializeData();
updateGraph();
updateResult();
calculateResult();
rbS1.PerformClick();
}
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Check Box /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#region Check Box
private void cbBinaryImage_CheckedChanged(object sender, EventArgs e)
{
ibBinaryImage.Visible = !ibBinaryImage.Visible;
}
private void cbResult_CheckedChanged(object sender, EventArgs e)
{
pnlResult.Visible = !pnlResult.Visible;
}
private void cbSign_CheckedChanged(object sender, EventArgs e)
{
if (sender == cbSign1)
{
chartX.Series["X1"].Enabled = !chartX.Series["X1"].Enabled;
chartY.Series["Y1"].Enabled = !chartY.Series["Y1"].Enabled;
}
else if (sender == cbSign2)
{
chartX.Series["X2"].Enabled = !chartX.Series["X2"].Enabled;
chartY.Series["Y2"].Enabled = !chartY.Series["Y2"].Enabled;
}
else if (sender == cbSign3)
{
chartX.Series["X3"].Enabled = !chartX.Series["X3"].Enabled;
chartY.Series["Y3"].Enabled = !chartY.Series["Y3"].Enabled;
}
else if (sender == cbSign4)
{
chartX.Series["X4"].Enabled = !chartX.Series["X4"].Enabled;
chartY.Series["Y4"].Enabled = !chartY.Series["Y4"].Enabled;
}
else if (sender == cbSign5)
{
chartX.Series["X5"].Enabled = !chartX.Series["X5"].Enabled;
chartY.Series["Y5"].Enabled = !chartY.Series["Y5"].Enabled;
}
else if (sender == cbSignRefer)
{
chartX.Series["Xref"].Enabled = !chartX.Series["Xref"].Enabled;
chartY.Series["Yref"].Enabled = !chartY.Series["Yref"].Enabled;
}
else
{
chartX.Series["Xtest"].Enabled = !chartX.Series["Xtest"].Enabled;
chartY.Series["Ytest"].Enabled = !chartY.Series["Ytest"].Enabled;
}
}
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Radio Button /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#region Radio Button
private void rbS_CheckedChanged(object sender, EventArgs e)
{
if (sender == rbS1)
resultMode = 0;
else if (sender == rbS2)
resultMode = 1;
else if (sender == rbS3)
resultMode = 2;
else if (sender == rbS4)
resultMode = 3;
else
resultMode = 4;
updateResult();
}
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Text Box /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
#region Text Box
private void tbId_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
btnLoad.PerformClick();
}
#endregion
//////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////// Function /////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
private void processFrame(object sender, EventArgs arg)
{
Image<Bgr, Byte> frame = capture.QueryFrame().Flip(FLIP.HORIZONTAL);
Image<Bgr, Byte> frameCrop = frame.Copy(new Rectangle(338, 2, 300, 300)); // copy a crop
Image<Gray, Byte> frameBinary;
if (counter == (NUMBERS_OF_FRAMES - 2))
redOrGreen = new Bgr(Color.Red);
frame.Draw(roi, redOrGreen, 2);
frameBinary = ImageProcessing.getSkin(frameCrop);
if (record == true)
{
imgGrayBuffer.Add(frameBinary);
counter++;
if (counter == NUMBERS_OF_FRAMES)
{
while (imgGrayBuffer.Count() > 0)
{
Point point = ImageProcessing.getHighestPoint(imgGrayBuffer.ElementAt(0));
imgGrayBuffer.RemoveAt(0);
pointX.Add(point.X);
pointY.Add(point.Y);
}
pointsOfSign[recordSign - 1][FEATURE_X] = pointX.ToArray();
pointsOfSign[recordSign - 1][FEATURE_X] = normalizeSize(pointsOfSign[recordSign - 1][FEATURE_X]);
pointsOfSign[recordSign - 1][FEATURE_X] = normalizePosition(pointsOfSign[recordSign - 1][FEATURE_X]);
pointsOfSign[recordSign - 1][FEATURE_Y] = pointY.ToArray();
pointsOfSign[recordSign - 1][FEATURE_Y] = normalizeSize(pointsOfSign[recordSign - 1][FEATURE_Y]);
pointsOfSign[recordSign - 1][FEATURE_Y] = normalizePosition(pointsOfSign[recordSign - 1][FEATURE_Y]);
pointX.Clear();
pointY.Clear();
calculateResult();
updateResult();
updateGraph();
record = false;
stopWatch.Stop();
lblSM.Text = SYSTEM_MESSAGE + "Time taken => " + stopWatch.Elapsed.TotalSeconds.ToString() + " seconds.";
if (cbAuto.Checked == true && recordSign == 6)
btnVerify.PerformClick();
recordSign = 0;
counter = 0;
}
}
ibMain.Image = frame;
if(cbBinaryImage.Checked == true)
ibBinaryImage.Image = frameBinary;
}
private int[] normalizePosition(int[] position)
{
int min = int.MaxValue,
max = int.MinValue;
for (int i = 0; i < position.Count(); i++)
{
if (position[i] > max)
max = position[i];
if (position[i] < min)
min = position[i];
}
int midPoint = (min + max) / 2;
for (int i = 0; i < position.Count(); i++)
position[i] -= midPoint;
return position;
}
private int[] normalizeSize(int[] position)
{
const int targetSize = 300;
int min = int.MaxValue,
max = int.MinValue;
for (int i = 0; i < position.Count(); i++)
{
if (position[i] > max)
max = position[i];
if (position[i] < min)
min = position[i];
}
int height = max - min;
if (height != 0)
height = targetSize / height;
for (int i = 0; i < position.Count(); i++)
position[i] *= height;
return position;
}
private void updateGraph()
{
foreach (var series in chartX.Series)
series.Points.Clear();
foreach (var series in chartY.Series)
series.Points.Clear();
for (int i = 0; i < NUMBERS_OF_FRAMES; i++)
{
chartX.Series["X1"].Points.AddXY
(i, pointsOfSign[0][FEATURE_X][i]);
chartX.Series["X2"].Points.AddXY
(i, pointsOfSign[1][FEATURE_X][i]);
chartX.Series["X3"].Points.AddXY
(i, pointsOfSign[2][FEATURE_X][i]);
chartX.Series["X4"].Points.AddXY
(i, pointsOfSign[3][FEATURE_X][i]);
chartX.Series["X5"].Points.AddXY
(i, pointsOfSign[4][FEATURE_X][i]);
chartX.Series["Xref"].Points.AddXY
(i, pointsOfSignReference[0][i]);
chartX.Series["Xtest"].Points.AddXY
(i, pointsOfSign[5][FEATURE_X][i]);
chartY.Series["Y1"].Points.AddXY
(i, pointsOfSign[0][FEATURE_Y][i]);
chartY.Series["Y2"].Points.AddXY
(i, pointsOfSign[1][FEATURE_Y][i]);
chartY.Series["Y3"].Points.AddXY
(i, pointsOfSign[2][FEATURE_Y][i]);
chartY.Series["Y4"].Points.AddXY
(i, pointsOfSign[3][FEATURE_Y][i]);
chartY.Series["Y5"].Points.AddXY
(i, pointsOfSign[4][FEATURE_Y][i]);
chartY.Series["Yref"].Points.AddXY
(i, pointsOfSignReference[1][i]);
chartY.Series["Ytest"].Points.AddXY
(i, pointsOfSign[5][FEATURE_Y][i]);
}
}
private void calculateResult()
{
int average = 0;
for (int i = 0; i < NUMBERS_OF_SIGN - 1; i++)
for (int j = 0; j < NUMBERS_OF_SIGN - 1; j++)
{
for (int k = 0; k < NUMBERS_OF_FEATURES - 1; k++)
{
distanceBetweenPoints[i][j][k] = DTW.Distance(pointsOfSign[i][k], pointsOfSign[j][k]);
average += distanceBetweenPoints[i][j][k];
}
distanceBetweenPoints[i][j][NUMBERS_OF_FEATURES - 1] = average / 2;
average = 0;
}
for (int i = 0; i < NUMBERS_OF_SIGN -1; i++)
{
finalAverage[i] = 0.0;
for (int j = 0; j < NUMBERS_OF_SIGN; j++)
finalAverage[i] += distanceBetweenPoints[i][j][NUMBERS_OF_FEATURES - 1];
finalAverage[i] /= NUMBERS_OF_SIGN - 2;
}
average = 0;
for (int k = 0; k < NUMBERS_OF_FEATURES - 1; k++)
{
distanceBetweenPointsForRefenceAndTest[k] = DTW.Distance(pointsOfSignReference[k], pointsOfSign[TEST][k]);
average += distanceBetweenPointsForRefenceAndTest[k];
}
distanceBetweenPointsForRefenceAndTest[NUMBERS_OF_FEATURES - 1] = average / 2;
}
private void updateResult()
{
tbResult1X.Text = distanceBetweenPoints[resultMode][0][0].ToString();
tbResult1Y.Text = distanceBetweenPoints[resultMode][0][1].ToString();
tbResult1A.Text = distanceBetweenPoints[resultMode][0][2].ToString();
tbResult2X.Text = distanceBetweenPoints[resultMode][1][0].ToString();
tbResult2Y.Text = distanceBetweenPoints[resultMode][1][1].ToString();
tbResult2A.Text = distanceBetweenPoints[resultMode][1][2].ToString();
tbResult3X.Text = distanceBetweenPoints[resultMode][2][0].ToString();
tbResult3Y.Text = distanceBetweenPoints[resultMode][2][1].ToString();
tbResult3A.Text = distanceBetweenPoints[resultMode][2][2].ToString();
tbResult4X.Text = distanceBetweenPoints[resultMode][3][0].ToString();
tbResult4Y.Text = distanceBetweenPoints[resultMode][3][1].ToString();
tbResult4A.Text = distanceBetweenPoints[resultMode][3][2].ToString();
tbResult5X.Text = distanceBetweenPoints[resultMode][4][0].ToString();
tbResult5Y.Text = distanceBetweenPoints[resultMode][4][1].ToString();
tbResult5A.Text = distanceBetweenPoints[resultMode][4][2].ToString();
tbTotalA.Text = finalAverage[resultMode].ToString();
tbRatX.Text = distanceBetweenPointsForRefenceAndTest[0].ToString();
tbRatY.Text = distanceBetweenPointsForRefenceAndTest[1].ToString();
tbRatA.Text = distanceBetweenPointsForRefenceAndTest[2].ToString();
}
private float predict(int[,] testingSetInt, ANN_MLP network)
{
Matrix<float> testingSet = new Matrix<float>(Utility.arrayIntToFloat(testingSetInt)),
prediction = new Matrix<float>(1, 1);
network.Predict(testingSet, prediction);
return prediction.Data[0, 0];
}
private ANN_MLP trainNN(int[] trainingClassesInt, int[,] trainingSetInt)
{
int numbers_of_training_set = 4,
numbers_of_data = trainingSetInt.GetUpperBound(0) + 1;
Matrix<float> trainingSet = new Matrix<float>(Utility.arrayIntToFloat(trainingSetInt)),
trainingClasses = new Matrix<float>(Utility.arrayIntToFloat(trainingClassesInt));
Matrix<float> trainingSetPositive = trainingSet.GetRows(0, numbers_of_training_set, 1);
Matrix<float> trainingSetNegative = trainingSet.GetRows(numbers_of_training_set, numbers_of_data, 1);
Matrix<float> trainClassesPositive = trainingClasses.GetRows(0, numbers_of_training_set, 1);
Matrix<float> trainClassesNegative = trainingClasses.GetRows(numbers_of_training_set, numbers_of_data, 1);
ANN_MLP network = new ANN_MLP(layerSize, Emgu.CV.ML.MlEnum.ANN_MLP_ACTIVATION_FUNCTION.SIGMOID_SYM, 1.0, 1.0);
network.Train(trainingSet, trainingClasses, null, (Matrix<int>)null, parameters, Emgu.CV.ML.MlEnum.ANN_MLP_TRAINING_FLAG.DEFAULT);
return network;
}
private void trainNN()
{
// Getting the most closest signature
int index = 0;
for (int i = 1; i < NUMBERS_OF_SIGN - 1; i++)
if (finalAverage[index] > finalAverage[i])
index = i;
lblSM.Text = SYSTEM_MESSAGE + "Sign # no." + (index + 1).ToString() + " is the reference now!";
for (int i = 0; i < NUMBERS_OF_FEATURES - 1; i++)
pointsOfSignReference[i] = pointsOfSign[index][i];
int total_training_data = 10; // 4 positive, 6 negative
int total_features_for_training = 3; // dtw of x, dtw of y, width of sign
int[,] trainingSet = new int[total_training_data, total_features_for_training];
// Get the distance (x and y) between closest signature and the rest of signature into training set
// Feature 0 and 1 => dtw of x, dtw of y
for (int i = 0, current = 0; i < NUMBERS_OF_SIGN - 1; i++)
{
if (i != index)
{
for (int j = 0; j < NUMBERS_OF_FEATURES; j++)
trainingSet[current, j] = distanceBetweenPoints[i][index][j];
current++;
}
}
// Generate negative data
int[] max_value = new int[NUMBERS_OF_FEATURES];
int[] min_value = new int[NUMBERS_OF_FEATURES];
for (int i = 0; i < NUMBERS_OF_SIGN - 1; i++)
{
for (int j = 0; j < NUMBERS_OF_FEATURES && i != index; j++)
{
if (max_value[j] < distanceBetweenPoints[i][index][j])
max_value[j] = distanceBetweenPoints[i][index][j];
if (min_value[j] > distanceBetweenPoints[i][index][j])
min_value[j] = distanceBetweenPoints[i][index][j];
}
}
Random random = new Random();
In your project, right click on the References, then look for the Emgu.CV.UI assembly and select it.

The type or namespace name 'Neodynamic' could not be found (are you missing a using directive or an assembly reference?)

i want to use the neodynamic image draw sdk and keep getting this error on build i have searched for solutions but none work i have this is my current code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevPro.Data.Enums;
using YGOPro_Launcher.CardDatabase;
using System.IO;
using System.Reflection;
using System.Data.SQLite;
using DevPro_CardManager.Properties;
using Neodynamic.SDK;
namespace Outlaws_CardManager
{
public partial class cardmaker : Form
{
public cardmaker()
{
InitializeComponent();
TopLevel = false;
Dock = DockStyle.Fill;
Visible = true;
}
private void GenerateCard()
{
//Get the info to create the card
string cardname = "";
string cardid = "";
string level = "";
string race = "";
string attribute = "";
string atk = "";
string def = "";
string type1 = "";
string type2 = "";
string stype = "";
string traptype = "";
string mainpicture = "";
string layout = "Left";
if (!String.IsNullOrEmpty(CardName.Text))
{
cardname = CardName.Text;
}
if (!String.IsNullOrEmpty(CardID.Text))
{
cardid = CardID.Text;
}
if (!String.IsNullOrEmpty(ATK.Text))
{
atk = ATK.Text;
}
if (!String.IsNullOrEmpty(DEF.Text))
{
def = DEF.Text;
}
ImageDraw imgDraw = new ImageDraw();
//Basic settings for Card
imgDraw.Canvas.AutoSize = false;
imgDraw.ImageFormat = ImageDrawFormat.Png;
//Set card size
imgDraw.Canvas.Width = 400;
imgDraw.Canvas.Height = 250;
//Create main decorative shape element
RectangleShapeElement rect1 = new RectangleShapeElement();
rect1.X = 10;
rect1.Y = 10;
rect1.Width = 380;
rect1.Height = 230;
rect1.Roundness = 20;
rect1.StrokeWidth = 0;
//Set background
rect1.Fill.BackgroundColor = Color.Black;
//Add element to output image
imgDraw.Elements.Add(rect1);
//Create top decorative shape element
RectangleShapeElement rect2 = new RectangleShapeElement();
rect2.X = 20;
rect2.Y = 20;
rect2.Width = 360;
rect2.Height = 170;
rect2.Roundness = 10;
rect2.StrokeWidth = 0;
rect2.Fill.BackgroundColor = Color.White;
//Add element to output image
imgDraw.Elements.Add(rect2);
//Create bottom decorative shape element
RectangleShapeElement rect3 = new RectangleShapeElement();
rect3.X = 30;
rect3.Y = 130;
rect3.Width = 340;
rect3.Height = 100;
rect3.Roundness = 10;
rect3.StrokeWidth = 1;
rect3.StrokeFill.BackgroundColor = Color.Black;
rect3.Fill.BackgroundColor = Color.White;
//Add element to output image
imgDraw.Elements.Add(rect3);
//Create an ImageElement to wrap the user logo
if (mainpicture.Length > 0 && System.IO.File.Exists(mainpicture))
{
ImageElement imgElemLogo = new ImageElement();
//Get user logo from disk
imgElemLogo.Source = ImageSource.File;
imgElemLogo.SourceFile = mainpicture;
//Logo Layout
if (layout == "Right")
{
imgElemLogo.X = 40;
imgElemLogo.Y = 40;
}
else
{
imgElemLogo.X = 400 - (50 + 40); //Canvas Width - (Logo Width + X Margin)
imgElemLogo.Y = 40;
}
//Apply Resize logo
Resize resizeLogo = new Resize();
resizeLogo.Width = 50;
resizeLogo.LockAspectRatio = LockAspectRatio.WidthBased;
imgElemLogo.Actions.Clear();
imgElemLogo.Actions.Add(resizeLogo);
//Add element to output image
imgDraw.Elements.Add(imgElemLogo);
}
//Create TextElement objects for each fields
if (cardname.Length > 0)
{
TextElement txtElemName = new TextElement();
txtElemName.AutoSize = false;
txtElemName.Font.Name = "Arial";
txtElemName.Font.Size = 14f;
txtElemName.Font.Unit = FontUnit.Point;
txtElemName.Font.Bold = true;
txtElemName.ForeColor = System.Drawing.Color.Black;
txtElemName.Text = cardname;
txtElemName.TextQuality = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
txtElemName.X = 40;
txtElemName.Y = 40;
txtElemName.Width = 320;
txtElemName.Height = 20;
if (layout == "Left")
{
txtElemName.TextAlignment = ContentAlignment.MiddleLeft;
}
else
{
txtElemName.TextAlignment = ContentAlignment.MiddleRight;
}
//Add element to output image
imgDraw.Elements.Add(txtElemName);
}
if (cardid.Length > 0)
{
TextElement txtElemJob = new TextElement();
txtElemJob.AutoSize = false;
txtElemJob.Font.Name = "Arial";
txtElemJob.Font.Size = 10f;
txtElemJob.Font.Unit = FontUnit.Point;
txtElemJob.ForeColor = System.Drawing.Color.Black;
txtElemJob.Text = cardid;
txtElemJob.TextQuality = System.Drawing.Text.TextRenderingHint.AntiAlias;
txtElemJob.X = 40;
txtElemJob.Y = 64;
txtElemJob.Width = 320;
txtElemJob.Height = 14;
if (layout == "Left")
{
txtElemJob.TextAlignment = ContentAlignment.MiddleLeft;
}
else
{
txtElemJob.TextAlignment = ContentAlignment.MiddleRight;
}
//Add element to output image
imgDraw.Elements.Add(txtElemJob);
}
if (atk.Length > 0)
{
TextElement txtElemAddress = new TextElement();
txtElemAddress.AutoSize = false;
txtElemAddress.Font.Name = "Times New Roman";
txtElemAddress.Font.Italic = true;
txtElemAddress.Font.Size = 11f;
txtElemAddress.Font.Unit = FontUnit.Point;
txtElemAddress.ForeColor = System.Drawing.Color.Black;
txtElemAddress.Text = atk + "\n" + race;
txtElemAddress.TextQuality = System.Drawing.Text.TextRenderingHint.AntiAlias;
txtElemAddress.X = 40;
txtElemAddress.Y = 130;
txtElemAddress.Width = 160;
txtElemAddress.Height = 50;
if (layout == "Left")
{
txtElemAddress.TextAlignment = ContentAlignment.MiddleLeft;
}
else
{
txtElemAddress.TextAlignment = ContentAlignment.MiddleRight;
}
//Add element to output image
imgDraw.Elements.Add(txtElemAddress);
}
if (attribute.Length > 0 || atk.Length > 0)
{
TextElement txtElemPhone = new TextElement();
txtElemPhone.AutoSize = false;
txtElemPhone.Font.Name = "Georgia";
txtElemPhone.Font.Size = 10f;
txtElemPhone.Font.Unit = FontUnit.Point;
txtElemPhone.ForeColor = System.Drawing.Color.Black;
txtElemPhone.Text = "Phone: " + attribute + "\n" + atk;
txtElemPhone.TextQuality = System.Drawing.Text.TextRenderingHint.AntiAlias;
txtElemPhone.X = 200;
txtElemPhone.Y = 180;
txtElemPhone.Width = 160;
txtElemPhone.Height = 50;
if (layout == "Right")
{
txtElemPhone.TextAlignment = ContentAlignment.MiddleLeft;
}
else
{
txtElemPhone.TextAlignment = ContentAlignment.MiddleRight;
}
//Add element to output image
imgDraw.Elements.Add(txtElemPhone);
}
//generate image card and preview it
CardImg.Image = imgDraw.GetOutputImage();
}
}
}
has anyone had a problem like this before please explain how fixed.
Such problems might occur if your Project's Target-Framework and your referenced assembly framework version are incompatible.
So as I may presume, you should take the following steps:
Right-Click on your Project -> Properties -> Target Framework -> Make Sure it is not set on Client Profile and if it does than choose .NET Framework 4 or 4.5 (according to the referenced-assembly targeted FW).
Update: Here is a snapshot of the settings

Head First C# Lab1 A Day at the Races called method not executing

I have a problem with the greyhound application that I have created. when I use the radio button to select who is placing a bet (Say Bob) and put his bet amount to 10 on dog number 4, (see image #1) when I click Bets, to update the 'Bob hasnt placed any bets' label with the description() method I get an error (see image #2)
What should happen is where it says "bob hasnt placed any bets" it should now read "bob bets 10 bucks on dog # 4. I have established this is failing due to the bettor returning NULL, but I cannot work out why this is when Bettor is referencing the Guy class which contains the bettor's name.
On a side notem when the race finishes and if Bob wins, he is note getting paid so either the PayOut() or Collect() methods are not working either.
Below are my 3 classes and my Form1.cs
Greyhound.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Drawing;
using System.Windows.Forms;
namespace A_Day_at_the_Races
{
public class Greyhound
{
public int StartingPosition; //Where my PictureBox starts
public int RacetrackLength; // How long the racetrack is
public PictureBox MyPictureBox = null; //My PictureBox object
public int Location = 0; // My Location on the racetrack
public Random Randomizer; // An instance of Random
public bool Run()
{
//1. Move forward either 1,2,3 or 4 spaces at random
int moveforward = Randomizer.Next(1, 4); // declare an int called 'moveforward' will move forward 1,2,3 or 4 spaces at random
//2. Update the position of my PictureBox on the form
Point p = MyPictureBox.Location; // current location of the picture of the greyhound
p.X += moveforward;
MyPictureBox.Location = p;
//3. Return true if I won the race
if (p.X >= RacetrackLength)
return true;
else
return false;
}
public void TakeStartingPosition()
{
//Reset my location to the start line
//MyPictureBox.Location.X = StartingPosition;
StartingPosition = 0;
}
}
}
Guy.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace A_Day_at_the_Races
{
public class Guy
{
public string Name; // The guy's name
public Bet MyBet = null; // An instance of bet() that has how much he's betting
public int Cash; // How much cash he has
// these last two fields are the guy's GUI controls on the form
public RadioButton MyRadioButton; // My RadioButton
public Label MyLabel; // My Label
public void UpdateLabels()
{
//1.Set my label to my bet's description,
if (MyBet == null)
MyLabel.Text = Name + " hasnt placed any bets";
else
MyLabel.Text = MyBet.GetDescription();
//2.Set the label on my radio button to show my cash ("Joe has 43 dollars")
MyRadioButton.Text = Name + " has " + Cash + " bucks";
}
public void ClearBet()
{
//1.Reset my bet so it's zero
MyBet = null;
}
//1.Place a new bet and store it in my bet field
//2.Return true if the guy had enough money to bet
public bool PlaceBet(int Amount, int Dog)
{
this.MyBet = new Bet();
if (Cash >= Amount)
{
Cash = Cash - Amount;
MyLabel = new Label();
MyBet.Amount = Amount;
MyBet.Dog = Dog;
UpdateLabels();
return true;
}
else
{
return false;
}
}
public void Collect(int Winner)
{
if (MyBet != null)
//1.Ask my bet to pay out (hint use the bet object to do the work)
Cash += MyBet.PayOut(Winner);
}
}
}
Bet.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace A_Day_at_the_Races
{
public class Bet
{
public int Amount; // The amount of cash that was bet
public int Dog; // The number of the dog the bet is on
public Guy Bettor; // The guy who placed the bet
public string GetDescription()
{
if (Amount > 0)
return Bettor.Name + " bets " + Amount + " bucks on dog #" + Dog;
else
return Bettor.Name + " hasnt placed a bet";
}
public int PayOut(int Winner)
{
if (Winner == Dog)
return Amount;
else
return -1 * Amount;
}
}
}
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace A_Day_at_the_Races
{
public partial class Form1 : Form
{
Guy[] Bettors;
Greyhound[] Dogs;
Guy CurrentBettor;
public Form1()
{
InitializeComponent();
Random Randomizer = new Random();
//initialise all my guys and dogs
Bettors = new Guy[3];
Dogs = new Greyhound[4];
//guys
Bettors[0] = new Guy();
Bettors[0].Name = "Joe";
Bettors[0].MyRadioButton = joeRadioButton;
Bettors[0].MyLabel = joeBetLabel;
Bettors[0].Cash = 50;
Bettors[0].UpdateLabels();
Bettors[1] = new Guy();
Bettors[1].Name = "Bob";
Bettors[1].MyRadioButton = bobRadioButton;
Bettors[1].MyLabel = bobBetLabel;
Bettors[1].Cash = 75;
Bettors[1].UpdateLabels();
Bettors[2] = new Guy();
Bettors[2].Name = "Al";
Bettors[2].MyRadioButton = alRadioButton;
Bettors[2].MyLabel = alBetLabel;
Bettors[2].Cash = 45;
Bettors[2].UpdateLabels();
int StartPosition = pictureBoxDog1.Location.X;
int distance = pictureBox1.Width;
for (int i = 0; i < 4; i++)
{
Dogs[i] = new Greyhound();
Dogs[i].Randomizer = Randomizer;
Dogs[i].RacetrackLength = distance;
Dogs[i].Location = Dogs[i].StartingPosition = StartPosition;
}
Dogs[0].MyPictureBox = pictureBoxDog1;
Dogs[1].MyPictureBox = pictureBoxDog2;
Dogs[2].MyPictureBox = pictureBoxDog3;
Dogs[3].MyPictureBox = pictureBoxDog4;
CurrentBettor = Bettors[0];
}
private void RaceButton_Click(object sender, EventArgs e)
{
int winner = 0;
int num_winners = 0;
while (num_winners == 0)
{
for (int i = 0; i < Dogs.Length; i++)
{
if (Dogs[i].Run())
{
num_winners++;
winner = i + 1;
}
}
Application.DoEvents();
System.Threading.Thread.Sleep(3);
}
if (num_winners > 1)
MessageBox.Show("We have " + num_winners + " winners");
else
MessageBox.Show(" Dog #" + winner + "wins!");
for (int i = 0; i < Dogs.Length; i++)
{
Dogs[i].TakeStartingPosition();
}
for (int i = 0; i < Bettors.Length; i ++)
{
Bettors[i].Collect(winner);
Bettors[i].ClearBet();
Bettors[i].UpdateLabels();
}
numericUpDownBet.Value = numericUpDownBet.Minimum;
numericUpDownDog.Value = numericUpDownDog.Minimum;
}
private void joeRadioButton_CheckedChanged(object sender, EventArgs e)
{
SetBettor(0);
}
private void bobRadioButton_CheckedChanged_1(object sender, EventArgs e)
{
SetBettor(1);
}
private void alRadioButton_CheckedChanged_1(object sender, EventArgs e)
{
SetBettor(2);
}
private void BetsButton_Click(object sender, EventArgs e)
{
CurrentBettor.PlaceBet((int)numericUpDownBet.Value, (int)numericUpDownDog.Value);
CurrentBettor.UpdateLabels();
}
private void SetBettor(int index)
{
CurrentBettor = Bettors[index];
NameLabel.Text = CurrentBettor.Name;
if (CurrentBettor.MyBet != null)
{
numericUpDownBet.Value = CurrentBettor.MyBet.Amount;
numericUpDownDog.Value = CurrentBettor.MyBet.Dog;
}
else
{
numericUpDownBet.Value = numericUpDownBet.Minimum;
numericUpDownDog.Value = 1;
}
}
private void Form1_Load(object sender, EventArgs e)
{
minimumBetLabel.Text = "Minimum Bet $5.00";
}
private void ResetButton_Click(object sender, EventArgs e)
{
pictureBoxDog1.Location = new Point(61,32);
pictureBoxDog2.Location = new Point(61,84);
pictureBoxDog3.Location = new Point(61,131);
pictureBoxDog4.Location = new Point(61,181);
}
}
}
Form1.Designer.cs
namespace A_Day_at_the_Races
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.pictureBoxDog1 = new System.Windows.Forms.PictureBox();
this.pictureBoxDog2 = new System.Windows.Forms.PictureBox();
this.pictureBoxDog3 = new System.Windows.Forms.PictureBox();
this.pictureBoxDog4 = new System.Windows.Forms.PictureBox();
this.RaceButton = new System.Windows.Forms.Button();
this.minimumBetLabel = new System.Windows.Forms.Label();
this.joeRadioButton = new System.Windows.Forms.RadioButton();
this.bobRadioButton = new System.Windows.Forms.RadioButton();
this.alRadioButton = new System.Windows.Forms.RadioButton();
this.BetsLabel = new System.Windows.Forms.Label();
this.joeBetLabel = new System.Windows.Forms.Label();
this.bobBetLabel = new System.Windows.Forms.Label();
this.alBetLabel = new System.Windows.Forms.Label();
this.NameLabel = new System.Windows.Forms.Label();
this.BetsButton = new System.Windows.Forms.Button();
this.numericUpDownBet = new System.Windows.Forms.NumericUpDown();
this.label1 = new System.Windows.Forms.Label();
this.numericUpDownDog = new System.Windows.Forms.NumericUpDown();
this.ResetButton = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxDog1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxDog2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxDog3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxDog4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownBet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownDog)).BeginInit();
this.SuspendLayout();
//
// pictureBox1
//
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.Location = new System.Drawing.Point(12, 12);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(602, 201);
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
//
// pictureBoxDog1
//
this.pictureBoxDog1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBoxDog1.Image")));
this.pictureBoxDog1.Location = new System.Drawing.Point(22, 21);
this.pictureBoxDog1.Name = "pictureBoxDog1";
this.pictureBoxDog1.Size = new System.Drawing.Size(75, 21);
this.pictureBoxDog1.TabIndex = 1;
this.pictureBoxDog1.TabStop = false;
//
// pictureBoxDog2
//
this.pictureBoxDog2.Image = ((System.Drawing.Image)(resources.GetObject("pictureBoxDog2.Image")));
this.pictureBoxDog2.Location = new System.Drawing.Point(22, 70);
this.pictureBoxDog2.Name = "pictureBoxDog2";
this.pictureBoxDog2.Size = new System.Drawing.Size(75, 22);
this.pictureBoxDog2.TabIndex = 2;
this.pictureBoxDog2.TabStop = false;
//
// pictureBoxDog3
//
this.pictureBoxDog3.Image = ((System.Drawing.Image)(resources.GetObject("pictureBoxDog3.Image")));
this.pictureBoxDog3.Location = new System.Drawing.Point(22, 120);
this.pictureBoxDog3.Name = "pictureBoxDog3";
this.pictureBoxDog3.Size = new System.Drawing.Size(75, 24);
this.pictureBoxDog3.TabIndex = 3;
this.pictureBoxDog3.TabStop = false;
//
// pictureBoxDog4
//
this.pictureBoxDog4.Image = ((System.Drawing.Image)(resources.GetObject("pictureBoxDog4.Image")));
this.pictureBoxDog4.Location = new System.Drawing.Point(22, 170);
this.pictureBoxDog4.Name = "pictureBoxDog4";
this.pictureBoxDog4.Size = new System.Drawing.Size(75, 24);
this.pictureBoxDog4.TabIndex = 4;
this.pictureBoxDog4.TabStop = false;
//
// RaceButton
//
this.RaceButton.Location = new System.Drawing.Point(468, 269);
this.RaceButton.Name = "RaceButton";
this.RaceButton.Size = new System.Drawing.Size(146, 73);
this.RaceButton.TabIndex = 5;
this.RaceButton.Text = "Race!";
this.RaceButton.UseVisualStyleBackColor = true;
this.RaceButton.Click += new System.EventHandler(this.RaceButton_Click);
//
// minimumBetLabel
//
this.minimumBetLabel.AutoSize = true;
this.minimumBetLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.minimumBetLabel.Location = new System.Drawing.Point(9, 241);
this.minimumBetLabel.Name = "minimumBetLabel";
this.minimumBetLabel.Size = new System.Drawing.Size(0, 13);
this.minimumBetLabel.TabIndex = 6;
//
// joeRadioButton
//
this.joeRadioButton.AutoSize = true;
this.joeRadioButton.Location = new System.Drawing.Point(12, 269);
this.joeRadioButton.Name = "joeRadioButton";
this.joeRadioButton.Size = new System.Drawing.Size(85, 17);
this.joeRadioButton.TabIndex = 7;
this.joeRadioButton.TabStop = true;
this.joeRadioButton.Text = "radioButton1";
this.joeRadioButton.UseVisualStyleBackColor = true;
this.joeRadioButton.CheckedChanged += new System.EventHandler(this.joeRadioButton_CheckedChanged);
//
// bobRadioButton
//
this.bobRadioButton.AutoSize = true;
this.bobRadioButton.Location = new System.Drawing.Point(12, 293);
this.bobRadioButton.Name = "bobRadioButton";
this.bobRadioButton.Size = new System.Drawing.Size(85, 17);
this.bobRadioButton.TabIndex = 8;
this.bobRadioButton.TabStop = true;
this.bobRadioButton.Text = "radioButton1";
this.bobRadioButton.UseVisualStyleBackColor = true;
this.bobRadioButton.CheckedChanged += new System.EventHandler(this.bobRadioButton_CheckedChanged_1);
//
// alRadioButton
//
this.alRadioButton.AutoSize = true;
this.alRadioButton.Location = new System.Drawing.Point(12, 317);
this.alRadioButton.Name = "alRadioButton";
this.alRadioButton.Size = new System.Drawing.Size(85, 17);
this.alRadioButton.TabIndex = 9;
this.alRadioButton.TabStop = true;
this.alRadioButton.Text = "radioButton2";
this.alRadioButton.UseVisualStyleBackColor = true;
this.alRadioButton.CheckedChanged += new System.EventHandler(this.alRadioButton_CheckedChanged_1);
//
// BetsLabel
//
this.BetsLabel.AutoSize = true;
this.BetsLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.BetsLabel.Location = new System.Drawing.Point(164, 241);
this.BetsLabel.Name = "BetsLabel";
this.BetsLabel.Size = new System.Drawing.Size(32, 13);
this.BetsLabel.TabIndex = 10;
this.BetsLabel.Text = "Bets";
//
// joeBetLabel
//
this.joeBetLabel.AutoSize = true;
this.joeBetLabel.Location = new System.Drawing.Point(164, 269);
this.joeBetLabel.Name = "joeBetLabel";
this.joeBetLabel.Size = new System.Drawing.Size(35, 13);
this.joeBetLabel.TabIndex = 11;
this.joeBetLabel.Text = "label1";
//
// bobBetLabel
//
this.bobBetLabel.AutoSize = true;
this.bobBetLabel.Location = new System.Drawing.Point(164, 293);
this.bobBetLabel.Name = "bobBetLabel";
this.bobBetLabel.Size = new System.Drawing.Size(35, 13);
this.bobBetLabel.TabIndex = 12;
this.bobBetLabel.Text = "label1";
//
// alBetLabel
//
this.alBetLabel.AutoSize = true;
this.alBetLabel.Location = new System.Drawing.Point(164, 317);
this.alBetLabel.Name = "alBetLabel";
this.alBetLabel.Size = new System.Drawing.Size(35, 13);
this.alBetLabel.TabIndex = 13;
this.alBetLabel.Text = "label1";
//
// NameLabel
//
this.NameLabel.AutoSize = true;
this.NameLabel.Location = new System.Drawing.Point(9, 359);
this.NameLabel.Name = "NameLabel";
this.NameLabel.Size = new System.Drawing.Size(0, 13);
this.NameLabel.TabIndex = 14;
//
// BetsButton
//
this.BetsButton.Location = new System.Drawing.Point(54, 354);
this.BetsButton.Name = "BetsButton";
this.BetsButton.Size = new System.Drawing.Size(75, 23);
this.BetsButton.TabIndex = 15;
this.BetsButton.Text = "Bets";
this.BetsButton.UseVisualStyleBackColor = true;
this.BetsButton.Click += new System.EventHandler(this.BetsButton_Click);
//
// numericUpDownBet
//
this.numericUpDownBet.Location = new System.Drawing.Point(135, 357);
this.numericUpDownBet.Minimum = new decimal(new int[] {
5,
0,
0,
0});
this.numericUpDownBet.Name = "numericUpDownBet";
this.numericUpDownBet.Size = new System.Drawing.Size(72, 20);
this.numericUpDownBet.TabIndex = 16;
this.numericUpDownBet.Value = new decimal(new int[] {
5,
0,
0,
0});
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(214, 359);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(113, 13);
this.label1.TabIndex = 17;
this.label1.Text = "bucks on dog number ";
//
// numericUpDownDog
//
this.numericUpDownDog.Location = new System.Drawing.Point(334, 356);
this.numericUpDownDog.Maximum = new decimal(new int[] {
4,
0,
0,
0});
this.numericUpDownDog.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDownDog.Name = "numericUpDownDog";
this.numericUpDownDog.Size = new System.Drawing.Size(79, 20);
this.numericUpDownDog.TabIndex = 18;
this.numericUpDownDog.Value = new decimal(new int[] {
1,
0,
0,
0});
//
// ResetButton
//
this.ResetButton.Location = new System.Drawing.Point(468, 349);
this.ResetButton.Name = "ResetButton";
this.ResetButton.Size = new System.Drawing.Size(146, 41);
this.ResetButton.TabIndex = 19;
this.ResetButton.Text = "Reset";
this.ResetButton.UseVisualStyleBackColor = true;
this.ResetButton.Click += new System.EventHandler(this.ResetButton_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(626, 410);
this.Controls.Add(this.ResetButton);
this.Controls.Add(this.numericUpDownDog);
this.Controls.Add(this.label1);
this.Controls.Add(this.numericUpDownBet);
this.Controls.Add(this.BetsButton);
this.Controls.Add(this.NameLabel);
this.Controls.Add(this.alBetLabel);
this.Controls.Add(this.bobBetLabel);
this.Controls.Add(this.joeBetLabel);
this.Controls.Add(this.BetsLabel);
this.Controls.Add(this.alRadioButton);
this.Controls.Add(this.bobRadioButton);
this.Controls.Add(this.joeRadioButton);
this.Controls.Add(this.minimumBetLabel);
this.Controls.Add(this.RaceButton);
this.Controls.Add(this.pictureBoxDog4);
this.Controls.Add(this.pictureBoxDog3);
this.Controls.Add(this.pictureBoxDog2);
this.Controls.Add(this.pictureBoxDog1);
this.Controls.Add(this.pictureBox1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxDog1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxDog2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxDog3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxDog4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownBet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownDog)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.PictureBox pictureBoxDog1;
private System.Windows.Forms.PictureBox pictureBoxDog2;
private System.Windows.Forms.PictureBox pictureBoxDog3;
private System.Windows.Forms.PictureBox pictureBoxDog4;
private System.Windows.Forms.Button RaceButton;
private System.Windows.Forms.Label minimumBetLabel;
private System.Windows.Forms.RadioButton joeRadioButton;
private System.Windows.Forms.RadioButton bobRadioButton;
private System.Windows.Forms.RadioButton alRadioButton;
private System.Windows.Forms.Label BetsLabel;
private System.Windows.Forms.Label joeBetLabel;
private System.Windows.Forms.Label bobBetLabel;
private System.Windows.Forms.Label alBetLabel;
private System.Windows.Forms.Label NameLabel;
private System.Windows.Forms.Button BetsButton;
private System.Windows.Forms.NumericUpDown numericUpDownBet;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.NumericUpDown numericUpDownDog;
private System.Windows.Forms.Button ResetButton;
}
}
in PlaceBet method you have forgotten to set the Bettor property:
if (Cash >= Amount)
{
Cash = Cash - Amount;
MyLabel = new Label();
MyBet.Amount = Amount; // HERE
MyBet.Dog = Dog; // HERE
UpdateLabels();
return true;
just add there also a line:
MyBet.Bettor = this;
Explanation/rationale: The point is that without it, when a "Guy" creates a "Bet", the Bet does not get to know who has created it. Nowhere in your code you set the Bettor field, so it never has a chance to be set to something meaningful. The bet will simply retain the default NULL value in this field. As I do not actually read/trace all the code, I think the simpliest way would be to make the Bet know his owner straight from the very beginning.
In Guy.cs when you call PlaceBet(...) and create instantiate the bet, you need to set:
this.MyBet.Bettor = this;
Within this function, this refers to the instance of Guy that is placing the bet.
The second problem you have is with the creation of a new instance of Label, without actually replacing the Label on your form with the new one. In summary fix the PlaceBet(...) method like so:
public bool PlaceBet(int Amount, int Dog)
{
this.MyBet = new Bet();
if (Cash >= Amount)
{
Cash = Cash - Amount;
// remove the following line
// MyLabel = new Label();
MyBet.Amount = Amount;
MyBet.Dog = Dog;
// insert this line...
MyBet.Bettor = this;
UpdateLabels();
return true;
}
else
{
return false;
}
}
I just performed this exercise myself in the book... been running through it. I looked over your code to see how you took care of this problem and I found a pretty big bug in how you handled paying out the betters - In form1.cs when you allow your loop to capture multiple winners you are not continuing to distribute winnings with the Collect method to anyone who bet on anything besides the last winning dog
while (num_winners == 0)
{
for (int i = 0; i < Dogs.Length; i++)
{
if (Dogs[i].Run())
{
num_winners++;
winner = i + 1;
}
}
Application.DoEvents();
System.Threading.Thread.Sleep(3);
}
if (num_winners > 1)
// you say that you have multiple winners right here but you never eval on
//it - winner is still set to one value above
MessageBox.Show("We have " + num_winners + " winners");
else
MessageBox.Show(" Dog #" + winner + "wins!");
for (int i = 0; i < Dogs.Length; i++)
{
Dogs[i].TakeStartingPosition();
}
for (int i = 0; i < Bettors.Length; i ++)
{
Bettors[i].Collect(winner);
Bettors[i].ClearBet();
Bettors[i].UpdateLabels();
}
What will need to be changed to correct this and disperse bets appropriately:
1) Make the betting scheme more realistic - when the bet is placed - subtract the money. You need to allow for a Re-Bet to take place just in case someone wants to redo one of the users on the front page
in guy.cs
public bool PlaceBet(int amount, int dog)
{
// place a new bet and store it in the bet field, return true if there is enough money
if (amount > Cash)
{
MessageBox.Show("I don't have enough money for that bet!", Name + " says...");
return false;
}
else
{
if (this.MyBet == null)
{
this.MyBet = new Bet() { Amount = amount, Bettor = this, Dog = dog };
this.Cash -= amount;
this.UpdateLabels();
return true;
}
else
{
this.Cash += this.MyBet.Amount;
this.MyBet = null;
this.MyBet = new Bet() { Amount = amount, Bettor = this, Dog = dog };
this.Cash -= amount;
this.UpdateLabels();
return true;
}
}
}
2) Now that the betters already lost/submitted their money and we don't have to worry about sending negative monies to them if their dog doesn't win, the Bet.cs Payout method can be updated to only provide a positive return if the winning dog matches their bet dog. if it doesn't, it returns nothing.
public int PayOut(int Winner)
{
// the parameter is the winner of the race. If the dog won, return the amount bet.
// otherwise return nothing
if (Winner == Dog)
{
int payout = Amount*2;
return payout;
}
else
{
int payout = 0;
return payout;
}
}
3) and now we can adjust our scheme in form1.cs to take care of paying multiples (even though this never really happens)
private void formButtonRace_Click(object sender, EventArgs e)
{
int winner = 0;
int windog = 0;
int count = 0;
for (int i = 0; i < Bettors.Length; i++)
{
if (Bettors[1].MyBet != null)
{
count++;
}
}
if (count == Bettors.Length)
{
while (winner == 0)
{
for (int i = 0; i < Dogs.Length; i++)
{
if (Dogs[i].Run())
{
winner++;
windog = i + 1;
for (int i2 = 0; i2 < Bettors.Length; i2++)
{
Bettors[i2].Collect(i + 1);
}
}
Application.DoEvents();
System.Threading.Thread.Sleep(3);
}
}
if (winner > 1)
{
MessageBox.Show("Multiple winners!", "WOW");
}
else
{
MessageBox.Show("The winner was dog #" + windog);
}
for (int i = 0; i < Bettors.Length; i++)
{
Bettors[i].ClearBet(true);
}
for (int i = 0; i < Dogs.Length; i++)
{
Dogs[i].TakeStartingPosition();
}
}
else
{
MessageBox.Show("Not all players have placed their bets!", "Wait wait!");
}
}
The reason why my ClearBet is passing in a bool is because I had to restore the money bet to each individual Guy if the reset button was pressed. However, if the race was completed I wanted to reset them without returning their bets.
This is that section for me in my code:
public void ClearBet(bool isRaceOver)
{
if (isRaceOver)
// reset bet when race is over
{
MyBet = null;
}
else
{
if (this.MyBet != null)
{
Cash += this.MyBet.Amount;
this.MyBet = null;
}
else
{
this.MyBet = null;
}
}
UpdateLabels();
}
In the PlaceBet() method, you are overwriting MyLabel with a new Label() therefore the original context of the label on the form is lost.
Although you are actually updating a Label, it's not the Label on the form.
public bool PlaceBet(int Amount, int Dog)
{
this.MyBet = new Bet();
if (Cash >= Amount)
{
Cash = Cash - Amount;
MyLabel = new Label(); // remove this
MyBet.Amount = Amount;
MyBet.Dog = Dog;
UpdateLabels();
return true;
}
else
{
return false;
}
}

Require help in C# Need to implement moving picture box

I need a help on this,
There are 3 picture boxes, red should grow its Width to left, green should grow its height to top blue's width to right
also if one reaches the top border / any text boxes it should give an error / stop execution
I need to add more picture boxes in future and if two of them collides it should give an error / stop execution. I have managed to code them to go up, however unable to get other functions working. Please some one help me with this.
OR
https://www.box.com/s/d0d302c6c266f52e0abf
Thank you.
RR
My code below,
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace ThreadwithmovingPicbxmoving
{
public partial class Form1 : Form
{
Thread t1;
Thread t2;
Thread t3;
delegate void CTMethod(int val);
delegate void CTFinish(string t);
Queue<string> order = new Queue<string>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int r = int.Parse(textBox1.Text);
int y = int.Parse(textBox2.Text);
int g = int.Parse(textBox3.Text);
t1 = new Thread(new ParameterizedThreadStart(loopred));
t2 = new Thread(new ParameterizedThreadStart(loopyel));
t3 = new Thread(new ParameterizedThreadStart(loopGree));
t1.Start(r);
t2.Start(y);
t3.Start(g);
}
private void updateRed(int val)
{
pictureBox1.Height = val;
pictureBox1.Refresh();
}
private void updateyell(int val)
{
pictureBox2.Height = val;
pictureBox2.Refresh();
}
private void updategree(int val)
{
pictureBox3.Height = val;
pictureBox3.Refresh();
}
private void loopred(object o)
{
int c = (int)o;
CTMethod ctred = new CTMethod(updateRed);
if (c < 500)
{
for (int i = 0; i < c; i++)
{
this.Invoke(ctred, i);
Thread.Sleep(20);
}
}
else
{
MessageBox.Show("Enter a value less than 500 for Red Box!!!");
}
CTFinish CTFin = new CTFinish(Threadfinish);
this.Invoke(CTFin, "Red");
}
private void loopyel(object o)
{
int c = (int)o;
CTMethod ctyell = new CTMethod(updateyell);
if (c < 500)
{
for (int i = 0; i < c; i++)
{
this.Invoke(ctyell, i);
Thread.Sleep(20);
}
}
else
{
MessageBox.Show("Enter a valure less than 500 for Yellow Box!!!");
}
CTFinish CTFin = new CTFinish(Threadfinish);
this.Invoke(CTFin, "Yell");
}
private void loopGree(object o)
{
int c = (int)o;
CTMethod ctgree = new CTMethod(updategree);
if (c < 500)
{
for (int i = 0; i < c; i++)
{
this.Invoke(ctgree, i);
Thread.Sleep(20);
}
}
else
{
MessageBox.Show("Enter a valure less than 500 for Green Box!!!");
}
CTFinish CTfin = new CTFinish(Threadfinish);
this.Invoke(CTfin, "Green");
}
private void Threadfinish(string t)
{
order.Enqueue(t);
if (order.Count == 3)
{
MessageBox.Show("Threads finished in this order: \n" + "1." + order.Dequeue() + "\n" + "2." + order.Dequeue()
+ "\n" + "3." + order.Dequeue() + "\n", "finished");
}
}
}
}
Try It. Its All Fine with three PictureBoxes
Create New Widows Application with name help and then replace Form1.cs code with Following
Run It. It also includes values from TextBoxes
using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using System.Collections.Generic;
namespace help
{
public partial class Form1 : Form
{
Thread t1;
Thread t2;
Thread t3;
delegate void CTMethod(int val);
delegate void CTFinish(string t);
Queue<string> order = new Queue<string>();
#region Variables of Designer File
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.PictureBox pictureBox2;
private System.Windows.Forms.PictureBox pictureBox3;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.TextBox textBox3;
private System.Windows.Forms.Button button1;
#endregion
public Form1()
{
#region Designer Code I have Cut and Pasted Here
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
this.pictureBox3 = new System.Windows.Forms.PictureBox();
this.textBox1 = new System.Windows.Forms.TextBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.textBox3 = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).BeginInit();
this.SuspendLayout();
this.Controls.Add(this.button1);
this.Controls.Add(this.textBox3);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.pictureBox3);
this.Controls.Add(this.pictureBox2);
this.Controls.Add(this.pictureBox1);
//
// pictureBox1
//
this.pictureBox1.BackColor = System.Drawing.Color.Red;
this.pictureBox1.Location = new System.Drawing.Point(161, 268);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(100, 50);
this.pictureBox1.TabIndex = 0;
this.pictureBox1.TabStop = false;
//
// pictureBox2
//
this.pictureBox2.BackColor = System.Drawing.Color.Green;
this.pictureBox2.Location = new System.Drawing.Point(383, 268);
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.Size = new System.Drawing.Size(100, 50);
this.pictureBox2.TabIndex = 1;
this.pictureBox2.TabStop = false;
//
// pictureBox3
//
this.pictureBox3.BackColor = System.Drawing.Color.Blue;
this.pictureBox3.Location = new System.Drawing.Point(605, 268);
this.pictureBox3.Name = "pictureBox3";
this.pictureBox3.Size = new System.Drawing.Size(100, 50);
this.pictureBox3.TabIndex = 2;
this.pictureBox3.TabStop = false;
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(161, 26);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(100, 20);
this.textBox1.TabIndex = 3;
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(383, 25);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(100, 20);
this.textBox2.TabIndex = 4;
//
// textBox3
//
this.textBox3.Location = new System.Drawing.Point(605, 26);
this.textBox3.Name = "textBox3";
this.textBox3.Size = new System.Drawing.Size(100, 20);
this.textBox3.TabIndex = 5;
//
// button1
//
this.button1.Location = new System.Drawing.Point(37, 23);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 6;
this.button1.Text = "Go";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
this.PerformLayout();
#endregion
InitializeComponent();
textBox1.Text = "490";
textBox2.Text = "490";
textBox3.Text = "490";
textBox1.Leave += new EventHandler(textBox1_Leave);
textBox2.Leave += new EventHandler(textBox2_Leave);
textBox3.Leave += new EventHandler(textBox3_Leave);
}
// To input Only Valid int values in TextBoxes
#region TextBoxes Input Validation
int t1Val = 490;
int t2Val = 490;
int t3Val = 490;
void textBox1_Leave(object sender, EventArgs e)
{
try
{
int t1Val = Convert.ToInt32(textBox1.Text);
}
catch
{
textBox1.Focus();
}
}
void textBox2_Leave(object sender, EventArgs e)
{
try
{
int t2Val = Convert.ToInt32(textBox2.Text);
}
catch
{
textBox2.Focus();
}
}
void textBox3_Leave(object sender, EventArgs e)
{
try
{
int t3Val = Convert.ToInt32(textBox3.Text);
}
catch
{
textBox3.Focus();
}
}
#endregion
private void button1_Click(object sender, EventArgs e)
{
int r = t1Val;
int y = t2Val;
int g = t3Val;
t1 = new Thread(new ParameterizedThreadStart(loopRed));
t2 = new Thread(new ParameterizedThreadStart(loopGreen));
t3 = new Thread(new ParameterizedThreadStart(loopBlue));
// It will avoid proble if you exit app when threads are working
t1.IsBackground = true;
t2.IsBackground = true;
t3.IsBackground = true;
t1.Start(r);
t2.Start(y);
t3.Start(g);
}
private void updateRed(int val)
{
pictureBox1.Width++;
pictureBox1.Left--;
pictureBox1.Refresh();
}
private void updateGreen(int val)
{
pictureBox2.Height++;
pictureBox2.Top--;
pictureBox2.Refresh();
}
private void updateBlue(int val)
{
pictureBox3.Width++;
pictureBox3.Refresh();
}
private void loopRed(object o)
{
int c = (int)o;
CTMethod ctRed = new CTMethod(updateRed);
if (c < 500)
{
for (int i = 0; i < c; i++)
{
if (pictureBox1.Left > 0)
{
this.Invoke(ctRed, i);
Thread.Sleep(20);
}
}
}
else
{
MessageBox.Show("Enter a value less than 500 for Red Box!!!");
}
CTFinish CTFin = new CTFinish(Threadfinish);
this.Invoke(CTFin, "Red");
}
private void loopGreen(object o)
{
int c = (int)o;
CTMethod ctGreen = new CTMethod(updateGreen);
if (c < 500)
{
for (int i = 0; i < c; i++)
{
if (pictureBox2.Top > 0 && pictureBox2.Top != textBox2.Top + textBox2.Height)
{
this.Invoke(ctGreen, i);
Thread.Sleep(20);
}
else
break;
}
}
else
{
MessageBox.Show("Enter a valure less than 500 for Green Box!!!");
}
CTFinish CTFin = new CTFinish(Threadfinish);
this.Invoke(CTFin, "Green");
}
private void loopBlue(object o)
{
int c = (int)o;
CTMethod ctBlue = new CTMethod(updateBlue);
if (c < 500)
{
for (int i = 0; i < c; i++)
{
if (pictureBox3.Left + pictureBox3.Width < this.Width)
{
this.Invoke(ctBlue, i);
Thread.Sleep(20);
}
else
break;
}
}
else
{
MessageBox.Show("Enter a valure less than 500 for Blue Box!!!");
}
CTFinish CTfin = new CTFinish(Threadfinish);
this.Invoke(CTfin, "Blue");
}
private void Threadfinish(string t)
{
order.Enqueue(t);
if (order.Count == 3)
{
MessageBox.Show("Threads finished in this order: \n" + "1." + order.Dequeue() + "\n" + "2." + order.Dequeue()
+ "\n" + "3." + order.Dequeue() + "\n", "finished");
}
}
}
}

Categories