Using MatLab: Begin the code using a variable that defines the board size – we w
ID: 3745727 • Letter: U
Question
Using MatLab:
Begin the code using a variable that defines the board size – we will create an 10x10 “board” by initializing a matrix that is size 10x10 using the ‘zeros’ command. From here forward, we are going to use the symbol ‘0’ to indicate a space that is unoccupied on the board.
2. Write code that will randomly place pieces on the board. Specifically, iterate through every available space on the board and randomly place a “0”, “1”, or “2”; these will correspond to open spaces, a red piece, and a black piece, respectively. Remember that checkers only involves light or dark spaces, so make sure you have scheme for valid placement (i.e. that only places pieces on one color).
a. Use the “randi” command to generate random integers of “0”, “1” and “2”.
3. Now, randomly select any space on the board (occupied or not) and place a red king there. We’ll use the number “3” to designate the king.
a. Make sure that your code is capable of placing the king on any suitable space. Do not hard code a specific space or limit it in any other way.
4. After placing the king, employ a series of if statements that will check for available moves. For each direction, print out text that describes the available move(s).
Explanation / Answer
clear all;
A=zeros(10);
for i=1:10
for j=1:10
A(i,j) = randi([0 2]);
end
end
a = randi([1 100]);
left = ceil(a/10);
right = a-(left-1)*10;
if right==0
right=right+1;
end
A(left, right) = 3;
disp('Current Board:');
disp(A);
disp(' ');
fprintf('Current Position(%d , %d) ',left,right);
if left~=1 && right~=1
if A(left-1,right)~=1
fprintf('Possible play: Position(%d , %d) ',left-1,right);
end
if A(left-1,right-1)~=1
fprintf('Possible play: Position(%d , %d) ',left-1,right-1);
end
if A(left, right-1)~=1
fprintf('Possible play: Position(%d , %d) ',left,right-1);
end
end
if left==1 && right~=1
if A(left,right-1)~=1
fprintf('Possible play: Position(%d , %d) ',left,right-1);
end
end
if left~=1 && right==1
if A(left-1,right)~=1
fprintf('Possible play: Position(%d , %d) ',left-1,right);
end
end
if left~=10 && right~=10
if A(left+1,right)~=1
fprintf('Possible play: Position(%d , %d) ',left+1,right);
end
if A(left+1,right+1)~=1
fprintf('Possible play: Position(%d , %d) ',left+1,right+1);
end
if A(left, right+1)~=1
fprintf('Possible play: Position(%d , %d) ',left,right+1);
end
end
if left==10 && right~=10
if A(left,right+1)~=1
fprintf('Possible play: Position(%d , %d) ',left,right+1);
end
end
if left~=10 && right==10
if A(left+1,right)~=1
fprintf('Possible play: Position(%d , %d) ',left+1,right);
end
end
if left~=1 && right~=10
if A(left-1, right+1)~=1
fprintf('Possible play: Position(%d , %d) ',left-1,right+1);
end
end
if left~=10 && right~=1
if A(left+1, right-1)~=1
fprintf('Possible play: Position(%d , %d) ',left+1,right-1);
end
end