Reputation: 151
I understand that this works and all but is there a better way of doing this ?
Button clicked = (Button)sender;
if (turn)
{
clicked.Text = player;
}
else {
clicked.Text = cpu;
}
turn = !turn;
Upvotes: 1
Views: 1026
Reputation: 6375
When you click a button it's click event handler is executed. This calls your tictactoe
function. In there your code is executed from top to bottom, which checks the .Text
of the first button in your array first and adjusts it. Then Your If..Else block ends. On the next click this repeats. This leads to the behaviour.
Instead you should cast the sender
object to Button
and only work on this. No need for the whole If..Else
block. Sender
is the object that raised the event (here: the button that was clicked).
public void tictactoe(object sender, EventArgs e)
{
Button b = (Button)sender;
if (string.IsNullOrEmpty(b.Text)) {
b.Text = player;
}
}
Afterwards you will also need to flip the player
from X
to O
or vice versa but you will find out how to do this I reckon. :-)
Upvotes: 6
Reputation: 125197
Change the tictactoe to this:
public void tictactoe(object sender, EventArgs e)
{
var button = (Button)sender;
if (button.Text == "")
button.Text = player;
}
Upvotes: 1