C# GUI Dice Game pass by reference - c#

Ok I'm trying to make a GUI dice game where the dice numbers are represented in textboxes.
I have to create a class that represents the dice and at least one of my methods has to correctly pass parameters by reference. My problem is that I am not too experienced with classes or passing parameters
I get an error at
rd.RollDice1(ref dice1);
rd.RollDice2(ref dice2);
(I am sure I have not constructed the RollDice class incorrectly)
Please is there anyone that can help me?
here is my code so far:
public partial class Form1 : Form
{
private RollDice rd;
public Form1()
{
InitializeComponent();
rd = new RollDice();
}
private void button1_Click(object sender, EventArgs e)
{
int dice1, dice2;
const int EYE = 1;
const int BOX = 6;
rd.RollDice1(ref dice1);
rd.RollDice2(ref dice2);
string result = string.Format("{0}", dice1);
string result2 = string.Format("(0)", dice2);
textBox1.Text = result;
textBox2.Text = result;
if (dice1 == EYE && dice2 == BOX)
{
MessageBox.Show("You rolled a Snake Eyes!");
}
if (dice1 == BOX && dice2 == BOX)
{
MessageBox.Show("You rolled BoxCars!");
}
else
{
MessageBox.Show("You rolled a {0} and a {1}", dice1, dice2);
}
}
}
}
class RollDice
{
const int EYE = 1;
const int BOX = 6;
public int RollDice1(ref int dieValue1)
{
Random randomNums = new Random();
dieValue1 = randomNums.Next(1, 7);
return dieValue1;
}
public int RollDice2(ref int dieValue2)
{
Random randomNums = new Random();
dieValue2 = randomNums.Next(1, 7);
return dieValue2;
}
}
}

Passing a variable with ref requires that variable to be initialized with a default value. If you don't set the two dices with an initial value your compiler complains about "Use of unassigned local variable xxxxx"
private void button1_Click(object sender, EventArgs e)
{
const int EYE = 1;
const int BOX = 6;
int dice1 = EYE;
int dice2 = BOX;
rd.RollDice1(ref dice1);
rd.RollDice2(ref dice2);
.....
However looking at your code there is no need to pass that values using ref, you could simply get the return value
dice1 = rd.RollDice1();
dice2 = rd.RollDice2();
of course you should change the two methods in your class to remove the parameter passed by ref
class RollDice
{
Random randomNums = new Random();
public int RollDice1()
{
return randomNums.Next(1, 7);
}
public int RollDice2()
{
return randomNums.Next(1, 7);
}
}

Related

scoreboard - add score to the main score board - not working

I am trying to add a score to the current score, so when we are printing the output i want the earlier score to be added to +1 and then sum it up and print the new score. This do not work, i have tried many options, how could i solve this problemset? The output i get is 1 and the same output i showing after the first result.
namespace scoreboard
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public double regnut()
{
int score = 0;
return score = score + 1;
}
private void button1_Click(object sender, EventArgs e)
{
string input = textBox1.Text;
int score;
count();
}
void count()
{
string iny = textBox1.Text;
double score = 0;
if (iny == "t")
{
score = score + 1;
listBox1.Items.Add(score);
}
label1.Text = "Score: " + score;
}
}
}
It is because you are always initializing score back to zero. You need to have a variable which holds the current value of your score. Example as below:
private int currentScore = 0; // holds you current Score value
void count()
{
string iny = textBox1.Text;
int score = currentScore; // sets initial value based from the current Score
if (iny == "t")
{
score = score + 1; // increment value
listBox1.Items.Add(score);
}
currentScore = score; // store the value in the variable
label1.Text = "Score: " + currentScore.ToString();
}

Using a generic method in a C# class

Here is my current code:
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Random random = new Random();
public int[] randomInt = new int[20];
public double[] randomDouble = new double[20];
public string searchKey;
public int intOrDouble; // 0 if int, 1 if double
public static int Search<T>(T[] inputArray, T key) where T : IComparable<T>
{
for (int i = 0; i < 20; i++)
{
if (inputArray[i].CompareTo(key) == 0)
{
return i;
}
}
return -1;
}
public Form1()
{
InitializeComponent();
}
private void randomIntGeneration_Click(object sender, EventArgs e)
{
randomNumbersTextBox.Clear(); // empty the textbox
intOrDouble = 0; // this is for knowing which parameter to send to search method
// generate 20 random integers and display them in the textbox
for (int i = 0; i < 20; ++i)
{
randomInt[i] = random.Next(0, 100);
randomNumbersTextBox.Text += randomInt[i].ToString() + " ";
}
}
private void randomDoubleGenerator_Click(object sender, EventArgs e)
{
randomNumbersTextBox.Clear(); // empty the textbox
intOrDouble = 1; // this is for knowing which parameter to send to search method
// generate 20 random doubles and display them in the textbox
for (int i = 0; i < 20; ++i)
{
randomDouble[i] = random.NextDouble() + random.Next(0, 100);
randomNumbersTextBox.Text += randomDouble[i].ToString() + " ";
}
}
private void searchArrayButton_Click(object sender, EventArgs e)
{
searchKey = searchKeyTextBox.Text;
if(intOrDouble == 0) // int array passed
{
resultsTextBox.Text = Search(randomInt, searchKey).ToString();
}
else
{
resultsTextBox.Text = Search(randomDouble, searchKey).ToString();
}
}
}
}
What i am trying to do is use this generic method. The GUI allows the user to generate a random array of either ints or doubles. I then want to use the Search method in the searchArrayButton_Click control to display whether or not the "searchKey" value entered is in the array. The error I am getting is "The type arguments for method 'Form1.Search(T[], T)' cannot be inferred from the usage. Try specifying the type arguments explicitly." They appear toward the bottom of the code when I try to call Search twice in the searchArrayButton_Click control.
You're trying to search an array of int or double values for a string. As a result, your call to Search has two arguments with two different types. That doesn't match the function signature.
You need to convert whatever is in that textbox into the value you are searching for, either an int or a double.
if(intOrDouble == 0) // int array passed
{
resultsTextBox.Text = Search(randomInt, int.Parse(searchKey)).ToString();
}
else
{
resultsTextBox.Text = Search(randomDouble, double.Parse(searchKey)).ToString();
}

Class is not returning an object

it's not recognizing my lstSectionNumber (Tickets.TicketForm.lastSectionNumber is inaccessible due to its protection level). Hopefully I explained everything clearly, I'm just recently started learning C#, any help would be appreciated. Thank you in advance.
public class TicketOrder
{
private static int premiumTicket = 40;
private static int basicTicket = 20;
private static int serviceCharge = 2;
private TicketForm form = new TicketForm();
public double CalcTicketCost(int section, double quantity)
{
double amount = 0;
if (int.Parse(form.lstSectionNumber.SelectedItem.Value) <= 150)
{
amount = (quantity*premiumTicket) + (quantity*serviceCharge);
return amount;
}
else
{
amount = (quantity*basicTicket) + (quantity*serviceCharge);
}
return amount;
}
}
Code-behind:
public partial class TicketForm : System.Web.UI.Page
{
int myInt;
public const double premiumTicket = 40;
public const double basicTicket = 20;
public const double serviceCharge = 2;
TicketUser user = new TicketUser();
TicketOrder order = new TicketOrder();
protected void Page_Load(object sender, EventArgs e)
{
// This disables the unobtrusive validation in order to see the result
this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
// This will keep my five numbers in my list box without adding more with a refresh of a page
if (!IsPostBack)
{
Random RandomSection = new Random();
for (int i = 0; i < 5; i++)
{
// Created a list box with five random numbers from 1 to 300
myInt = RandomSection.Next(1, 300);
lstSectionNumber.Items.Add(myInt.ToString());
}
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
// I also added TextMode="Number"to my <asp:TextBox ID="txtNumberOfTickets"
// runat="server" Height="18px" Width="134px"></asp:TextBox> code in order
// to get rid of an error incase I left my txtNumberOfTicket empty
int section = Convert.ToInt32(lstSectionNumber.SelectedValue);
double ticketQuantity = Convert.ToInt32(txtNumberOfTickets.Text);
//This label displays users first and last names, number of tickers, seat section number and ticket price
lblPrice.Text = txtFirstName.Text + " " +
txtLastName.Text + ", " +
txtNumberOfTickets.Text + " " +
"Tickets in Section:" + " " +
lstSectionNumber.SelectedValue + "," +
" Total Cost is: " +
order.CalcTicketCost(section, ticketQuantity).ToString("C");
}
protected void btnCreateAccount_Click(object sender, EventArgs e)
{
user.firstName = txtFirstName.Text;
user.lastName = txtLastName.Text;
user.username = txtUserName.Text;
lblCreateAccount.Text = user.CreateAccount();
}
}
Simply give your constructor an empty body
change
public TicketOrder()
to
public TicketOrder() { }
TO solve your other problem, you are trying to make a NEW page, but asp.NET has already made a page for this page load and populated the values for you. You should Pass the current page object into your TicketOrder constructor and save instead.
Like so:
public TicketOrder(TicketForm form)
{
this.form = form;
}
and change in TicketOrder
private TicketForm form = new TicketForm();
to
private TicketForm form;
and change in TicketForm
TicketOrder order = new TicketOrder();
to
TicketOrder order;
public TicketForm()
{
this.order = new TicketOrder(this);
}
Well, I figured it out.
if (section <= 150)
{ amount = (quantity * premiumTicket) + (quantity * serviceCharge);
return amount;

Converting strings to int in C#

im pretty new to C# and i want to make a cardgame. What i have is a list of cards (strings) with names like c6, s3, h11, d13 where the character represents the colour and the number represents the value. When pressing a button the program takes a random string from the list and displays it in a textbox. From there the point of the game is to guess if the next random card will have a higher value or a lower value then the previous card.
What i want to do is to take the string from the textbox and turn it into a int so that i can compare the value of the previous card with the new one. Only problem is how do i get rid of the c in c6 so i can convert it by using parse.
This is my code.
public partial class MainWindow : Window
{
static Random rndmlist = new Random();
Random rndm = new Random();
List<string> deck = new List<string>();
int score = 0;
public MainWindow()
{
InitializeComponent();
}
private void test_Click(object sender, RoutedEventArgs e)
{
//disregard this
foreach (string j in deck)
{
testbox.Text += j + ", ";
}
}
private void btnstart_Click(object sender, RoutedEventArgs e)
{
//this is where i add all the cards to the list
for (int i = 1; i <= 13;)
{
deck.Add("c" + i);
i++;
}
for (int i = 1; i <= 13; )
{
deck.Add("s" + i);
i++;
}
for (int i = 1; i <= 13; )
{
deck.Add("h" + i);
i++;
}
for (int i = 1; i <= 13; )
{
deck.Add("d" + i);
i++;
}
}
private void btnbegin_Click(object sender, RoutedEventArgs e)
{
//this is where i take a random card from the list and display it in textBox2
int r = rndmlist.Next(deck.Count);
textBox2.Text = ((string)deck[r]);
//disregard this
testbox.Text += ((string)deck[r]) + ", ";
deck.Remove((string)deck[r]);
}
private void btnhigh_Click(object sender, RoutedEventArgs e)
{
//this is where i want to compare the cards.
}
}
Thank you in advance for reading this. (:
I'd better create a class Card, which represents a card, with 2 properties: Color and Number and implemented method Card.ParseFromString()
Try this,
string SubString = MyString.Substring(1);
But take care if the string is empty, it is an error case.
Assuming there will always be one (and only one) character before the number, you can simply do this:
string numberAsString = "c2".Substring(1);
And to make that an int:
int number = Int32.Parse(numberAsString);
You can use Regex to replace all alpha characters eg
string result = Regex.Replace(myString, #"[a-zA-Z\s]+", string.Empty);
string str = "c12";
var noChars = str.SubString(1); // take a new string from index 1
var number = Int32.Parse(noChars);

Generating a random number that can be accesed anywhere

Here is the beginning of my code:
public partial class Form1 : Form
{
static Random random = new Random();
int prevnum;
int currentnum;
public int GenerateRandomNumber()
{
return random.Next(1, 1000);
}
public Form1()
{
int randomNumber = random.Next(1, 1000);
InitializeComponent();
}
private void enterButton_Click(object sender, EventArgs e)
{
currentnum = Convert.ToInt32(guessBox.Text);
if (randomNumber < currentnum)
{
warmOrColdLabel.Text = "Too High";
if (currentnum > prevnum)
{
guessBox.BackColor = Color.Blue;
prevnum = currentnum;
}
else
{
guessBox.BackColor = Color.Red;
prevnum = currentnum;
}
}
if (randomNumber > currentnum)
{
warmOrColdLabel.Text = "Too Low";
if (currentnum > prevnum)
{
guessBox.BackColor = Color.Blue;
prevnum = currentnum;
}
else
{
guessBox.BackColor = Color.Red;
prevnum = currentnum;
}
}
if (randomNumber == currentnum)
{
guessBox.Enabled = false;
enterButton.Enabled = false;
playAgainButton.Enabled = true;
}
}
private void playAgainButton_Click(object sender, EventArgs e)
{
enterButton.Enabled = true;
guessBox.Enabled = true;
playAgainButton.Enabled = false;
}
}
The issue I have is getting a random number, it always puts out 0. I simply need a random number that I can put into different buttons and such. What am I doing wrong?
Edit: must be a random number between 1 and 1000.
You don't actually call RandomNumberHandler() anywhere. Also, you need to specify your range in the call to .Next() (e.g., random.Next(1000)+1 to get a number from 1 to 1000).
public partial class Form1 : Form
{
//other stuff from before
int randomNumber; //move this here
public Form1()
{
randomNumber = random.Next(1, 1000); //assign it here
InitializeComponent();
}
Main problem is randomNumber is initialized when the constructor is called, and thereafter when you access it you access the same value.
You should eliminate that instance variable, and instead simply make a new call to GenerateRandom().
In addition, you probably want to make your instance of Random a static variable:
static Random random =
Otherwise each time the class is unloaded and reloaded it will repeat the same sequence which would be less random (or rather, pseudo random).

Categories

Resources