Tic-Tac-Toe game weird behavior of the program
I'm working on a mini project in JAVA which is building an X/O game , I'm
in the part where the program will figure out which is the next sign to
show weither is it "X" or "O". So I setup an eventlistener and wait for
the user to click the button. and I do the following for each button :
Button7.setBounds(50,180,80,30);
panel.add(Button7);
Button7.addActionListener(new ActionListener () {
@Override
public void actionPerformed(ActionEvent event) {
int countX = 0;
int countO = 0;
int difxo = 0;
String xo = "";
if (Button1.getText().equals("X"))
{
countX += 1;
}
else if (Button2.getText().equals("X"))
{
countX += 1;
}
else if (Button3.getText().equals("X"))
{
countX += 1;
}
else if (Button4.getText().equals("X"))
{
countX += 1;
}
else if (Button5.getText().equals("X"))
{
countX += 1;
}
else if (Button6.getText().equals("X"))
{
countX += 1;
}
else if (Button7.getText().equals("X"))
{
countX += 1;
}
else if (Button8.getText().equals("X"))
{
countX += 1;
}
else if (Button9.getText().equals("X"))
{
countX += 1;
}
else
{
countX += 0;
}
if (Button1.getText().equals("O"))
{
countO += 1;
}
else if (Button2.getText().equals("O"))
{
countO += 1;
}
else if (Button3.getText().equals("O"))
{
countO += 1;
}
else if (Button4.getText().equals("O"))
{
countO += 1;
}
else if (Button5.getText().equals("O"))
{
countO += 1;
}
else if (Button6.getText().equals("O"))
{
countO += 1;
}
else if (Button7.getText().equals("O"))
{
countO += 1;
}
else if (Button8.getText().equals("O"))
{
countO += 1;
}
else if (Button9.getText().equals("O"))
{
countO += 1;
}
difxo = countX - countO;
if (difxo == 0)
{
xo = "X";
}
else if (difxo == 1)
{
xo = "O";
}
countX = 0;
countO = 0;
Button7.setText(xo);
}
});
So you can figure out that in X/O game (When the beginning sign is X) we
can pretend which sign is after by doing a basic subsraction. If the
result of the sustraction is 1 : the sign in the button must be "O", and
if the result is 0 the sign must be "X". But in the program that I made,
repeating the same for each button click event I get "X" "O" "X" "X" "X"
instead of getting "X" "O" "X" "O" ... etc I don't know why is that
happening because each time I count "X"s and "O"s then do the
substraction. Thanks.
No comments:
Post a Comment