In my C# game TextQuest, The fighting system is in progress now and I ran into a problem.
If the player misses the Monster misses too (always at the same time). Here is the used code:
private void button1_Click(object sender, EventArgs e)
{
Monster_Class mc = new Monster_Class();
Account_Class ac = new Account_Class();
if (hitOrMiss())
{
int hit = -1;
hit = mc.hitAmount(ac.getAtk(Properties.Settings.Default.CurrentUser), mc.getDef(monster));
mhealth -= hit;
if (hit == -1)
{
setText("You missed.");
}
else
{
setText("You hit " + hit + ".");
}
monsterHit();
update();
}
else
{
setText("You missed.");
monsterHit();
}
}
private void monsterHit()
{
Monster_Class mc = new Monster_Class();
Account_Class ac = new Account_Class();
if (hitOrMiss())
{
int hit = -1;
hit = mc.hitAmount(mc.getAtk(monster), ac.getDef(Properties.Settings.Default.CurrentUser));
phealth -= hit;
if (hit == -1)
{
addText(monster + " missed.");
}
else
{
addText(monster + " hit " + hit + ".");
}
}
else
{
addText(monster + " missed.");
}
}
private bool hitOrMiss()
{
bool hit = true;
Random rand = new Random();
if (rand.Next(101) < 15)
{
hit = false;
}
return hit;
}
public int hitAmount(int Atk, int Def)
{
int hit = -1;
Random rand = new Random();
int deturm = rand.Next(6);
try
{
hit = ((Atk + deturm * 3) / Def + 1) / 2;
if (hit == 0)
{
hit = 1;
}
}
catch { }
return hit;
}
Also if you have a better Idea for the amount of damage done please let me know. since I just kinda threw numbers and symbols together
You don’t want to create a new Random object every time you need a random number. Otherwise I suspect you will get always the same number! Define a global Random object once and use it in every request for random numbers.