Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function myFunc(coords) {
- let field = [
- [false, false, false],
- [false, false, false],
- [false, false, false],
- ];
- let currentPlayer = "X";
- while (coords.length > 0) {
- let [row, col] = coords.shift().split(" ");
- row = Number(row);
- col = Number(col);
- if (
- isNaN(row) ||
- isNaN(col) ||
- row < 0 ||
- row >= field.length ||
- col < 0 ||
- col >= field.length
- ) {
- continue;
- }
- if (field[row][col]) {
- console.log("This place is already taken. Please choose another!");
- continue;
- }
- field[row][col] = currentPlayer;
- if (
- [
- checkRow(row, field),
- checkCol(col, field, currentPlayer),
- checkDiagonals(field),
- ].some((v) => v === true)
- ) {
- console.log(`Player ${currentPlayer} wins!`);
- for (let row = 0; row < field.length; row++) {
- console.log(field[row].join("\t"));
- }
- return;
- }
- if (!field.flat().includes(false)) {
- console.log("The game ended! Nobody wins :(");
- for (let row = 0; row < field.length; row++) {
- console.log(field[row].join("\t"));
- }
- return;
- }
- currentPlayer = currentPlayer === "X" ? "O" : "X";
- }
- function checkRow(row, field) {
- let currentRow = new Set(field[row]);
- return currentRow.size == 1 && !currentRow.has(false);
- }
- function checkCol(col, field, currentPlayer) {
- let currentCol = new Set();
- for (let row = 0; row < field.length; row++) {
- if (
- field[row][col] === false ||
- field[row][col] !== currentPlayer
- ) {
- return false;
- }
- }
- return true;
- }
- function checkDiagonals(field) {
- let diagonal1 = new Set();
- let diagonal2 = new Set();
- for (let row = 0; row < field.length; row++) {
- diagonal1.add(field[row][row]);
- diagonal2.add(field[row][field.length - 1 - row]);
- }
- if (
- (diagonal1.size === 1 && !diagonal1.has(false)) ||
- (diagonal2.size === 1 && !diagonal2.has(false))
- ) {
- return true;
- }
- return false;
- }
- }
- // myFunc(["0 0", "1 1", "0 1", "1 2", "0 2", "2 2", "1 2", "2 2", "2 1"]);
- // myFunc(["0 0", "0 1", "0 2", "1 1", "2 0", "2 1", "1 2", "2 2", "2 1"]);
- myFunc(["0 2", "0 1", "1 1", "0 0", "2 0", "2 1", "1 2", "2 2", "2 1"]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement