0

在我的 C# 游戏 TextQuest 中,战斗系统正在进行中,我遇到了一个问题。如果玩家错过了怪物也错过了(总是同时)。这是使用的代码:

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;
}

另外,如果您对造成的伤害量有更好的想法,请告诉我。因为我只是把数字和符号放在一起

4

2 回答 2

5

您不想每次需要随机数时都创建一个新的 Random 对象。否则我怀疑你会得到相同的号码!定义一个全局 Random 对象一次,并在每个随机数请求中使用它。

于 2013-01-23T01:25:39.833 回答
0

作为一个侧面提示,我会稍微改变设计,例如:

bool hitOrMiss(Entity attacker, Entity defender)
{
  // do your calcs
}

int doAttack(Entity attacker, Entity defender)
{
  if (hitOrMiss(attacker, defender)) {
    // calculate damage
    return dmg;
  }
  else
    return 0;
}

private void attachPhase(object sender, EventArgs e)
{
  Player player = ...
  Monster monster = ...

  int playerDmg = doAttack(player, monster);
  int monsterDmg = doAttack(monster, player);

  if (playerDmg > 0) {

  }

  if (monsterDmg > 0) {

  }
}
于 2013-01-23T01:31:11.953 回答