大家好,我正在做一个跳棋游戏。我有一个宣布获胜者的方法,我希望是否有一种使用循环的方法。目前,它可以正常工作:),但是我不得不对其进行硬编码,而不是使用逻辑。

public void checkWinner() {
  if (pictureBoxs[0].Image != bc && pictureBoxs[2].Image != bc && pictureBoxs[4].Image != bc && pictureBoxs[6].Image != bc && pictureBoxs[9].Image != bc && pictureBoxs[11].Image != bc &&
    pictureBoxs[13].Image != bc && pictureBoxs[15].Image != bc && pictureBoxs[16].Image != bc && pictureBoxs[18].Image != bc && pictureBoxs[20].Image != bc && pictureBoxs[22].Image != bc &&
    pictureBoxs[25].Image != bc && pictureBoxs[27].Image != bc && pictureBoxs[29].Image != bc && pictureBoxs[31].Image != bc && pictureBoxs[32].Image != bc && pictureBoxs[34].Image != bc &&
    pictureBoxs[36].Image != bc && pictureBoxs[38].Image != bc && pictureBoxs[41].Image != bc && pictureBoxs[43].Image != bc && pictureBoxs[45].Image != bc && pictureBoxs[47].Image != bc &&
    pictureBoxs[48].Image != bc && pictureBoxs[50].Image != bc && pictureBoxs[52].Image != bc && pictureBoxs[54].Image != bc && pictureBoxs[57].Image != bc && pictureBoxs[59].Image != bc &&
    pictureBoxs[61].Image != bc && pictureBoxs[63].Image != bc) {
    MessageBox.Show("White is the winner!");

  } else if (pictureBoxs[0].Image != wc && pictureBoxs[2].Image != wc && pictureBoxs[4].Image != wc && pictureBoxs[6].Image != wc && pictureBoxs[9].Image != wc && pictureBoxs[11].Image != wc &&
    pictureBoxs[13].Image != wc && pictureBoxs[15].Image != wc && pictureBoxs[16].Image != wc && pictureBoxs[18].Image != wc && pictureBoxs[20].Image != wc && pictureBoxs[22].Image != wc &&
    pictureBoxs[25].Image != wc && pictureBoxs[27].Image != wc && pictureBoxs[29].Image != wc && pictureBoxs[31].Image != wc && pictureBoxs[32].Image != wc && pictureBoxs[34].Image != wc &&
    pictureBoxs[36].Image != wc && pictureBoxs[38].Image != wc && pictureBoxs[41].Image != wc && pictureBoxs[43].Image != wc && pictureBoxs[45].Image != wc && pictureBoxs[47].Image != wc &&
    pictureBoxs[48].Image != wc && pictureBoxs[50].Image != wc && pictureBoxs[52].Image != wc && pictureBoxs[54].Image != wc && pictureBoxs[57].Image != wc && pictureBoxs[59].Image != wc &&
    pictureBoxs[61].Image != wc && pictureBoxs[63].Image != wc) {
    MessageBox.Show("Black is the winner!");
  }
}


我不能使用从0到63的for循环,因为pictureBoxs[1]pictureBoxs[3]设置为no,这会产生错误!

最佳答案

使用LINQ仅捕获不是PictureBoxnull,然后测试Image的值:

if (pictureBoxs.Where(p => p != null).All(p => p.Image != bc))
    MessageBox.Show("White is the winner!");
else if (pictureBoxs.Where(p => p != null).All(p => p.Image != wc))
    MessageBox.Show("Black is the winner!");

09-19 16:31