I'm building a boardgame...game in Mathematica. I have the board state represented as a matrix. It's a two player game, and each player (let's call them A & B) only has one type of piece or 'marker':
0 0 0 0 0 0
0 A A B 0 0
0 A A B 0 0
0 B A A 0 0
0 0 0 0 0 0
0 0 0 0 0 0
I want to include an edit/board setup mode. For reasons that have to do with rules/mechanics of the game itself, when the user selects a space to clear it (set to 0), I need to check the 8 adjacent spaces around it and clear those as well if they contain the same player's markers. For example, if the user clicked the 'A' in the 3rd row and column in the above matrix, I want the surrounding As to automatically get set to 0 as well, leaving the Bs alone. Is it possible to write this logic for checking the 8 adjacent spaces without using repetitive If statements? E.g.:
clicked=board[[row,col]];
If[board[[row-1,col-1]]==clicked,board[[row-1,col-1]]=0];
If[board[[row,col-1]]==clicked,board[[row,col-1]]=0];
If[board[[row+1,col-1]]==clicked,board[[row+1,col-1]]=0];
.
.
.
If[board[[row+1,col+1]]==clicked,board[[row-1,col-1]]=0]
board[[row,col]]=0;
It'd only be about 10 lines of code but it sure is ugly and a pain in the neck when it comes to readability/maintainability etc. Is there a better way to do it?
Edit: Yes, row and col can be the first and last rows and columns of the board matrix. That is something important I forgot to mention. Representing A and B pretty much the same in my real code. Just using LR (left right) and UD (up down) for the player's names.
A
andB
in your code? $\endgroup$ – Martin Ender Apr 27 '16 at 8:26row
orcol
be the first or last row or column of the board? $\endgroup$ – Martin Ender Apr 27 '16 at 8:30