Published
Edited
Jan 31, 2022
Insert cell
# Raw Logic Javascript Example
Insert cell
ROWS = 6
Insert cell
COLUMNS = 7
Insert cell
state = Array(ROWS * COLUMNS).fill(0)

Insert cell
/**
* Note: Returns a new array and does not modify the one passed in!
*
* state: array of integers representing game state; 0 == empty; 1 == player1; 2 == player2 piece
* column: column to drop a piece in (0 to 6)
* [ 0 1 2 3 4 5 6 ]
* player: n where 1 == player1; 2 == player2
*/
function dropPiece(state, column, player) {
const newState = Array.from(state);
for (let i = 0; i < ROWS; i++) {
const current = state[i * COLUMNS + column]
if (current == 0) {
newState[i * COLUMNS + column] = player;
return newState; // return new state;
}
}
throw new Error("column maxed out!");
}
Insert cell
// Format state to string for outputting text
function renderBoard(state) {
let board = '';
for (let i = 0; i < ROWS; i++) {
let row = '';
for (let j = 0; j < COLUMNS; j++) {
row += state[i*COLUMNS + j];
}
board = row + "\n" + board;
}
return "\n" + board;
}
Insert cell
// Stack player 2 tile in 4th column
renderBoard(
dropPiece(state, 3, 1)
);
Insert cell
// Stack player 2 tile in 3rd column
renderBoard(
dropPiece(state, 2, 2)
);
Insert cell
// Stack player 1 tile over player 2 in 4th column
renderBoard(
dropPiece(
dropPiece(state, 3, 2),
3,
1
)
)
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more