Created
May 13, 2022 22:26
-
-
Save supasympa/0b44f42d1228caa77d5f62b83a90257a to your computer and use it in GitHub Desktop.
Simple JavaScript Connect four
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function pubSubRegistry(){ | |
const subscriptions = []; | |
return { | |
publish: function publish(event) { | |
subscriptions.forEach(function(subscription) { | |
subscription(event); | |
}); | |
}, | |
subscribe: function subscribe(fn){ | |
subscriptions.push(fn); | |
}, | |
unsubscribe: function unsubscribe(fn){ | |
subscriptions.splice(subscriptions.indexOf(fn), 1); | |
}, | |
}; | |
} | |
const eventRegistry = pubSubRegistry(); | |
type Board = string[][]; | |
const board: Board = Array(6).fill(Array(7).fill('.')); | |
type Move = { vector: [number, number], piece: string, board: Board }; | |
type UpdatedBoardEvent = Board; | |
function nextMove(move: Move): Board { | |
const updatedBoard = move.board.map((row, rowIndex) => { | |
return row.map((cell, columnIndex) => { | |
if (rowIndex === move.vector[0] && columnIndex === move.vector[1]){ | |
return move.piece; | |
} | |
return cell; | |
}); | |
} | |
return updatedBoard; | |
} | |
eventRegistry.subscribe((updateBoard) => { | |
setBoardState(updateBoard); | |
console.log(updateBoard.map(r => r.join('')).join('\n')); | |
}); | |
let boardState = board; | |
const getBoardState = (): Board => boardState; | |
const setBoardState = (newBoardState): void => boardState = newBoardState | |
const m = (p, x, y) => { | |
eventRegistry.publish(nextMove({ | |
vector: [x, y], | |
piece: p, | |
board: getBoardState() | |
})); | |
} | |
m('x', 5, 0); | |
m('o', 5, 1); | |
m('x', 4, 0); | |
m('o', 5, 2); | |
m('x', 4, 1); | |
m('o', 5, 3); | |
m('x', 5, 4); | |
m('o', 5, 1); | |
m('x', 5, 3); | |
m('o', 3, 1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment