# Connect 4 Initializing the board

조회 수: 21(최근 30일)
The Legend 2019년 12월 15일
편집: The Legend 2019년 12월 16일
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!

댓글을 달려면 로그인하십시오.

### 채택된 답변

Image Analyst 2019년 12월 15일
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

댓글을 달려면 로그인하십시오.

### 추가 답변(1개)

The Legend 2019년 12월 15일
bump
##### 댓글 수: 1표시숨기기 없음
The Legend 2019년 12월 15일
bump

댓글을 달려면 로그인하십시오.

### Community Treasure Hunt

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

Start Hunting!

Translated by