我对java很陌生,我刚刚做了一个井字游戏。我成功地设法只用 AI 创建了它,但是当我尝试添加一个额外的选项来与另一个人一起玩时,我遇到了一个问题。我试图这样做,如果turncount(定义为静态int)是偶数,它将检查按下按钮的文本是否等于空,如果是,则将其设置为x。否则,它应该检查按下按钮的文本是否等于空,如果是,则将其设置为 O。无论出于何种原因,它似乎都不会检查 else 语句。以下代码非常重复,因此您只需阅读前 12 行左右即可了解我的意思。感谢您的帮助!
动作监听器方法:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == topl)
if (turncount % 2 == 0)
{
if (topl.getText().equals(""))
{
topl.setText("X");
turncount += 1;
winchecker();
}
else
if (topl.getText().equals(""))
{
topl.setText("O");
turncount += 1;
winchecker();
}
}
if (e.getSource() == midup)
{
if (turncount % 2 == 0)
{
if (midup.getText().equals(""))
{
midup.setText("X");
turncount += 1;
winchecker();
}
else
if (midup.getText().equals(""))
{
midup.setText("O");
turncount += 1;
winchecker();
}
}
}
if (e.getSource() == topr)
{
if (turncount % 2 == 0)
{
if (topr.getText().equals(""))
{
topr.setText("X");
turncount += 1;
winchecker();
}
else
if (topr.getText().equals(""))
{
topr.setText("O");
turncount += 1;
winchecker();
}
}
}
if (e.getSource() == midl)
{
if (turncount % 2 == 0)
{
if (midl.getText().equals(""))
{
midl.setText("X");
turncount += 1;
winchecker();
}
else
if (midl.getText().equals(""))
{
midl.setText("O");
turncount += 1;
winchecker();
}
}
}
if (e.getSource() == mid)
{
if (turncount % 2 == 0)
{
if (mid.getText().equals(""))
{
mid.setText("X");
turncount += 1;
winchecker();
}
else
if (mid.getText().equals(""))
{
mid.setText("O");
turncount += 1;
winchecker();
}
} }
if (e.getSource() == midr)
{
if (turncount % 2 == 0)
{
if (midr.getText().equals(""))
{
midr.setText("X");
turncount += 1;
winchecker();
}
else
if (midr.getText().equals(""))
{
midr.setText("O");
turncount += 1;
winchecker();
}
}
}
if (e.getSource() == botl)
{
if (turncount % 2 == 0)
{
if (botl.getText().equals(""))
{
botl.setText("X");
turncount += 1;
winchecker();
}
else
if (botl.getText().equals(""))
{
botl.setText("O");
turncount += 1;
winchecker();
}
}
}
if (e.getSource() == midlow)
{
if (turncount % 2 == 0)
{
if (midlow.getText().equals(""))
{
midlow.setText("X");
turncount += 1;
winchecker();
}
else
if (midlow.getText().equals(""))
{
midlow.setText("O");
turncount += 1;
winchecker();
}
}
}
if (e.getSource() == botr)
{
if (turncount % 2 == 0)
{
if (botr.getText().equals(""))
{
botr.setText("X");
turncount += 1;
winchecker();
}
else
if (botr.getText().equals(""))
{
botr.setText("O");
turncount += 1;
winchecker();
}
}
}
}