C# random image in picturebox and assign value - c#

I'm creating a card game using C#. I want to assign a value to my card example: Ace(image) = 1; and I want to random it. Here's my code:
private void button1_Click(object sender, EventArgs e)
{
Random cards = new Random();
card = cards.Next(0, 9);
switch (card)
{
case 0:
pictureBox1.Image = Properties.Resources.king_d;
pictureBox2.Image = Properties.Resources.jack_s;
break;
case 1:
pictureBox1.Image = Properties.Resources.ace_c;
pictureBox2.Image = Properties.Resources.ten_d;
break;
}
}
}

new the random out of the method. you can take it from a singleton class (read this) or for simplicity if you are in windows app make it static like this:
static Random cards = new Random();
private void button1_Click(object sender, EventArgs e)
{
card = cards.Next(0, 9);
switch (card)
{
case 0:
pictureBox1.Image = Properties.Resources.king_d;
pictureBox2.Image = Properties.Resources.jack_s;
break;
case 1:
pictureBox1.Image = Properties.Resources.ace_c;
pictureBox2.Image = Properties.Resources.ten_d;
break;
}
}
}
Update
The best way to have a card that contains a value, picture, etc. is to have a new class for that. Since PictureBox already has most properties and behaviors that you need, I recommend using it.
The code has to be something like this:
Public Class MyCard:PictureBox
{
public int GamePoint {get;set;}
}
Then instead of using PictureBox in your code, use this.
To be honest I like to encapsulate the code a bit more so I prefer this:
Public Class MyCard:PictureBox
{
public CardType CardType {set;get;}
public int GamePoint {get{ return (int)this.CardType; }}
public MyCard(CardType _cardType)
{
CardType = _cardType;
}
}
enum CardType
{ Ace=1,
King=2,
...
}

Although I don't see an actual question in your question, I think you want to do this in a simpler way.
Well first of all, don't create a Random every time the method is called, make it a class-level variable and initialize it:
private static Random cards = new Random();
Currently, you're using a switch to decide what to show in the two picture boxes. If the random number is 0, put these two cards, if the number is 1, put those two cards... This means that each number from 0 to 9 corresponds to two Bitmaps.
You can use a dictionary to map 0 to 9 to Tuple<Bitmap, Bitmap>, but I think it's better to use an array.
What you basically need to do is to declare an array that stores those Tuple<Bitmap, Bitmap>. Let's call it CardCombinations. I recommend you to put this array in a utility class called CardUtility or something. Then, you can just do:
card = cards.Next(0, 9);
pictureBox1.Image = CardUtility.CardCombinations[card].Item1;
pictureBox2.Image = CardUtility.CardCombinations[card].Item2;
As you can see, this greatly reduced the code in the button1_Click method. Now we can declare the array that I was talking about.
It's pretty simple:
public static Tuple<Bitmap, Bitmap>[] CardCombinations => new[] {
new Tuple<Bitmap, Bitmap>(Properties.Resources.king_d, Properties.Resources.jack_s),
...
};
"But that's still verbose!" you cried. Protip: you can use the using static directive to shorten the bitmap names to king_d and jack_s!
using static SomeNamespace.Properties.Resources;

Related

Getting resources Image path from Picturebox [duplicate]

I have a program which has 16 grid tiles using picturebox but only uses 5 images, the rest of the tiles are just a black image.
I would like to be able to tell which image the 'user' clicks on.
I have a method called image_Click(object sender, EventArgs e)
I have an if statement inside this method that states:
if (peckedSquare.BackColor == Color.Black)
{
System.Diagnostics.Debug.WriteLine("Pecked a black square");
return;
}
This sends a String that lets me know when a black square has been clicked.
Is there an easy way to perhaps say:
//pseudo code:
if (peckedSquare.ImageName == pigeon1.png)
{
System.Diagnostics.Debug.WriteLine("Pecked Pigeon number 1");
}
I have googled my query but I have not found any suitable answers.
//EDIT
I have just re-read my code.
I was assigning each picture to a picturebox square using a randomnumber.
I had this random number as a variable, so I can just use that variable to determine which image was clicked.
ie.
if (randomNumber == 1)
{
System.Diagnostics.Debug.WriteLine("Pecked Pigeon number 1");
}
or better than that
pigeonSelected = randomNumber + 1 //as I am using an array to store the images
System.Diagnostics.Debug.WriteLine("Pecked Pigeon Number {0}", pigeonSelected);
As quick & dirty solution I would use Tag property for that, null for black tiles and file path for the others (and it's always available, even if your image comes from resources), something like this:
if (peckedSquare.Tag == null)
{
Debug.WriteLine("Pecked a black square");
}
else
{
switch (Path.GetFileName(peckedSquare.Tag.ToString()))
{
case "pigeon1.png":
break;
}
}
Of course when you create tiles you have to store file path in Tag:
PictureBox tile = new PictureBox();
tile.Image = Image.FromFile(path); // Or another source, of course
tile.Tag = path;
As alternative you may even use Name property for this, each control is named (primary for designer-code integration) but if you create controls at run-time you can set that value to anything you want (not only valid identifiers). Same usage as above just no need to call ToString().
How to Improve?
Please let me say this solution is not very OOP. Even without a big refactoring we can do little bit better. Note that you can store whatever you want in Tag property. A number, a simple string unrelated to file name or even (maybe better) a class or an enum that represents that image (to delegate action to that object). This is a very raw example:
abstract class Tile {
public abstract void Activate();
}
sealed class EmptyTile : Tile {
public virtual void Activate() {
Debug.WriteLine("Pecked a black square");
}
}
sealed class ImageTile : Tile {
public ImageTile(string content) {
_content = content;
}
public virtual void Activate() {
Debug.WriteLine(_content);
}
private string _content;
}
In this way in your click event handler you can do this:
((Tile)peckedTile.Tag).Activate();
No need to check what's inside or to compare with null. No if and no switch, just don't forget to put proper object (ImageTile or BlackTile) when you create tiles.
Use PictureBox.Load(string) method to load images from file. Then the file path will be stored in the
PictureBox.ImageLocation property:
A call to the Load method will overwrite the ImageLocation property, setting ImageLocation to the URL value specified in the method call.
So you can write for example:
if (peckedSquare.ImageLocation.EndsWith("pigeon1.png"))
{
System.Diagnostics.Debug.WriteLine("Pecked Pigeon number 1");
}
I think you could do something like the following:
private List<PictureBox> pictures = null;
string[] ImageNames = new string[]
{
"images\\test_1.jpg",
"images\\test_2.jpg"
};
private void Form1_Load(object sender, EventArgs e)
{
pictures = new List<PictureBox>();
for (var idx = 0; idx < ImageNames.Length; idx++)
{
pictures.Add(new PictureBox());
pictures[idx].Image = new Bitmap(ImageNames[idx]);
pictures[idx].Click += OnClick;
// you'll want to set the offset and everything so it shows at the right place
Controls.Add(pictures[idx]);
}
}
private void OnClick(object sender, EventArgs eventArgs)
{
// you'll definitely want error handling here
var ImageName = ImageNames[pictures.IndexOf((PictureBox) sender)];
}
You can see that in the click method you will be able to get the image name, which is what you are looking for I believe.
As others have said, you can also use the "Tag" property assuming you weren't already using this for some other purpose. The nice thing about tag is you can probably also edit it through the form designer which allows you to lay things out a little more nicely than the automatic layout I used above. Good luck!
You can do something like this using the Tag property like #Adriano suggested:
public Form1()
{
InitializeComponent();
pictureBox1.Click += pictureBox_Click;
pictureBox2.Click += pictureBox_Click;
pictureBox3.Click += pictureBox_Click;
// ...
pictureBox1.Tag = "picture1.png";
pictureBox2.Tag = "picture2.png";
pictureBox3.Tag = "picture3.png";
}
void pictureBox_Click(object sender, EventArgs e)
{
PictureBox pb = sender as PictureBox;
if (pb.BackColor != Color.Black)
Debug.WriteLine(pb.Tag.ToString());
else
Debug.WriteLine("Black image");
}

How to progress my Five Dice game

I am learning to program, in particular starting with C# where I have been experimenting with dice games to become more familiar and to improve myself. I am now trying to create a basic game in windows forms, where two players roll 5 dice and keep record of their score.
Rules:
Begin with 5 dice
If a 1 or 4 appears, player scores no points and those dice are removed. Otherwise add all the dice to total
Continue with remaining dice until there a no dice left over
So far I have an Image array which stores all my dice images in my resources and a button which will roll the dice. What I need help with specifically is being able to remove the penalized dice (setting that particular one back to blank) and allowing the player to continue rolling their remaining dice until none are left.
At the moment I am unsure as to where I can further this and maybe I am biting off more than I can chew. I am loving coding and any help would be much appreciated.
Here's an image of the interface:
public partial class Form1 : Form
{
Image[] diceImages;
int[] dice;
int[] diceResults;
Random random;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
diceImages = new Image[7];
diceImages[0] = Properties.Resources.blank;
diceImages[1] = Properties.Resources.one;
diceImages[2] = Properties.Resources.two;
diceImages[3] = Properties.Resources.three;
diceImages[4] = Properties.Resources.four;
diceImages[5] = Properties.Resources.five;
diceImages[6] = Properties.Resources.six;
dice = new int[5] { 0, 0, 0, 0, 0 };
random = new Random();
diceResults = new int[6] { 0, 0, 0, 0, 0, 0 };
}
private void btn_rollDice_Click(object sender, EventArgs e)
{
RollDice();
GetResults();
ResetResults();
}
private void RollDice()
{
for (int i = 0; i < dice.Length; i++)
{
dice[i] = random.Next(1, 7);
switch (dice[i])
{
case 1:
diceResults[0]++;
break;
case 2:
diceResults[1]++;
break;
case 3:
diceResults[2]++;
break;
case 4:
diceResults[3]++;
break;
case 5:
diceResults[4]++;
break;
case 6:
diceResults[5]++;
break;
}
}
lbl_dice1.Image = diceImages[dice[0]];
lbl_dice2.Image = diceImages[dice[1]];
lbl_dice3.Image = diceImages[dice[2]];
lbl_dice4.Image = diceImages[dice[3]];
lbl_dice5.Image = diceImages[dice[4]];
}
private void GetResults()
{
bool oneRoll = false, fourRoll = false;
for (int i = 0; i < diceResults.Length; i++)
{
if (diceResults[i] == 1 && diceResults[i] == 4)
{
oneRoll = true;
fourRoll = true;
}
}
}
private void ResetResults()
{
}
}
The code you posted has at least a couple of oddities that don't seem to fit with your description:
The code simply increments an element in an array (diceResults) when a given die value is rolled (i.e. the element corresponds to the die value, not the die's order in the game). From your description, I would have expected the code to simply add the die value to a single sum variable.
In your GetResults() method, your code compares the individual element values in the diceResults to the values 2 and 5. In other words, for each possible die value, if that value comes up twice or five times, you set both flags. There are a number of reasons this is strange, but the biggest, most obvious one is that a single variable (i.e. the element diceResults[i]) can never have two different values at the same time. I.e. that array element will never be both 2 and 5, as the if statement requires.
Given those issues, I'm more inclined to focus on the original specification than to trust the code too much in terms of trying to understand what your intended behavior of the code actually is. :)
It seems that the basic question is how best to remove die from play. The suggestion (in the comments above) to use a list to track the dice is certainly a workable one. In that approach, one would iterate through the list to set each element, and if the roll for a given element ever comes up as 1 or 4, remove that element before moving on.
Having done that, one would just iterate through the list again to set the die value images, using the "blank" image for any die beyond the length of the list.
But there is a simpler way, and based on your statement "setting that particular one back to blank", which seems to imply that each blank die should appear in the same position in which it was rolled, it seems like that simpler way might be preferable to you.
Specifically, after rolling the dice, just scan through the dice array and reset any 1 and 4 values to 0, and use this 0 value as a special "sentinel" value to indicate that die is now blank.
Note that however you do this (with a list, or just setting values to 0), there is also the question of whether to show the user the actual 1 and 4 rolls, or to immediately set those rolls to a blank die. I'm going to assume the former, but it would be very easy to implement it the other way instead. (As always, the beginning of good code is a good specification…right now, your specification is a bit light on detail, and thus is vague and ambiguous).
Taking that approach, your code might look something more like this:
public partial class Form1 : Form
{
#region Declaration
Image[] diceImages;
Label[] labels;
int[] dice;
int diceTotal;
bool checkOnesAndFours;
Random random;
#endregion
#region Initialiazation;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Initializing an array this way eliminates the chance of having
// a typo in the array index for the assignment.
diceImages = new Image[]
{
Properties.Resources.blank,
Properties.Resources.one,
Properties.Resources.two,
Properties.Resources.three,
Properties.Resources.four,
Properties.Resources.five,
Properties.Resources.six
};
// Arrays are always initialized with the elements having their default
// values, so there's no need to specify `0` values for `int` arrays explicitly
dice = new int[5];
random = new Random();
diceTotal = 0;
// For the purposes of setting the dice images, it will be helpful
// to keep the control references in an array. This is both convenient
// and, again, helps guard against typographical errors
labels = new Label[]
{
lbl_dice1,
lbl_dice2,
lbl_dice3,
lbl_dice4,
lbl_dice5
};
}
#endregion
#region Private Methods
private void btn_rollDice_Click(object sender, EventArgs e)
{
RollDice();
}
private void RollDice()
{
bool rolledOneOrFour = false;
int rollTotal = 0;
for (int i = 0; i < dice.Length; i++)
{
if (checkOnesAndFours)
{
// First, clear any 1 or 4 from the previous roll
if (dice[i] == 1 || dice[i] == 4)
{
dice[i] = 0;
}
// Then, ignore any blank die
if (dice[i] == 0)
{
continue;
}
}
dice[i] = random.Next(1, 7);
if (dice[i] == 1 || dice[i] == 4)
{
rolledOneOrFour = true;
}
rollTotal += dice[i];
}
if (!rolledOneOrFour)
{
diceTotal += rollTotal;
}
checkOnesAndFours = true;
for (int i = 0; i < labels.Length; i++)
{
labels[i].Image = diceImages[dice[i]];
}
}
#endregion
}
NOTE: it was not entirely clear to me what you mean to do when a 1 or 4 comes up. Taking what you wrote literally, I understand it to mean that if any die shows a 1 or 4 on a roll, that none of the dice count for that roll. The above code is implemented with that understanding in mind.
It occurs to me that you might have instead meant that only the dice that show 1 or 4 are not counted for the roll, and that the other dice for that roll are still included. It would not be hard to change the above to accommodate that alternative specification.
NOTE: you'll also notice that I have made other changes to the code not technically required in order to address the immediate question. I added comments in the code itself to try to explain why I made those changes, and why I feel they make the code better.
Just for grins, here's a version that does use a list instead:
public partial class Form1 : Form
{
#region Declaration
Image[] diceImages;
Label[] labels;
List<int> dice;
int diceTotal;
bool checkOnesAndFours;
Random random;
#endregion
#region Initialiazation;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Initializing an array this way eliminates the chance of having
// a typo in the array index for the assignment.
diceImages = new Image[]
{
Properties.Resources.blank,
Properties.Resources.one,
Properties.Resources.two,
Properties.Resources.three,
Properties.Resources.four,
Properties.Resources.five,
Properties.Resources.six
};
// Lists must be initialized explicitly with their initial values, as by default
// they are initially empty.
dice = new List<int>(Enumerable.Repeat(0, 5));
random = new Random();
diceTotal = 0;
// For the purposes of setting the dice images, it will be helpful
// to keep the control references in an array. This is both convenient
// and, again, helps guard against typographical errors
labels = new Label[]
{
lbl_dice1,
lbl_dice2,
lbl_dice3,
lbl_dice4,
lbl_dice5
};
}
#endregion
#region Private Methods
private void btn_rollDice_Click(object sender, EventArgs e)
{
RollDice();
}
private void RollDice()
{
bool rolledOneOrFour = false;
int rollTotal = 0;
for (int i = 0; i < dice.Count; i++)
{
// Clear any 1 or 4 from the previous roll
if (checkOnesAndFours && (dice[i] == 1 || dice[i] == 4))
{
// Remove this die from play
dice.RemoveAt(i);
// The next list element to examine is now at the current i value
// and the for loop is going to increment i when the continue
// is executed, so decrement i in anticipation of that
// so that the loop moves on to the correct next element
i--;
continue;
}
dice[i] = random.Next(1, 7);
if (dice[i] == 1 || dice[i] == 4)
{
rolledOneOrFour = true;
}
rollTotal += dice[i];
}
if (!rolledOneOrFour)
{
diceTotal += rollTotal;
}
checkOnesAndFours = true;
for (int i = 0; i < labels.Length; i++)
{
labels[i].Image = i < dice.Count ? diceImages[dice[i]] : diceImages[0];
}
}
#endregion
}
Finally, note that neither of the above addresses a couple of other issues with the code:
Initializing the dice labels at the beginning of a game.
Resetting the entire game once the game has ended (i.e. there are no more dice left).
I leave these two items as an exercise for the reader (of course, if you run into problems with those specific issues, you may always post another question on Stack Overflow asking about each specifically).

2 instances of class using random number

So I am trying to learn some C#, currently on a short course on An Introduction to Programming. I have a question in my text book which is giving me pretty much simular results to this post Same random numbers from instantiated class
I have tried to follow the solution but get the same results every time, the task is to Roll two dice and display their numbers using 2 instances of a class. But like the post above the "dice" role the same number. If I call the same instance of the class twice and out put the values to separate labels I get completely different values like i want. here is the class:
namespace CH10_Ex10._5
{
public class ThrowDice
{
public ThrowDice()
{
}
private Random newRandom = new Random();
private int x;
public void Throw()
{
x = newRandom.Next(1, 7);
}
public int value
{
get
{
return x;
}
}
}
}
and here is my main form:
namespace CH10_Ex10._5
{
public partial class Form1 : Form
{
ThrowDice Die1;
ThrowDice Die2;
public Form1()
{
InitializeComponent();
Die1 = new ThrowDice();
Die2 = new ThrowDice();
}
private void button1_Click(object sender, EventArgs e)
{
Die1.Throw();
dieOneLabel.Text = Convert.ToString(Die1.value);
Die2.Throw();
dieTwoLabel.Text = Convert.ToString(Die2.value);
}
}
}
I have tried to find an answer with out opening a new post so i am sorry if this have been answered before. I am very green at this.
My understanding is that if i declare objects with new, then i am creating separate instances of the class and therefore when i call those objects they should run independently/separately, but use the same rules which are specified in my class. I have tried to debug and as i step through the code i see the 2 separate calls to the class and what it looks like is the call 1 generates a random number eg 6 and call 2 seems to generate 6 as well.
thanks in advance
The problem is that the random instance will be initialized with the current time since you're using the default constructor. Since that happens on two instances very quick they get the same seed here:
public Form1()
{
InitializeComponent();
Die1 = new ThrowDice();
Die2 = new ThrowDice();
}
You could make it static:
private static Random newRandom = new Random();
Random constructor:
The default seed value is derived from the system clock and has finite
resolution. As a result, different Random objects that are created in
close succession by a call to the default constructor will have
identical default seed values and, therefore, will produce identical
sets of random numbers.
However, Random is not thread safe. So you should have a look at this answer.
This is also really worth reading: C# in Depth: Random numbers which suggests to use ThreadLocal<T> which is new in .NET 4 instead of static with lock.
You can fix this using same random instance in both instances.For example you can add a constructor like this:
private Random newRandom;
public ThrowDice(Random rnd)
{
newRandom = rnd;
x = newRandom.Next(1, 7);
}
Then:
Random rnd = new Random;
public Form1()
{
InitializeComponent();
Die1 = new ThrowDice(rnd);
Die2 = new ThrowDice(rnd);
}
What i usually use :
private Random newRandom = new Random(Guid.NewGuid().GetHashCode());

How do you access the name of the image in a picturebox in Visual Studio using C#

I have a program which has 16 grid tiles using picturebox but only uses 5 images, the rest of the tiles are just a black image.
I would like to be able to tell which image the 'user' clicks on.
I have a method called image_Click(object sender, EventArgs e)
I have an if statement inside this method that states:
if (peckedSquare.BackColor == Color.Black)
{
System.Diagnostics.Debug.WriteLine("Pecked a black square");
return;
}
This sends a String that lets me know when a black square has been clicked.
Is there an easy way to perhaps say:
//pseudo code:
if (peckedSquare.ImageName == pigeon1.png)
{
System.Diagnostics.Debug.WriteLine("Pecked Pigeon number 1");
}
I have googled my query but I have not found any suitable answers.
//EDIT
I have just re-read my code.
I was assigning each picture to a picturebox square using a randomnumber.
I had this random number as a variable, so I can just use that variable to determine which image was clicked.
ie.
if (randomNumber == 1)
{
System.Diagnostics.Debug.WriteLine("Pecked Pigeon number 1");
}
or better than that
pigeonSelected = randomNumber + 1 //as I am using an array to store the images
System.Diagnostics.Debug.WriteLine("Pecked Pigeon Number {0}", pigeonSelected);
As quick & dirty solution I would use Tag property for that, null for black tiles and file path for the others (and it's always available, even if your image comes from resources), something like this:
if (peckedSquare.Tag == null)
{
Debug.WriteLine("Pecked a black square");
}
else
{
switch (Path.GetFileName(peckedSquare.Tag.ToString()))
{
case "pigeon1.png":
break;
}
}
Of course when you create tiles you have to store file path in Tag:
PictureBox tile = new PictureBox();
tile.Image = Image.FromFile(path); // Or another source, of course
tile.Tag = path;
As alternative you may even use Name property for this, each control is named (primary for designer-code integration) but if you create controls at run-time you can set that value to anything you want (not only valid identifiers). Same usage as above just no need to call ToString().
How to Improve?
Please let me say this solution is not very OOP. Even without a big refactoring we can do little bit better. Note that you can store whatever you want in Tag property. A number, a simple string unrelated to file name or even (maybe better) a class or an enum that represents that image (to delegate action to that object). This is a very raw example:
abstract class Tile {
public abstract void Activate();
}
sealed class EmptyTile : Tile {
public virtual void Activate() {
Debug.WriteLine("Pecked a black square");
}
}
sealed class ImageTile : Tile {
public ImageTile(string content) {
_content = content;
}
public virtual void Activate() {
Debug.WriteLine(_content);
}
private string _content;
}
In this way in your click event handler you can do this:
((Tile)peckedTile.Tag).Activate();
No need to check what's inside or to compare with null. No if and no switch, just don't forget to put proper object (ImageTile or BlackTile) when you create tiles.
Use PictureBox.Load(string) method to load images from file. Then the file path will be stored in the
PictureBox.ImageLocation property:
A call to the Load method will overwrite the ImageLocation property, setting ImageLocation to the URL value specified in the method call.
So you can write for example:
if (peckedSquare.ImageLocation.EndsWith("pigeon1.png"))
{
System.Diagnostics.Debug.WriteLine("Pecked Pigeon number 1");
}
I think you could do something like the following:
private List<PictureBox> pictures = null;
string[] ImageNames = new string[]
{
"images\\test_1.jpg",
"images\\test_2.jpg"
};
private void Form1_Load(object sender, EventArgs e)
{
pictures = new List<PictureBox>();
for (var idx = 0; idx < ImageNames.Length; idx++)
{
pictures.Add(new PictureBox());
pictures[idx].Image = new Bitmap(ImageNames[idx]);
pictures[idx].Click += OnClick;
// you'll want to set the offset and everything so it shows at the right place
Controls.Add(pictures[idx]);
}
}
private void OnClick(object sender, EventArgs eventArgs)
{
// you'll definitely want error handling here
var ImageName = ImageNames[pictures.IndexOf((PictureBox) sender)];
}
You can see that in the click method you will be able to get the image name, which is what you are looking for I believe.
As others have said, you can also use the "Tag" property assuming you weren't already using this for some other purpose. The nice thing about tag is you can probably also edit it through the form designer which allows you to lay things out a little more nicely than the automatic layout I used above. Good luck!
You can do something like this using the Tag property like #Adriano suggested:
public Form1()
{
InitializeComponent();
pictureBox1.Click += pictureBox_Click;
pictureBox2.Click += pictureBox_Click;
pictureBox3.Click += pictureBox_Click;
// ...
pictureBox1.Tag = "picture1.png";
pictureBox2.Tag = "picture2.png";
pictureBox3.Tag = "picture3.png";
}
void pictureBox_Click(object sender, EventArgs e)
{
PictureBox pb = sender as PictureBox;
if (pb.BackColor != Color.Black)
Debug.WriteLine(pb.Tag.ToString());
else
Debug.WriteLine("Black image");
}

Calling a instance value in a different method

I don't know how to access my instance in another method. I have this set of code.
Card rorbcard = new Card();
Deck deck = new Deck();
deck.Shuffle();
rorbcard = deck.TakeCard();
Start0:
Console.Clear();
Console.WriteLine("Allright lets play! Red or black?");
string userValue0 = Console.ReadLine();
switch (userValue0.ToLower())
{
case "red":
{
if (rorbcard.Suit.Equals(Suit.Diamonds))
{
Console.WriteLine("{0},\n Correct give 2 drinks",
rorbcard.ToString());
Thread.Sleep(2000);
}
else if (rorbcard.Suit.Equals(Suit.Hearts))
{
Console.WriteLine("{0},\n Correct give 2 drinks",
rorbcard.ToString());
Thread.Sleep(2000);
}
else
{
Console.WriteLine("{0},\n Wrong sucka take 2 drinks",
rorbcard.ToString());
Thread.Sleep(2000);
}
}
I am trying to use that rorbcard.ToString() in another method, but I cant figure out how to reference it. Here is the other method.
public void HighLow()
{
//highlow part of the game
Deck deck = new Deck();
deck.Shuffle();
Card highLow = new Card();
highLow = deck.TakeCard();
Start1:
Console.Clear();
Console.WriteLine("Your Hand:");
Grid.WriteAt(rorbcard.ToString(), 0, 1);
Console.WriteLine("\n\nDo you think that the next card will higher,lower,\n or
equal to the {0}. Enter high, low, or equal\n", rorbcard);
string uservalue1 = Console.ReadLine();
switch (uservalue1.ToLower())
{
case "high":
if (highLow.CardNumber > rorbcard.CardNumber) <-----Issue
{
Console.WriteLine("{0},\n Correct give 4 drinks",
highLow.ToString());
Thread.Sleep(2000);
}
else
{
Console.WriteLine("{0},\n Wrong drink 4\n", highLow.ToString());
Thread.Sleep(2000);
}
Thanks for your time in looking into this. I am stuck and have been for a bit.
You can do either
a. Pass as parameter to HighLow() like
public void HighLow(string rorbcard)
b. Create a class level variable. Assign value to it and use that value in HighLow() like
class MyClass
{
private string rorbCardClassLevel;
private void MyrorbCardMethod
{
//Other code lines.
//Inside case statement
rorbCardClassLevel = rorbcard.ToString();
}
private void HighLow()
{
//Use rorbCardClassLevel here.
}
}
All I needed to do was place my instances outside the methods and inside my class. Duh

Categories