clean-tictactoe/CleanTicTacToe/MainForm.cs
Michael Chen 27f6efb58a
Added proprietary user interface.
Added most game logic.
2023-04-19 20:18:10 +02:00

60 lines
2.1 KiB
C#

using System;
using System.Drawing;
using System.Windows.Forms;
using TicTacToe;
namespace CleanTicTacToe {
public partial class MainForm : Form {
private const int BUTTONSIZE = 100;
private readonly Grid _grid;
private readonly Button[,] _pbxs = new Button[Grid.GRIDSIZE, Grid.GRIDSIZE];
public MainForm() {
InitializeComponent();
_grid = new Grid();
_grid.ExpectNextTurn += Grid_ExpectNextTurn;
_grid.GameOver += Grid_GameOver;
for (var x = 0; x < Grid.GRIDSIZE; x++)
for (var y = 0; y < Grid.GRIDSIZE; y++) {
var pictureBox = new Button() {
Location = new Point(x * BUTTONSIZE, y * BUTTONSIZE),
Width = BUTTONSIZE,
Height = BUTTONSIZE,
Tag = (x, y)
};
pictureBox.Click += Grid_Click;
Controls.Add(pictureBox);
_pbxs[x, y] = pictureBox;
}
}
private void Grid_GameOver(object sender, Player e) {
TslStatus.Text = $"Player {e} has won!";
_grid.Reset();
}
private void Grid_ExpectNextTurn(object sender, Player e) {
TslStatus.Text = $"Player {e} must now pick a spot!";
}
private void Grid_Click(object sender, EventArgs e) {
if (!(sender is Button pictureBox))
throw new InvalidProgramException("Expected picturebox as sender!");
(var x, var y) = ((int x, int y))pictureBox.Tag;
TslStatus.Text = $"Spot {x},{y} clicked!";
try {
_grid.PickSpot(x, y);
} catch (Exception ex) {
TslStatus.Text = ex.Message;
}
RefreshPbxs();
}
private void RefreshPbxs() {
for (var x = 0; x < Grid.GRIDSIZE; x++)
for (var y = 0; y < Grid.GRIDSIZE; y++) {
_pbxs[x, y].Text = $"{Grid.GetPlayerChar(_grid[x, y])}";
}
}
}
}