Connect 4 Initializing the board

6 views (last 30 days)
The Legend
The Legend on 15 Dec 2019
Edited: The Legend on 16 Dec 2019
Worked on / edited the code (this is what I came up with so far, don't know how to put it into code though):
clear;
close all;
clc;
N = 3
K = 4
boardInit = initializeBoard(N, K);
function [M, turn] = initializeBoard(N, K)
M = zeros(N+2,N+3) % Creates the board
% 1 Generate random column value
% 2 Check if the column doesn't already have K / N+3 (since uniform destr. in width) pieces
% 3 Check if the bottom most row already has a piece (so a value of 1 or 2)
% 4 If no piece, add value of 1 or 2 randomly (there should be an equal amount of pieces be added in the end (K red pieces and K yellow pieces)
% 5 If there is a piece, move one row up and check from step 3 again
% Repeat from 1 - 5
turn = randi(2,1,1)
end
How would I go about adding random yellow or red pieces (ones and twos) to the board. They have to start at the bottom (to simulate gravity, irl they would fall down too) and have to be randomly distributed.
I don't need a whole piece of code, just an idea of what I could use. All help is greatly appreciated!

Accepted Answer

Image Analyst
Image Analyst on 15 Dec 2019
You can use randi() or randperm() to get a random column to drop the piece into, if that's the strategy you want to use.
column = randi(size(M, 2), 1)
Now you need to find the top most row in your matrix M and drop the piece into the slot above that, as long as the top filled row is not 1, meaning the whole column is full.
thisColumn = M(:, column); % Extract this one column.
topRow = find(thisColumn ~= 0);
if isempty(topRow)
% No pieces are in this column yet. Drop the piece to the bottom.
row = size(M, 1); % This is the last row.
else
if topRow == 1
% All slots are filled. Don't let them place a piece in this column.
else
% Not all slots are filled so we can drop a piece in this column.
% Place it in the row above the highest piece that is in there now.
row = topRow - 1
end
end

More Answers (1)

The Legend
The Legend on 15 Dec 2019
bump

Categories

Find more on Board games in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!