public partial class Form1 : Form
{
private System.Windows.Forms.Button[] _buttonArray;
private bool _isx;
private bool _isGameOver;
public Form1()
{
InitializeComponent();
}
public void InitTicTacToe()
{
for (int i = 0; i < 9; i++)
{
_buttonArray[i].Text = "";
_buttonArray[i].ForeColor = Color.Black;
_buttonArray[i].BackColor = Color.LightGray;
_buttonArray[i].Font = new System.Drawing.Font("Microsoft Sans Serif", 24F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
}
this._isx = true;
this._isGameOver = false;
}
private void ClickHandler(object sender, System.EventArgs e)
{
Button tempButton = (Button)sender;
if (_isGameOver)
{
MessageBox.Show("Game telah berakhir, Silahkan klik file -> New untuk mulai lagi.", "Game End", MessageBoxButtons.OK);
return;
}
if (tempButton.Text != "")
{
return;
}
if (_isx)
tempButton.Text = "X";
else
tempButton.Text = "O";
_isx = !_isx;
this._isGameOver = result.CheckWinner(_buttonArray);
}
private void Form1_Load(object sender, EventArgs e)
{
_buttonArray = new Button[9] { but1, but2, but3, but4, but5, but6, but7, but8, but9 };
for (int i = 0; i < 9; i++)
this._buttonArray[i].Click += new System.EventHandler(this.ClickHandler);
InitTicTacToe();
}
private void menunew_Click(object sender, EventArgs e)
{
InitTicTacToe();
}
private void menukeluar_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
public class result
{
static private int[,] Winners = new int[,]
{
{0,1,2},
{3,4,5},
{6,7,8},
{0,3,6},
{1,4,7},
{2,5,8},
{0,4,8},
{2,4,6},
};
static public bool CheckWinner(Button[] myControls)
{
bool gameOver = false;
for (int i = 0; i < 8; i++)
{
int a = Winners[i, 0], b = Winners[i, 1], c = Winners[i, 2];
Button b1 = myControls[a], b2 = myControls[b], b3 = myControls[c];
if (b1.Text == "" || b2.Text == "" || b3.Text == "")
continue;
if (b1.Text == b2.Text && b2.Text == b3.Text)
{
b1.BackColor = b2.BackColor = b3.BackColor = Color.LightCoral;
b1.Font = b2.Font = b3.Font = new System.Drawing.Font("Microsoft Sans Serif", 32F, System.Drawing.FontStyle.Italic & System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
gameOver = true;
MessageBox.Show(b1.Text + " .... menang...!!!", "Tamat", MessageBoxButtons.OK);
break;
}
}
return gameOver;
}
}
}
Dalam bermain game Derek
siapa yang lebih duluan sejajar
keatas ,ke samping dan miring
, X atau O itu yang akan menjadi pemenangnya, jika X dan O
tidak ada sejajar berarti games tersebut draw. sebaiknya mengulangi lagi game tersebut yaitu dengan klik
File – New
Berikut adalah screenshot dari games Derek
X winner
|
Game draw
No comments:
Post a Comment