How can i create buttons in C# [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
Please, can you help me with create buttons. I have problem that when i run application so i dont see any buttons from my code. Somewhere in my code is bug.
Step 1) (Class for button properities)
class GraphicClassStructure : GraphicPosition
{
public Button menu = new Button();
public Button classBackround = new Button();
public Button resetTree = new Button();
public void CreateClassButtons()
{
switch (UniqueValue.character)
{
case "sorcerer":
this.menu.Name = "sorcererText";
this.menu.BackgroundImage = BuildResource.sorcerer;
this.classBackround.BackgroundImage = BuildResource.sorcerer_skill_tree;
break;
case "dragonknight":
this.menu.Name = "dragonKnightText";
this.menu.BackgroundImage = BuildResource.dragonknight;
this.classBackround.BackgroundImage = BuildResource.dragonknight_skill_tree;
break;
case "templar":
this.menu.Name = "templarText";
this.menu.BackgroundImage = BuildResource.templar;
this.classBackround.BackgroundImage = BuildResource.templar_skill_tree;
break;
case "nightblade":
this.menu.Name = "nightbladeText";
this.menu.BackgroundImage = BuildResource.nightblade;
this.classBackround.BackgroundImage = BuildResource.nightblade_skill_tree;
break;
}
// Menu
this.menu.BackColor = System.Drawing.Color.Transparent;
this.menu.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.menu.FlatAppearance.BorderSize = 0;
this.menu.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Transparent;
this.menu.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
this.menu.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.menu.Location = new System.Drawing.Point(Location[0][0][0], Location[0][1][0]);
this.menu.Size = new System.Drawing.Size(Size[0][0][0], Size[0][1][0]);
this.menu.TabIndex = 3;
this.menu.UseVisualStyleBackColor = false;
// Class Backround
this.classBackround.BackColor = System.Drawing.Color.Transparent;
this.classBackround.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.classBackround.FlatAppearance.BorderSize = 0;
this.classBackround.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Transparent;
this.classBackround.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
this.classBackround.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.classBackround.Location = new System.Drawing.Point(Location[0][0][1], Location[0][1][1]);
this.classBackround.Name = "classBackround";
this.classBackround.Size = new System.Drawing.Size(Size[0][0][1], Size[0][1][1]);
this.classBackround.TabIndex = 17;
this.classBackround.UseVisualStyleBackColor = false;
// Reset tree
this.resetTree.BackColor = System.Drawing.Color.Transparent;
this.resetTree.BackgroundImage = BuildResource.reset;
this.resetTree.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.resetTree.FlatAppearance.BorderSize = 0;
this.resetTree.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Transparent;
this.resetTree.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
this.resetTree.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.resetTree.Name = "resetTree";
this.resetTree.Size = new System.Drawing.Size(Size[0][0][2], Size[0][1][2]);
//this.resetTree.TabIndex = 18;
this.resetTree.UseVisualStyleBackColor = false;
}
}
Step 2) (Class for button position and size)
class GraphicPosition
{
// new int[type][x,y][value]
// Location
public int[][][] Location;
// Size
public int[][][] Size;
public GraphicPosition()
{
Location = new int[][][]
{
new int[][]
{
// Menu
new int[89],
// Class
new int[325],
// Reset Tree
new int[410],
new int[615],
new int[823]
},
new int[][]
{
// Menu
new int[223],
// Class
new int[200],
// Reset Tree
new int[169],
new int[169],
new int[169]
}
};
Size = new int[][][]
{
new int[][]
{
// Menu
new int[133],
// Class
new int[619],
// Reset Tree
new int[28]
},
new int[][]
{
// Menu
new int[26],
// Class
new int[484],
// Reset Tree
new int[25]
}
};
}
}
Step 3) (Script in form initialization component)
Collection collection = new Collection();
GraphicClassStructure classStructure = new GraphicClassStructure();
public buildEditor()
{
InitializeComponent();
this.Cursor = NativeMethods.LoadCustomCursor(Path.Combine(collection.source, collection.cursor));
maxSkillPoint.Text = collection.maxSkill.ToString();
classStructure.CreateClassButtons();
this.Controls.Add(classStructure.classBackround);
for (int i = 0; i < 3; i++)
{
switch (i)
{
case 0:
classStructure.resetTree.Location = new System.Drawing.Point(classStructure.Location[0][0][2], classStructure.Location[0][1][2]);
break;
case 1:
classStructure.resetTree.Location = new System.Drawing.Point(classStructure.Location[0][0][3], classStructure.Location[0][1][3]);
break;
case 2:
classStructure.resetTree.Location = new System.Drawing.Point(classStructure.Location[0][0][4], classStructure.Location[0][1][4]);
break;
}
classStructure.resetTree.Click += new EventHandler(resetTreekOneEvent_Click);
classStructure.resetTree.Tag = i;
this.Controls.Add(classStructure.resetTree);
}
switch (UniqueValue.character)
{
case "sorcerer":
MessageBox.Show("sorcerer");
classStructure.menu.Click += new System.EventHandler(sorcerer_Click);
classStructure.menu.MouseEnter += new System.EventHandler(sorcerer_MouseEnter);
classStructure.menu.MouseLeave += new System.EventHandler(sorcerer_MouseLeave);
break;
case "dragonknight":
MessageBox.Show("dragonknight");
classStructure.menu.Click += new System.EventHandler(dragonKnightText_Click);
classStructure.menu.MouseEnter += new System.EventHandler(dragonKnightText_MouseEnter);
classStructure.menu.MouseLeave += new System.EventHandler(dragonKnightText_MouseLeave);
break;
case "templar":
MessageBox.Show("templar");
classStructure.menu.Click += new System.EventHandler(templar_Click);
classStructure.menu.MouseEnter += new System.EventHandler(templar_MouseEnter);
classStructure.menu.MouseLeave += new System.EventHandler(templar_MouseLeave);
break;
case "nightblade":
MessageBox.Show("nightblade");
classStructure.menu.Click += new System.EventHandler(nightblade_Click);
classStructure.menu.MouseEnter += new System.EventHandler(nightblade_MouseEnter);
classStructure.menu.MouseLeave += new System.EventHandler(nightblade_MouseLeave);
break;
}
this.Controls.Add(this.classStructure.menu);
}
Any buttons is not displayed. Please, help me.

