I am creating a project where random images show when i click a button and the total of the images (dice) will have to be guessed. I already have down the random image generating and keeping track of the persons amount of rolls. However; I cant figure out how to make a dice (image) have a certain value. Like dice 5 shows and has a value of 4. The person puts there guess in the guessBx and clicks on the guessBtn and it will pop up if they are correct or not.
Here is my code as of now:
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;
namespace PetalsAroundTheRose
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int a = 0;
int diceRoll;
int diceImage;
int diceValue;
private void btnRoll_Click_1(object sender, EventArgs e)
{
Random random = new Random();
picBx1.Image = imageList1.Images[random.Next(1, 6)];
picBx2.Image = imageList1.Images[random.Next(1, 6)];
picBx3.Image = imageList1.Images[random.Next(1, 6)];
picBx4.Image = imageList1.Images[random.Next(1, 6)];
a++;
txtBxRolls.Text = a.ToString();
//each dice seperate
//dice 1
diceRoll = 1;
diceImage = imageList1.Images[(1)];
diceValue = 0;
//dice 2
diceRoll = 1;
diceImage = imageList1.Images[(2)];
diceValue = 0;
//dice 3
diceRoll = 1;
diceImage = imageList1.Images[(3)];
diceValue = 2;
//dice 4
diceRoll = 1;
diceImage = imageList1.Images[(4)];
diceValue = 0;
//dice 5
diceRoll = 1;
diceImage = imageList1.Images[(5)];
diceValue = 4;
}
private void guessBx_TextChanged_1(object sender, EventArgs e)
{
}
}
}
On my design I have btnRoll for rolling the dice. guessBx for entering the guess, btnGuess, txtBxCorrect for the amount correct they got, and txtBxResult to say if they are correct or not
The images are in an imageList
Firstly i create a class with these two properties
public class Dice
{
public int Indexer { get; set; }
public string PhotoPath { get; set; }
public Dice(int indexer, string photoPath)
{
Indexer = indexer;
PhotoPath = photoPath;
}
}
After that i put in my form the picture boxes and then i created two methods
the first one:
public void SetUp()
{
for (int i = 1; i <= 6; i++)
{
temp = random.Next(1, 6);
dice = new Die(temp, "C:\\Users\\giorg\\Desktop\\dice\\dice" + temp + ".PNG");
dices.Add(dice); // list<Dice> dices = new list<Dice>();
}
}
and the second one:
public void RollDices()
{
//this is not necessary but if you want to keep a sum of dices keep
//it
var count = 0;
foreach (var dice in dices)
{
count += dice.Indexer;
}
//pictureboxes 2-7 are guess boxes
if(textBox2.Text.Equals(dices[0].Indexer.ToString()))
pictureBox1.Image = Image.FromFile(dices[0].PhotoPath);
if (textBox3.Text.Equals(dices[1].Indexer.ToString()))
pictureBox2.Image = Image.FromFile(dices[1].PhotoPath);
if (textBox4.Text.Equals(dices[2].Indexer.ToString()))
pictureBox3.Image = Image.FromFile(dices[2].PhotoPath);
if (textBox5.Text.Equals(dices[3].Indexer.ToString()))
pictureBox4.Image = Image.FromFile(dices[3].PhotoPath);
if (textBox6.Text.Equals(dices[4].Indexer.ToString()))
pictureBox5.Image = Image.FromFile(dices[4].PhotoPath);
if (textBox7.Text.Equals(dices[5].Indexer.ToString()))
pictureBox6.Image = Image.FromFile(dices[5].PhotoPath);
}
Put these two methods to your button click event and you are ok...
Inform me if you are ok with this approach.
Related
I'm trying to get back into programming and I'm having trouble getting the final int answers into the text boxes at the end. It has been a few years since I've coded, so if I messed up big time, please let me know.
{
int dice_total;
int dice_num;
int diff_num;
int succ_num = 0;
int ones = 0;
Boolean comp_num = false;
string Succ;
string Comp;
dice_total = int.Parse(Dice.Text);
diff_num = int.Parse(Diff.Text);
Random random = new Random();
dice_num = random.Next(dice_total);
if (dice_num >= diff_num)
{
succ_num++;
}
else
{
if (dice_num == 1)
{
ones++;
}
}
if (ones >= succ_num)
{
comp_num = true;
}
else
{
comp_num = false;
}
Succ = succ_num.ToString();
Comp = comp_num.ToString();
}```
[your text box name].Text=[some int].ToString();
For example:
label1.Text = product.BuyingPrice.ToString();
I can't seem to get it count up the successes. For those who don't know, WoD has you roll d10s and you are given a difficulty. You have to roll that difficulty number or higher to get successes. If there are more (or equal) 1s than total successes, its a complication. This isn't even including code for when you roll a 10 (which has you roll again while still counting as a success).
Ex. Roll 5d10s with a difficulty of 6
6, 8, 10, 1, 1 = 3 success
Roll again for the 10: 1
Total: 3 successes and a complication
using Accord.Math.Distances;
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;
namespace Roller
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int dice_total;
int dice_add;
int dice_num;
int diff_num;
int succ_num = 0;
int ones = 0;
Boolean comp_num = false;
public void button1_Click(object sender, EventArgs e)
{
dice_total = int.Parse(Dice.Text);
diff_num = int.Parse(Diff.Text);
for (dice_add = 0; dice_add < dice_total; dice_add++)
{
Random random = new Random();
dice_num = random.Next(dice_total);
if (dice_num >= diff_num)
{
succ_num++;
}
else
{
if (dice_num == 1)
{
ones++;
}
}
if (ones >= succ_num)
{
comp_num = true;
}
else
{
comp_num = false;
}
}
Succ.Text = succ_num.ToString();
Comp.Text = comp_num.ToString();
}
}
}
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 OpenQA.Selenium;
using OpenQA.Selenium.Support;
using OpenQA.Selenium.Chrome;
using System.Text.RegularExpressions;
using System.IO;
using OpenQA.Selenium.Support.UI;
namespace FlippaSearch
{
public partial class Form1 : Form
{
static IWebDriver driverGC;
public Form1()
{
driverGC = new ChromeDriver(#"Z:\Justin\Documents\Visual Studio 2015\chromedriver_win32");
driverGC.Navigate().GoToUrl("https://flippa.com/websites/starter-sites?sitetype=blog&uniques_per_month_min=1000");
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
List<IWebElement> starterSites = new List<IWebElement>();
List<String> myStarterSites = new List<string>();
IWait<IWebDriver> wait = new WebDriverWait(driverGC, TimeSpan.FromSeconds(30.00));
var numPages = (driverGC.FindElement(By.XPath("//*[#id='searchBody']/div[1]/div[1]/h2/span")).Text);
double numberPages = int.Parse(Regex.Match(numPages, #"\d+", RegexOptions.RightToLeft).Value);
numberPages = Math.Ceiling(numberPages / 50);
int j;
for (int i = 1; i <= numberPages; i++)
{
driverGC.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(30);
var mySites = driverGC.FindElements(By.CssSelector(".ListingResults___listingResult"));
int size = 1;
for (j = 0; j < 3; ++j)
{
driverGC.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(30);
mySites = driverGC.FindElements(By.CssSelector(".ListingResults___listingResult"));
size = mySites.Count();
driverGC.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(30);
String siteLink = " ";
siteLink = mySites[j].FindElement(By.CssSelector(".ListingResults___listingResultLink")).GetAttribute("href");
driverGC.Navigate().GoToUrl(siteLink);
driverGC.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
//testing tables
int row_tr = 5;
int Column_td = 3;
String CellValue;
String newCellValue;
String cellValueChange;
try
{
driverGC.FindElement(By.XPath("/html/body/div[3]/div[1]/div[1]/div[5]/div[1]/div/table[1]/tbody"));
for (int k = 1; k <= row_tr; k++)
{
for (int b = 1; b <= Column_td; b++)
{
CellValue = driverGC.FindElement(By.XPath("/html/body/div[3]/div[1]/div[1]/div[5]/div[1]/div/table[1]/tbody/tr[" + k + "]/td[" + b + "]")).Text.ToString();
if (CellValue == "Organic Search")
{
String mySiteName = driverGC.FindElement(By.XPath("/html/body/div[3]/div[1]/div[1]/div[1]/div[1]/h1")).Text.ToString();
newCellValue = driverGC.FindElement(By.XPath("/html/body/div[3]/div[1]/div[1]/div[5]/div[1]/div/table[1]/tbody/tr[" + k + "]/td[3]")).Text.ToString();
cellValueChange = Regex.Replace(newCellValue, #"[%\s]", string.Empty);
float organicSearch = float.Parse(cellValueChange);
if (organicSearch >= 50)
{
myStarterSites.Add(mySiteName);
myStarterSites.Add(CellValue);
myStarterSites.Add(newCellValue);
Console.WriteLine(mySiteName);
Console.WriteLine(CellValue);
Console.WriteLine(newCellValue);
}
}
}
}
}
catch (OpenQA.Selenium.NoSuchElementException)
{
}
//testing tables
driverGC.Navigate().Back();
//write shit to file
siteLink = "";
driverGC.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(30);
}
j = 0;
//mySites = null;
try
{
driverGC.FindElement(By.XPath("//*[#id='searchBody']/div[2]/div[2]/div/a[3]")).Click();
//driverGC.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(30);
}
catch (ElementNotVisibleException)
{
Console.WriteLine("No more pages");
}
}
using (StreamWriter writer = new StreamWriter(#"C:\Users\Justin\Desktop\newFile.txt"))
{
foreach (string s in myStarterSites)
{
writer.WriteLine(s + " ");// Writes in next line
writer.WriteLine(" ");
}
}
//MessageBox.Show("End");
driverGC.Quit();
Application.Exit();
}
}
}
Upon starting, the code will run fine on the first page. It grab's the elements, puts them in a list, and then i can gather the required information. Once it loops through the first page (i have it set to 3 strictly for testing reasons so its quicker) it will click next page, and then the next page loads and the loop begins again. The issue is, when the second page loads, the first element on the first page is being checked again, and then after that one is checked, it will go to the 2nd element on the 2nd page, and then continue on from there. My question is, how can i get it to scan the first element on the second page instead of redoing the first element on the first page again? I have tried using Waits but I cannot seem to get anything to work.
Thanks in advance.
It probably timing issue, the next loop iteration starts before the next page is actually loaded. You can use explicit wait and ExpectedConditions TextToBePresentInElementLocated on the page numbers to make sure the current page is what you actually need. You can do it by checking the number in the element with Pagination___activeLink class
driverGC.FindElement(By.XPath("//*[#id='searchBody']/div[2]/div[2]/div/a[3]")).Click(); // go to next page
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
wait.Until(ExpectedConditions.TextToBePresentInElementLocated(By.ClassName("Pagination___activeLink"), (i + 1).ToString()));
The assignment is as follows:
Total Sales
Use the attached file named Sales.txt. Create an application that
reads the file’s content into an array of double or decimal
displays the array’s content in a ListBox control,
calculates the total of the array’s values, average sales, largest sales, smallest sales
Display the Total Sales, Average sales, Highest Sales and Smallest Sales
Form should look similar to the following:
How do I get the data to display the Total/Average/High/Low Sales part of the image to display properly by typing the corresponding code?
I'd like to do this on my own so if you could provide an example that might relate to what I am doing that would really help.
Here's what I've been able to type up so far:
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.IO;
namespace Total_Sales
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void displayButton_Click(object sender, EventArgs e)
{
//declaring array
const int SIZE = 100;
decimal[] sales = new decimal[SIZE];
//varible to hold amount stored in array
int count = 0;
decimal additionHolder = 0;
//declaring streamreader
StreamReader inputFile;
//opening the sales file
inputFile = File.OpenText("../../Sales.txt");
try
{
//pull contents from file into array while there is still items
//to pull and the array isnt full
while (!inputFile.EndOfStream && count < sales.Length)
{
sales[count] = decimal.Parse(inputFile.ReadLine());
count++;
}
//close the file
inputFile.Close();
//display contents in listbox
for (int index = 0; index < count; index++)
{
ListBox.Items.Add(sales[index]);
}
//add all the values
for (int index = 0; index < sales.Length; index++)
{
additionHolder += sales[index];
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Here are two solutions. The first using an array, the second using a List. In both example's I presume that the textboxes for total, average, min and max sales are called TotalSales, AverageSales, MinSales and MaxSales.
private void displayButton_Click(object sender, EventArgs e)
{
const int SIZE = 100;
decimal[] sales = new decimal[SIZE];
int count = 0;
decimal totalSales, averageSales, minSales, maxSales;
StreamReader inputFile;
inputFile = File.OpenText("../../Sales.txt");
try
{
while (!inputFile.EndOfStream && count < sales.Length)
{
sales[count] = decimal.Parse(inputFile.ReadLine());
minSales = count == 0 ? sales[count] : Math.Min(minSales, sales[count]);
maxSales = count == 0 ? sales[count] : Math.Max(maxSales, sales[count]);
totalSales += sales[count];
ListBox.Items.Add(sales[count]);
count++;
}
inputFile.Close();
averageSales = totalSales / sales.Length;
TotalSales.Text = totalSales;
AverageSales.Text = averageSale;
MinSales.Text = minSales;
MaxSales.Text = maxSales;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Using a List and Linq:
private void displayButton_Click(object sender, EventArgs e)
{
List<decimal> sales = new List<decimal>(); // notice: no size limitation
StreamReader inputFile;
inputFile = File.OpenText("../../Sales.txt");
try
{
while (!inputFile.EndOfStream)
{
var sale = decimal.Parse(inputFile.ReadLine());
sales.Add(sale);
ListBox.Items.Add(sale);
}
inputFile.Close();
TotalSales.Text = sales.Sum();
AverageSales.Text = sales.Average();
MinSales.Text = sales.Min();
MaxSales.Text = sales.Max();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
As you can see this code is much more concise.
BTW, I wrote this code without Visual Studio at hand so it might contain some typo's.
After you read values from file just use Linq methods and set Text property of yours TextBox controls.
var total = sales.Sum();
var avg = sales.Average();
var min = sales.Min();
var max = sales.Max();
totalTextBox.Text = total.ToString(); //example for TextBox named totalTextBox
remember to add using :)
using System.Linq;
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm currently working with a project that a book has assigned for me (Head First C#, 3rd Edition) and I'm facing some problems with my code.
The whole project is based on a gambling game that 3 guys can participate in.
The gambling game consists of the 3 guys betting on 4 dogs that can randomly win a race on a track.
One of the problems is when a guy bets a bigger amount of money than he has, the program sets the value of Amount to 0.
I don't know why I'm not seeing the obvious mistake or not but I really appreciate the help if someone would offer it.
The code for the whole program is as follows:
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 if (MyBet.Amount > Cash)
MyLabel.Text = Name + " doesn't have that amount of money";
else
MyLabel.Text = MyBet.GetDescription();
if (Cash >= 0)
{
//2.Set the label on my radio button to show my cash ("Joe has 43 dollars")
MyRadioButton.Text = Name + " has " + Cash + " bucks";
}
else
{
MyRadioButton.Text = Name + " has no cash left";
}
}
public void ClearBet()
{
//1.Reset my bet so it's zero
MyBet = null;
}
public bool PlaceBet(int Amount, int Dog)
{
//1.Place a new bet and store it in my bet field
this.MyBet = new Bet();
//2.Return true if the guy had enough money to bet
if (Cash >= Amount)
{
Cash = Cash - Amount; // Remove the amount bet
MyBet.Amount = Amount;
MyBet.Dog = Dog;
MyBet.Bettor = this;
UpdateLabels();
return true;
}
else if (Cash < Amount)
{
return false;
}
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);
}
}
}
Greyhound.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
namespace A_Day_at_the_Races
{
public class Greyhound
{
public int StartingPosition; // Where 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()
{
// Move forward either 1, 2, 3 or 4 spaces at random
int x = Randomizer.Next(1, 4);
// Update the position of my PictureBox on the form
Point p = MyPictureBox.Location;
p.X += x;
MyPictureBox.Location = p;
// Return true if I won the game
if (p.X >= RacetrackLength)
{
return true;
}
else
{
return false;
}
}
public void TakeStartingPosition ()
{
// Reset starting position of PictureBox
StartingPosition = 0;
}
}
}
Bet.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 = new Guy(); // The guy who placed the bet
public string GetDescription()
{
// Return a string that says who placed the bet, how much cash
// was bet, and which dog he bet on ("Joe bets 8 on dog #4").
if (Amount > 0 && Amount < Bettor.Cash)
{
return Bettor.Name + " bets $" + Amount + " on dog #" + Dog;
}
// If the amount is zero, no bet was placed; ("Joe hasn't placed
// a bet").
else if (Amount == 0)
{
return Bettor.Name + " hasn't placed a bet";
}
else if (Amount > Bettor.Cash)
{
return Bettor.Name + " doesn't have that amount of money";
}
else
{
return Bettor.Name + "'s bet";
}
}
public int PayOut(int Winner) // The parameter is the winner of the race
{
// If the dog won, return the amount bet.
if (Winner == Dog)
{
return Amount;
}
// Otherwise, return the negative of the amount bet.
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
// Joe
Bettors[0] = new Guy();
Bettors[0].Name = "Joe";
Bettors[0].MyRadioButton = joeRadioButton;
Bettors[0].MyLabel = joeBetLabel;
Bettors[0].Cash = 50;
Bettors[0].UpdateLabels();
// Bob
Bettors[1] = new Guy();
Bettors[1].Name = "Bob";
Bettors[1].MyRadioButton = bobRadioButton;
Bettors[1].MyLabel = bobBetLabel;
Bettors[1].Cash = 75;
Bettors[1].UpdateLabels();
// Al
Bettors[2] = new Guy();
Bettors[2].Name = "Al";
Bettors[2].MyRadioButton = alRadioButton;
Bettors[2].MyLabel = alBetLabel;
Bettors[2].Cash = 45;
Bettors[2].UpdateLabels();
// Local integers on distance and starting position of the Dogs
int StartPosition = pictureBoxDog1.Location.X;
int distance = pictureBox1.Width;
// Initialize all 4 Dogs
for (int i = 0; i < Dogs.Length; i++)
{
Dogs[i] = new Greyhound();
Dogs[i].Randomizer = Randomizer;
Dogs[i].RacetrackLength = distance;
Dogs[i].Location = Dogs[i].StartingPosition = StartPosition;
}
// Connect pictureboxes with MyPictureBox in the Dog class
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; // Number of the winner Dog
int num_winners = 0; // Amount of winners
// While none has won,
while (num_winners == 0)
{
for (int i = 0; i < Dogs.Length; i++)
{
// If a Dog has reached max length of the race track,
// increment number of winners and add 1 to i and save it
// to the winner variable
if (Dogs[i].Run())
{
num_winners++;
winner = i + 1;
}
}
Application.DoEvents();
System.Threading.Thread.Sleep(3);
}
// If there is more than one winner, show this message
if (num_winners > 1)
MessageBox.Show("We have " + num_winners + " winners");
// Otherwise if there are more than or equal to one winner,
// show this message
else if (num_winners >= 1)
MessageBox.Show("Dog #" + winner + " wins!");
// Place all Dogs in their starting positions
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)
{
// Bettor = Joe when his radio button is checked
SetBettor(0);
}
private void bobRadioButton_CheckedChanged_1(object sender, EventArgs e)
{
// Bettor = Bob when his radio button is checked
SetBettor(1);
}
private void alRadioButton_CheckedChanged_1(object sender, EventArgs e)
{
// Bettor = Al when his radio button is checked
SetBettor(2);
}
private void BetsButton_Click(object sender, EventArgs e)
{
// Place bet depending on the value of the two numericUpDowns
// (Amount & Dog)
CurrentBettor.PlaceBet((int)numericUpDownBet.Value, (int)numericUpDownDog.Value);
CurrentBettor.UpdateLabels();
}
private void SetBettor(int index)
{
// Set the current bettor and update the name label
// to the his name
CurrentBettor = Bettors[index];
NameLabel.Text = CurrentBettor.Name;
// If the Guy's bet isn't 0,
// then save the amount and the dog he's
// betting on
if (CurrentBettor.MyBet != null)
{
numericUpDownBet.Value = CurrentBettor.MyBet.Amount;
numericUpDownDog.Value = CurrentBettor.MyBet.Dog;
}
// Otherwise, make the value of the bet
// to the minimum on the numericUpDownBet
// and set the default Dog that is being
// bet on as the first 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)
{
// Reset Dogs to their default location when
// the Reset button is pressed
pictureBoxDog1.Location = new Point(22, 21);
pictureBoxDog2.Location = new Point(22, 63);
pictureBoxDog3.Location = new Point(22, 120);
pictureBoxDog4.Location = new Point(22, 170);
}
}
}
All answers are appreciated.
The problem is in the following code.
Here, a new bet is created (Amount defaults to 0 if not set otherwise!):
//1.Place a new bet and store it in my bet field
this.MyBet = new Bet();
Here, all relevant data is set for MyBet:
//2.Return true if the guy had enough money to bet
if (Cash >= Amount)
{
Cash = Cash - Amount; // Remove the amount bet
MyBet.Amount = Amount;
MyBet.Dog = Dog;
MyBet.Bettor = this;
UpdateLabels();
return true;
}
Here, no data is set for MyBet, so Amount remains 0:
else if (Cash < Amount)
{
return false;
}
This can not occur at all:
else
{
return false;
}
I PlaceBet - you create an empty Bet, and only then check, if the guy has enough cash. If he hasn't, then the empty Bet will stay empty - and its Amount field will remain at the default 0.
public bool PlaceBet(int Amount, int Dog)
{
//1.Place a new bet and store it in my bet field
this.MyBet = new Bet(); // EMPTY BET
//2.Return true if the guy had enough money to bet
if (Cash >= Amount)
{
Cash = Cash - Amount; // Remove the amount bet
MyBet.Amount = Amount;
MyBet.Dog = Dog;
MyBet.Bettor = this;
UpdateLabels();
return true;
}
else if (Cash < Amount)
{
// THE BET REMAINS EMPTY
return false;
}
else
{
return false;
}
}
Also, the "else" block will never happen - you can actually remove the else if (Cash < Amount) case.
//1.Place a new bet and store it in my bet field
this.MyBet = new Bet();
//2.Return true if the guy had enough money to bet
if (Cash >= Amount)
{
Cash = Cash - Amount; // Remove the amount bet
MyBet.Amount = Amount;
MyBet.Dog = Dog;
MyBet.Bettor = this;
UpdateLabels();
return true;
}
else if (Cash < Amount)
{
return false;
}
At (1) you are creating a new Bet object then if Cash < Amount at (2) you return false without setting this.MyBet to null.
The best solution would probably be to put this.MyBet = new Bet(); within the Cash >= Amount block.
I've created a Random Number Generator app. It allows the user to enter integers into min, max, and amount to gen. There are three buttons; generate, clear output, and save. All work except the save.
I've been working on this for about 6 hours now (not joking) and I still can't figure it out. I found this thread, but I don't understand how it is implemented:
How to store an integer value in isolated storage in wp7?
Here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Random_Number_Generator_by_Bailey.Resources;
using System.Windows.Input;
using System.IO.IsolatedStorage;
namespace Random_Number_Generator_by_Bailey
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
if (IsolatedStorageSettings.ApplicationSettings.Contains("minstorage"))
{
min1 = (int)IsolatedStorageSettings.ApplicationSettings["minstorage"];
string min1text = min1.ToString();
MinNumInput.Text = min1text;
}
// Retrieve settings
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
private int randomNumber(int min, int max)
{
Random random = new Random(Guid.NewGuid().GetHashCode());
return random.Next(min, max);
}
public void Randomize_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
{
int tester2;
if (!Int32.TryParse(MinNumInput.Text, out tester2))
{
OutputBox.Text = "You did not specify an integer for \"Minimum Number\" ";
return;
}
int tester3;
if (!Int32.TryParse(MaxNumInput.Text, out tester3))
{
OutputBox.Text = "You did not specify an integer for \"Maximum\" ";
return;
}
int tester;
if (!Int32.TryParse(AmountToGenInput.Text, out tester))
{
OutputBox.Text = "You did not specify an integer for \"Amount to generate\" ";
return;
}
int gen;
gen = Convert.ToInt32(AmountToGenInput.Text);
gen = int.Parse(AmountToGenInput.Text);
int min1;
min1 = Convert.ToInt32(MinNumInput.Text);
min1 = int.Parse(MinNumInput.Text);
int max1;
max1 = Convert.ToInt32(MaxNumInput.Text);
max1 = int.Parse(MaxNumInput.Text);
if (gen <= 100 && gen > 0)
{
for (int i = 0; i < gen; i++)
{
int random = randomNumber(min1, max1);
OutputBox.Text += " " + random;
}
}
else
{
if (gen > 100) { OutputBox.Text = "You cannot generate more than 100 numbers."; }
if (gen < 0) { OutputBox.Text = "You cannot generate less than 0 numbers."; }
}
}
private void ClearTextBox_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
{
OutputBox.Text = "";
}
private void SaveParameters(object sender, System.Windows.Input.GestureEventArgs e)
{
int gen;
gen = Convert.ToInt32(AmountToGenInput.Text);
gen = int.Parse(AmountToGenInput.Text);
int min1;
min1 = Convert.ToInt32(MinNumInput.Text);
min1 = int.Parse(MinNumInput.Text);
int max1;
max1 = Convert.ToInt32(MaxNumInput.Text);
max1 = int.Parse(MaxNumInput.Text);
//If the variables need to be strings:
//string gen = AmountToGenInput.Text;
//string min1 = MinNumInput.Text;
//string max1 = MaxNumInput.Text;
// Store the value
IsolatedStorageSettings.ApplicationSettings["minstorage"] = min1;
}
// Sample code for building a localized ApplicationBar
//private void BuildLocalizedApplicationBar()
//{
// // Set the page's ApplicationBar to a new instance of ApplicationBar.
// ApplicationBar = new ApplicationBar();
// // Create a new button and set the text value to the localized string from AppResources.
// ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
// appBarButton.Text = AppResources.AppBarButtonText;
// ApplicationBar.Buttons.Add(appBarButton);
// // Create a new menu item with the localized string from AppResources.
// ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
// ApplicationBar.MenuItems.Add(appBarMenuItem);
//}
}
}
If anyone could PLEASE help me, that would be great. Thank you.
You are using min1 in your constructor without declaring the variable.
min1 = (int)IsolatedStorageSettings.ApplicationSettings["minstorage"];
Change to
var min1 = IsolatedStorageSettings.ApplicationSettings["minstorage"];