Skip to content

Instantly share code, notes, and snippets.

@unstoppablecarl
Last active March 6, 2019 15:40
Show Gist options
  • Save unstoppablecarl/2dc6f7f9f5402e1f657f3c1106b54ce0 to your computer and use it in GitHub Desktop.
Save unstoppablecarl/2dc6f7f9f5402e1f657f3c1106b54ce0 to your computer and use it in GitHub Desktop.
SCRIPT-8
const ROW = 10;
const COL = 10;
const SQ = 7;
const VACANT = -1;
const FILL = 2;
// const DEBUG = 2;
let board = [];
for(let r = 0; r <ROW; r++){
board[r] = [];
for(let c = 0; c < COL; c++){
board[r][c] = VACANT;
}
}
initialState = {
board: board,
count: 0,
tick: 0,
piece: false
}
const drawSquare = (x, y, type) => {
let color;
x *= SQ;
y *= SQ;
let width = SQ - 1;
let height = SQ - 1;
if(type == VACANT){
color = 6;
rectStroke(x, y, width, height, color)
return
}
color = type;
rectFill(x, y, width, height, color)
rectStroke(x, y, width, height, color+1)
}
function drawBoard(board){
range(ROW).forEach((r) => {
range(COL).forEach((c) => {
drawSquare(c, r, board[c][r])
})
});
}
const piece = makePieceHandler();
update = (state, input, elapsed) => {
if(!state.piece){
state.piece = makePiece();
log(state.piece);
}
// state.board[4][6] = FILL;
state.tick += elapsed;
const updateInterval = 250;
if(state.tick < updateInterval){
return
}
state.tick = 0;
piece.update(state, input);
}
draw = (state) => {
clear()
drawBoard(state.board);
}
function makePiece(){
log('z');
return {
x: 4,
y: 0,
color: Math.floor(Math.random() * 6),
shape: [
[0,1,0],
[1,1,1]
]
}
}
function makePieceHandler(){
let piece;
let board;
return {
update(state){
piece = state.piece;
board = state.board;
if(hasCollision()){
state.piece = makePiece();
}
else{
movePiece();
}
}
}
function hasCollision(){
if(piece.y == 9) {
return true;;
}
let collision = false;
eachCollisionCoord((x, y) => {
if(board[x][y] !== VACANT){
collision = true;
}
});
return collision;
}
function eachCoord(callback){
piece.shape.forEach((row, y) => {
row.forEach((val, x) => {
callback(x, y, val);
})
})
}
function fillPiece(color){
eachCoord((x, y, val) => {
if(val){
board[piece.x + x][piece.y + y] = color;
}
});
}
function eachCollisionCoord(callback){
let bottomRowIndex = piece.shape.length - 1;
let bottomRow = piece.shape[bottomRowIndex];
let checkY = piece.y + bottomRowIndex + 1;
bottomRow.forEach((val, x) => {
if(val){
callback(piece.x + x, checkY);
}
});
}
function movePiece() {
fillPiece(VACANT);
piece.y += 1;
fillPiece(piece.color);
}
}
{
"lines": [
74,
83,
0,
0,
0,
0,
0,
0
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment