I have a simple game in which clicking an image moving through an array of picture boxes grants the player a point and I plan to add another image to this so that a sub class grants the user a different amount of points when clicking on a different image. I'm wondering how to get a derived class to inherit a variable that is in the base class and change the numeric value.
Here are the relevant parts of my code:
public class Monster
{
public static int Score = 1;
public Monster()
{
}
}
class Skeleton:Monster
{
public Skeleton()
{
Score = 2;
}
}
public partial class Form1 : Form
{
PictureBox[] boxes;
int initialscore = 0;
public Form1()
{
InitializeComponent();
}
private void boxes_MouseClick(object sender, MouseEventArgs e)
{
for (int x = 0; x < 27; x++)
{
if (sender.Equals(boxes[x]))
{
Image grass = Image.FromFile("swamp.png");
PictureBox temp = (PictureBox)sender;
temp.Image = grass;
}
if (sender.Equals(boxes[x]))
{
PictureBox pb = (PictureBox)sender;
if (pb.Tag == "skeleton.png")
{
addScore(Monster.Score);
}
}
}
label1.Text = " Score: " +initialscore.ToString();
}
public void addScore(int add)
{
initialscore += add;
label1.Text = " Score: " + initialscore.ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
addScore(0);
}
}
How would I get the skeleton class to be able to have a different Score value to that of the Monster class? Would anything else need to be added/changed regarding Form1, and if so what would need to be done to maintain a working score system?
This should do the trick:
public class Monster
{
public Monster()
{
this.Score = 1;
}
public int Score
{
get;
set;
}
}
public class Skeleton : Monster
{
public Skeleton()
: base()
{
this.Score = 2;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.