All your buttons have size (0, 0) and location (0, 0).
You use arrays incorrectly. E.g. the code new int[89] creates an array of 89 elements and all the elements are zero. But it looks like you wanted to store a single int value 89.
You need to change your code in such a way:
Declaration:
// 2 pairs of square brackets instead of 3
public int[][] Location;
public int[][] Size;
Initialization:
Location = new int[][]
{
new int[]
{
// Menu
89,
// Class
325,
// Reset Tree
410,
615,
823
},
...
Use:
this.menu.Location = new System.Drawing.Point(Location[0][0], Location[1][0]);
But better way is to redesign your Location and Size data structures in such a way:
Point[] Location; // instead of int[][] Location
Size[] Size; // instead of int[][] Size

Related

Unit test a dynamically populating user control in WinForms

I have a WinForms project with MVP pattern (passive view) implemented.
I think that I have a problem with the pattern when it comes to a user control, which I figured out during unit testing
I have a user control that I put on my form as a result of an event fired in my view. That user control adds a certain amount of labels, textboxes, etc. to itsself based on a number it gets from the view. Finally, it tells the view to add the user control to the view.
I want to unit test the logic in this class, since that is what I think is most important to test. I just do not know how to do this, since there is both logic and form controls in this class. I am currently using Moq for creating my unit tests.
I would normally create a Mock object to represent the view and then test the implementation of the methods in the object to be tested in isolation. However, since I create controls in this class, I don't think I can test this like this (without including the .Forms library that is).
I hope someone knows a solution.
EDIT: I have been trying to separate my logic from the control manipulation, but I am struggling with a function from a different user control I have posted below the original user control code. Since I loop through a list of controls, I dont know how to separate this into just logic and just control handling.
User control code
public partial class DetailScreenUserControl : UserControl
{
// Private members.
private readonly IDetailScreenView _view;
private List<ComboBox> maturityInput = new List<ComboBox>();
private List<ComboBox> complianceInput = new List<ComboBox>();
// Public members.
public List<string> MaturityInput
{
get
{
var list = new List<string>();
for (int i = 0; i < maturityInput.Count; i++)
{
list.Add(maturityInput[i].Text);
}
return list;
}
set
{
for (int i = 0; i < maturityInput.Count; i++)
{
maturityInput[i].DataSource = new List<string>(value);
}
}
}
public List<string> ComplianceInput
{
get
{
var list = new List<string>();
for (int i = 0; i < complianceInput.Count; i++)
{
list.Add(complianceInput[i].Text);
}
return list;
}
set
{
for (int i = 0; i < complianceInput.Count; i++)
{
complianceInput[i].DataSource = new List<string>(value);
}
}
}
// Initialize user control with IDetailScreenView. Subscribe to necessary events.
public DetailScreenUserControl(IDetailScreenView view)
{
InitializeComponent();
_view = view;
_view.InitializingUserControl += InitializeUserControl;
}
// Initializes the user control for the detail screen.
public void InitializeUserControl(object sender, EventArgs e)
{
List<string> qStandards = _view.SelectedQuestionStandards;
Controls.Clear();
maturityInput.Clear();
complianceInput.Clear();
int inputSeparation = Height / 2;
int spacing = Width / 20;
Size = new Size(_view.RightUserControlBoundary - Location.X, Size.Height);
for (int i = 0; i < qStandards.Count; i++)
{
Panel inputPanel = new Panel();
inputPanel.BackColor = Color.AliceBlue;
inputPanel.Location = new Point(0, i * inputSeparation);
inputPanel.Size = new Size(Width - spacing, inputSeparation);
Controls.Add(inputPanel);
Label qs_label = new Label();
qs_label.AutoSize = true;
qs_label.Location = new Point(0, 0);
qs_label.Font = new Font("Arial", 12F, FontStyle.Bold);
qs_label.AutoSize = true;
qs_label.Text = qStandards[i].ToString();
inputPanel.Controls.Add(qs_label);
Label m_label = new Label();
m_label.AutoSize = true;
m_label.Location = new Point(0, qs_label.Bounds.Bottom + qs_label.Height / 2);
m_label.Font = new Font("Arial", 12F, FontStyle.Regular);
m_label.Text = "Maturity standard";
inputPanel.Controls.Add(m_label);
Label c_label = new Label();
c_label.AutoSize = true;
c_label.Location = new Point(0, m_label.Bounds.Bottom + qs_label.Height / 2);
c_label.Font = new Font("Arial", 12F, FontStyle.Regular);
c_label.Text = "Compliance standard";
inputPanel.Controls.Add(c_label);
ComboBox m_input = new ComboBox();
m_input.AutoSize = true;
m_input.Location = new Point(c_label.Bounds.Right + 2 * spacing, m_label.Bounds.Top);
m_input.Font = new Font("Arial", 10F, FontStyle.Regular);
m_input.DropDownStyle = ComboBoxStyle.DropDownList;
m_input.Size = new Size(inputPanel.Size.Width - m_input.Bounds.Left, spacing);
maturityInput.Add(m_input);
inputPanel.Controls.Add(m_input);
ComboBox c_input = new ComboBox();
c_input.AutoSize = true;
c_input.Location = new Point(c_label.Bounds.Right + 2 * spacing, c_label.Bounds.Top);
c_input.Font = new Font("Arial", 10F, FontStyle.Regular);
c_input.DropDownStyle = ComboBoxStyle.DropDownList;
c_input.Size = new Size(inputPanel.Size.Width - c_input.Bounds.Left, spacing);
complianceInput.Add(c_input);
inputPanel.Controls.Add(c_input);
}
if(qStandards.Count != 0)
{
saveAssessmentButton.BackColor = System.Drawing.SystemColors.ButtonHighlight;
Controls.Add(saveAssessmentButton);
saveAssessmentButton.Location = new Point(this.Size.Width - saveAssessmentButton.Width - spacing, qStandards.Count * inputSeparation);
}
_view.AddUserControl();
}
// Tells the view to save the assessment.
private void saveAssessmentButton_Click(object sender, EventArgs e)
{
_view.SaveAssessmentButtonClicked();
}
}
Other user control function('answers' is the list of controls)
public void SaveResults()
{
results = new List<string>();
int questionNr = 0;
for (int p = 0; p < questions.Count; p++)
{
for (int i = 0; i < questions[p].Count; i++)
{
bool unanswered = true;
results.Add(questions[p][i]);
for (int j = 1; j <= maturityAnswers[p].Count; j++)
{
var radioButton = (RadioButton)answers[questionNr][j];
if (radioButton.Checked)
{
results.Add(answers[questionNr][j].Text);
unanswered = false;
}
}
if (unanswered == true)
{
results.Add("");
}
unanswered = true;
for (int j = maturityAnswers[p].Count + 1; j <= (maturityAnswers[p].Count + complianceAnswers[p].Count); j++)
{
var radioButton = (RadioButton)answers[questionNr][j];
if (radioButton.Checked)
{
results.Add(answers[questionNr][j].Text);
unanswered = false;
}
}
if (unanswered == true)
{
results.Add("");
}
results.Add(answers[questionNr][0].Text.Replace("'", "''"));
questionNr++;
}
}
I want to unit test the logic in this class, since that is what I
think is most important to test. I just do not know how to do this,
since there is both logic and form controls in this class
So separate them to different classes and test the class which contains only logic

Create new instance uses much memory

I use Nevron Chart in my program. following code is in a click button event:
this.nChartControl1 = new NChartControl();
// add data to chart ...
after each click program allocates a lot of memory and even GC.Collect() doesn't clean the memory, and if I use one instance of Nevron Chart and every time clean the data and then add new data every thing is OK.
what's the problem?
Update 1: here is the function
private void button_Click(object sender, RoutedEventArgs e)
{
//if (nChartControl1 == null)
{
this.nChartControl1 = new NChartControl();
}
// clear data
nChartControl1.Charts.Clear();
nChartControl1.Panels.Clear();
GC.Collect();
// empty the grid then add NevronChart
this.grid.Children.Clear();
this.grid.Children.Add(nChartControl1);
nChartControl1.BackgroundStyle.FrameStyle.Visible = false;
// set a chart title
NLabel title = nChartControl1.Labels.AddHeader("2D Line Chart");
// setup chart
NCartesianChart chart = new NCartesianChart();
nChartControl1.Panels.Add(chart);
chart.DockMode = PanelDockMode.Fill;
chart.Margins = new NMarginsL(2, 0, 2, 2);
chart.Projection.SetPredefinedProjection(PredefinedProjection.Orthogonal);
chart.LightModel.EnableLighting = false;
chart.Axis(StandardAxis.Depth).Visible = false;
chart.Wall(ChartWallType.Floor).Visible = false;
chart.Wall(ChartWallType.Left).Visible = false;
chart.BoundsMode = BoundsMode.Stretch;
chart.Height = 40;
chart.RangeSelections.Add(new NRangeSelection());
chart.Axis(StandardAxis.PrimaryX).ScrollBar.Visible = true;
chart.Axis(StandardAxis.PrimaryY).ScrollBar.Visible = true;
// setup the line series
NLineSeries line = (NLineSeries)chart.Series.Add(SeriesType.Line);
//line.Values.FillRandom(new Random(), 10);
SetRandomData(line);
line.DataLabelStyle.Visible = false;
line.Legend.Mode = SeriesLegendMode.DataPoints;
line.ShadowStyle.Type = ShadowType.GaussianBlur;
line.ShadowStyle.Offset = new NPointL(new NLength(3, NGraphicsUnit.Pixel), new NLength(3, NGraphicsUnit.Pixel));
line.ShadowStyle.FadeLength = new NLength(5, NGraphicsUnit.Pixel);
line.ShadowStyle.Color = System.Drawing.Color.FromArgb(55, 0, 0, 0);
line.LineSegmentShape = LineSegmentShape.Line;
nChartControl1.Controller.Tools.Add(new NSelectorTool());
nChartControl1.Controller.Tools.Add(new NAxisScrollTool());
nChartControl1.Controller.Tools.Add(new NDataZoomTool());
NDataPanTool dpt = new NDataPanTool();
nChartControl1.Controller.Tools.Add(dpt);
nChartControl1.Legends.Clear();
nChartControl1.Refresh();
}
I just tested the control using the following code:
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 100000; i++)
{
using (NChartControl chartControl = new NChartControl())
{
// set a chart title
NLabel title = chartControl.Labels.AddHeader("2D Line Chart");
// setup chart
NCartesianChart chart = new NCartesianChart();
chartControl.Panels.Add(chart);
chart.DockMode = PanelDockMode.Fill;
chart.Margins = new NMarginsL(2, 0, 2, 2);
chart.Projection.SetPredefinedProjection(PredefinedProjection.Orthogonal);
chart.LightModel.EnableLighting = false;
chart.Axis(StandardAxis.Depth).Visible = false;
chart.Wall(ChartWallType.Floor).Visible = false;
chart.Wall(ChartWallType.Left).Visible = false;
chart.BoundsMode = BoundsMode.Stretch;
chart.Height = 40;
chart.RangeSelections.Add(new NRangeSelection());
chart.Axis(StandardAxis.PrimaryX).ScrollBar.Visible = true;
chart.Axis(StandardAxis.PrimaryY).ScrollBar.Visible = true;
// setup the line series
NLineSeries line = (NLineSeries)chart.Series.Add(SeriesType.Line);
//line.Values.FillRandom(new Random(), 10);
line.DataLabelStyle.Visible = false;
line.Legend.Mode = SeriesLegendMode.DataPoints;
line.ShadowStyle.Type = ShadowType.GaussianBlur;
line.ShadowStyle.Offset = new NPointL(new NLength(3, NGraphicsUnit.Pixel), new NLength(3, NGraphicsUnit.Pixel));
line.ShadowStyle.FadeLength = new NLength(5, NGraphicsUnit.Pixel);
line.ShadowStyle.Color = System.Drawing.Color.FromArgb(55, 0, 0, 0);
line.LineSegmentShape = LineSegmentShape.Line;
chartControl.Controller.Tools.Add(new NSelectorTool());
chartControl.Controller.Tools.Add(new NAxisScrollTool());
chartControl.Controller.Tools.Add(new NDataZoomTool());
NDataPanTool dpt = new NDataPanTool();
chartControl.Controller.Tools.Add(dpt);
chartControl.Legends.Clear();
chartControl.Refresh();
}
}
}
And there was no memory leak in the control. So the answer is that you need to call dispose or use a using statement.

Strange drawing behavior with labels

on startup I'm generating a lot of controls 90 to be exact and everything is working ok EXCEPT for the labels they are not being drawn or something? they are there because I can click them and they show proper ID (click event) here's the genereation code
private static bool ClientsLoaded = false;
private static WebBrowser[] Clients = new WebBrowser[45];
private static Label[] ClientLabel = new Label[45];
private static int MaximizedClient = -1;
public Form1()
{
InitializeComponent();
int WBoffsetX = 0;
int WBoffsetY = 0;
int lbloffsetX = 0;
int lbloffsetY = 0;
for (int i = 0; i < 45; i++)
{
var wb = new WebBrowser();
Clients[i] = wb;
wb.ScrollBarsEnabled = false;
wb.Height = 12;
wb.Width = 12;
wb.Location = new Point(2 + WBoffsetX, 2 + WBoffsetY);
WBoffsetX += 13;
wb.ScriptErrorsSuppressed = true;
this.Controls.Add(wb);
ClientLabel[i] = new Label();
ClientLabel[i].Name = "lbl_" + i;
ClientLabel[i].Font = new Font("Arial", 12);
ClientLabel[i].ForeColor = System.Drawing.Color.White;
ClientLabel[i].Location = new Point(12 + lbloffsetX, 450 + lbloffsetY);
lbloffsetX += 22;
ClientLabel[i].Click += new EventHandler(lbl_click);
ClientLabel[i].Text = "C" + i + ": o";
this.Controls.Add(ClientLabel[i]);
}
}
I've tried adding a button with for(45) clientlabel[i].Refresh() and it did nothing I tried changing the visibilty of them all to false and then back to true and nothing however I did find 1 thing interesting if I hide lbl_1 label 2 text will appear if I had label 2 label 3 text will appear but if I change the previous label back to visible they stay invisible textwise
I can click in a line on the form and
private void lbl_click(object sender, EventArgs e)
{
int id = -1;
var s = sender.ToString();
for(int i = 0; i<=45; i++)
{
if (s.Contains("C" + i + ":"))
{
id = i;
}
}
MessageBox.Show("Hello label, " + id);
}
will pop up the proper ids etc
does anyone know what's causing this maybe? or how to fix it
Well, I don't know what is the problem. This code works well enough and it has only marginal differences with the original(AutoSize property, explicit statement of Height and Width, and minor Location adjustment):
for (int i = 0; i < ClientLabel.Length; i++)
{
// Web browsers
WebBrowser wb = new WebBrowser()
{
ScrollBarsEnabled = false,
Height = 12,
Width = 12,
Location = new Point(2 + WBoffsetX, 2 + WBoffsetY),
ScriptErrorsSuppressed = true
};
WBoffsetX += 13;
Clients[i] = wb;
// Labels
Label label = new Label()
{
Name = "label_" + i,
Text = "Data",
AutoSize = true,
Location = new Point(50 + lbloffsetX, 50 + lbloffsetY),
Width = 100,
Height = 20,
Font = new Font("Arial", 12),
ForeColor = System.Drawing.Color.White,
};
label.Click += new EventHandler(lbl_click);
ClientLabel[i] = label;
lbloffsetX += 30;
}
this.Controls.AddRange(Clients);
this.Controls.AddRange(ClientLabel);

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;
}
}

derived class problem using interface

I have a interface
interface Dot
{
// protected Random r = new Random();
void createdot(Rectangle clientrectangle, Control.ControlCollection Controls);
}
and I use this interface as a base class for my derived classes as stated
public class BlueDot : Dot
{
public List<Label> bluedot = new List<Label>();
Random r = new Random();
public void createdot(Rectangle ClientRectangle, Control.ControlCollection Controls)
{
for (int i = 0; i < 5; i++)
{
var temp = new Label();
temp.Location = new Point(r.Next(ClientRectangle.Right - 10), r.Next(ClientRectangle.Bottom - 20));
temp.Text = "?";
temp.Width = 10;
temp.Height = 10;
temp.ForeColor = System.Drawing.Color.Blue;
temp.BackColor = System.Drawing.Color.White;
Controls.Add(temp);
temp.Visible = true;
temp.Show();
bluedot.Add(temp);
}
}
}
and
public class RedDot:Dot
{
public List<Label> reddot = new List<Label>();
Random r = new Random();
public void createdot(Rectangle Clientrectangle,Control.ControlCollection Controls)
{
for (int z = 0; z < 10; z++)
{
var temp2 = new Label();
temp2.Location = new Point(r.Next(Clientrectangle.Right - 10), r.Next(Clientrectangle.Bottom - 20));
temp2.Text = "?";
temp2.Width = 10;
temp2.Height = 10;
temp2.ForeColor = System.Drawing.Color.Red;
temp2.BackColor = System.Drawing.Color.White;
Controls.Add(temp2);
temp2.Show();
reddot.Add(temp2);
}
}
and they are called here
BlueDot bdot = new BlueDot();
RedDot rdot = new RedDot();
private void Form1_Load(object sender, EventArgs e)
{
this.Activate();
bdot.createdot(this.ClientRectangle,this.Controls);
rdot.createdot(this.ClientRectangle, this.Controls);
}
Why is it that I keep getting only 5 red dots even if the loop performs 10 iterations?
here is the sample output https://www.facebook.com/photo.php?fbid=2372861522202&set=a.1600508493859.85328.1270463960&type=1 , i just cant figure out what happened to the other 5 red dots, it should be 10 red dots....
There is no inheritance problem here. The problem is the random number generator.
Try this line in your code:
temp2.Location = new Point(10 * z, 10 * z);
Replacing
temp2.Location = new Point(r.Next(Clientrectangle.Right - 10), r.Next(Clientrectangle.Bottom - 20));
You'll see your 5 blue "?"-labels and your 10 red "?"-labels
To solve the problem of the weak random number generator try seeding your random number generator. Example:
Random r = new Random((int)DateTime.Now.Ticks);
I am not that sure, but why aren't you making your temp2 visible ????
temp2.Visible=true
If this dowsn't work can you provide a screen shot of both your output. Sometimes due to the size of the window one dot may reside over another. I mean they actually overlap. Seeing your output may help to sort out your problem

Categories