Skip to content

Instantly share code, notes, and snippets.

@mikehibm
Created January 12, 2019 20:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikehibm/597b782773596687ecf1822f59049334 to your computer and use it in GitHub Desktop.
Save mikehibm/597b782773596687ecf1822f59049334 to your computer and use it in GitHub Desktop.
computerPlayer1.ts
const thinkProc = () => {
self.addEventListener(
'message',
function(e) {
console.log('Worker called: ', e.data);
const board: BoardState = e.data.board;
let result = { row: -1, col: -1 };
const placeableCells: CellState[] = [];
board.cells.forEach((row) => {
row.forEach((cell) => {
if (cell.placeable) placeableCells.push(cell);
});
});
if (placeableCells.length) {
const index = Math.floor(Math.random() * placeableCells.length);
const cell = placeableCells[index];
result = { row: cell.row, col: cell.col };
}
postMessage(result);
},
false
);
};
const thinkWorker = createWorker(thinkProc);
export default function(name?: string): Player {
return {
name: name || 'CPU-1',
isHuman: false,
think: async (board: BoardState) => {
const result = await thinkWorker.execute({ board: { cells: board.cells } });
await wait(WAIT_MSEC);
return result as Position;
},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment