我正在制作这款简单的回合制“真人快打”游戏。有2个comboBoxes,您可以从中选择一些字符。单击攻击按钮时,会生成一个半随机的攻击值,该攻击值会降低对手的生命值。首先达到0 HP的人松动。
我正在制作Character类的2个实例(从comboBoxes中检索)。单击“攻击”按钮时,将创建两个实例。问题在于,每次用户单击ATTACK时,都会再次创建2个实例,因此HP会重置为默认值。角色由名称,健康点,伤害组成。
private void button_Attack_Click(object sender, EventArgs e)
{
Character P1 = (Character)comboBox_CharacterSelectionP1.SelectedItem;
Character P2 = (Character)comboBox_CharacterSelectionP2.SelectedItem;
double HP_1;
double HP_2;
double DMG_1 = P1.Attack();
double DMG_2 = P2.Attack();
if (P1.Counter % 2 == 0)
{
HP_1 = P1.HealthPoints;
HP_2 = P2.HealthPoints;
label_Player1_HP.Text = HP_1.ToString();
label_AttackValueP1.Text = DMG_1.ToString();
label_Message.Text = $"{P1.Name} throws a punch";
HP_2 -= DMG_1;
label_Player2_HP.Text = HP_2.ToString();
P1.Counter++;
}
else { //... }
}
我必须在攻击按钮空间之外创建2个实例。我在哪里声明和初始化它们以便在攻击功能中使用它们? (=>这样,HP不会在用户每次单击攻击按钮时都被重置)
这2个实例是:
Character P1 = (Character)comboBox_CharacterSelectionP1.SelectedItem;
Character P2 = (Character)comboBox_CharacterSelectionP2.SelectedItem;
这是Windows Forms应用程序的图片
答案 0 :(得分:0)
“您的问题不是由实例引起的,不是在方法中创建的。只是不在播放器实例中存储新的HP值。HP_1和HP_2变量是局部的。– dymanoid” / p>
此评论帮助了我,谢谢。
我的错误我为HP设置了局部变量,我想这没有更新。一旦将它们替换为Character类的HealthPoints属性,它便可以正常工作。新代码如下:
private void button_Attack_Click(object sender, EventArgs e)
{
button_Play.Enabled = false;
Character P1 = (Character)comboBox_CharacterSelectionP1.SelectedItem;
Character P2 = (Character)comboBox_CharacterSelectionP2.SelectedItem;
if (P1.Counter % 2 == 0)
{
double DMG_1 = P1.Attack();
label_Player1_HP.Text = P1.HealthPoints.ToString("F3");
label_AttackValueP1.Text = $"Damage inflicted: {DMG_1.ToString("F3")}";
label_Message.Text = $"{P1.Name} throws a punch";
P2.HealthPoints -= DMG_1;
label_Player2_HP.Text = P2.HealthPoints.ToString("F3");
P1.Counter++;
}
else...