How to make a chess board with layout?

Hi am trying to implement a little game using vaadin (just for fun).

So I need to have buttons display as a chess board.
That is to say: a square of 8x8 buttons in the middle of the page.

How could I do that with layouts of vaadin 11 ?

Here a untested snipped:

PlainVerticalLayout lines = new PlainVerticalLayout();
PlainHorizontalLayout line;

int width = 8;
int counter = 0;

for(int i=0;i<width;++i) {
	line = new PlainHorizontalLayout();
	for(int j=0;j<width;++j) {
		if(counter % 2 == 0) {
			line.add(new BlackButton());
		} else {
			line.add(new WhiteButton());
		}
		++counter;
	}
	lines.add(line);
}

add(lines);

Plain___Layout means no padding, no margin, no spacing.

Greetz

(I don’t have much help to offer, only some observations, sorry.)

A game board with Layouts is a pretty tricky case. Layout components typically have an undefined amount of self-contained children in a one-dimensional list. All of these defining characteristics (undefined amount, self-contained children and one-dimensional list) are not great for a game board - in the typical case, a board has a fixed amount of rows and columns, so a defined amount of children in a two-dimensional array.

You can simulate an array with nested layouts by creating a horizontal “row” layout with a fixed number of child nodes (each representing a cell on the game board), and then repeating row layouts enough times to have a full board. This approach is not great for several reasons. Just from the top of my head:

  • in order to have working columns, each row must have a fixed amount of fixed width components at all time. You can’t remove a chess piece from row 6 and move it to row 7 without breaking everything unless you add some extra code for replacing the pieces with empty slots and such in there.
  • there are no sanity checks built in. If someone wants to put 12 pieces on one row, the layout will happily oblige (unless you manually code a check to prevent such an action).
  • typical game scenarios involve things like moving pieces from (x1, y1) to (x2, y2) or checking if (x, y) is unoccupied etc. etc… You’ll need to do all of this manually and you can’t just access a specific square directly.
  • generally, you’ll probably want to store the game state in a two-dimensional array and what you have is a list of lists

If I had to do it, I’d probably start with a plain old html <table> element with a fixed amount of rows and columns inside a PolymerTemplate. You still have a lot of things to manage there, but at least you won’t need to spend a ton of effort with the neat positioning of the rows and the columns.

-Olli