Created
May 11, 2018 19:34
-
-
Save abeforgit/152f52aaad4d7b6261d968b6ac2d21ba to your computer and use it in GitHub Desktop.
This file contains 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
class Quixo { | |
constructor(size, init = '') { | |
this.alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; | |
this.size = size; | |
this.grid = []; | |
for (let i = 0; i < size; i += 1) { | |
this.grid.push(new Array(size).fill('-')); | |
} | |
try { | |
if (init) { | |
init.split('').forEach((char, index) => { | |
if (!['-', 'X', 'O'].includes(char)) { | |
throw "AssertionError: ongeldig rooster" | |
} | |
this.grid[Math.floor(index / size)][index % size] = char; | |
}); | |
} | |
} catch (e) { | |
throw "AssertionError: ongeldig rooster" | |
} | |
} | |
positie(pos) { | |
let letter = pos.charAt(0); | |
let num = parseInt(pos.substring(1)); | |
let x = this.alpha.indexOf(letter.toUpperCase()); | |
let y = num - 1; | |
if (x > this.size - 1 || y > this.size - 1) { | |
throw "AssertionError: ongeldige positie"; | |
} | |
if (!(x === this.size - 1) && !(y === this.size - 1) && !(x === 0) && !(y === 0)) { | |
throw "AssertionError: ongeldige positie"; | |
} | |
return [y, x]; | |
} | |
toString() { | |
let rslt = ''; | |
this.grid.forEach(row => rslt += row.join('') + '\n'); | |
return rslt.substring(0, rslt.length - 1); | |
} | |
beurt(symbol, posfrom, posto) { | |
if (!['X', 'O'].includes(symbol) || posto === posfrom){ | |
throw "AssertionError: ongeldige beurt"; | |
} | |
try { | |
let from = this.positie(posfrom); | |
let to = this.positie(posto); | |
if (![symbol, '-'].includes(this.grid[from[0]][from[1]])) { | |
throw "AssertionError: ongeldige beurt"; | |
} | |
if (from[1] === to[1]) { | |
this.putcol(symbol, from, to[0] === 0); | |
} else { | |
this.putrow(symbol, from, to[1] === 0); | |
} | |
} catch (e) { | |
throw "AssertionError: ongeldige beurt"; | |
} | |
return this; | |
} | |
isCorner(pos) { | |
let poslist = [0, this.grid.length]; | |
return poslist.includes(pos[0]) && poslist.includes(pos[1]); | |
} | |
putcol(symbol, from, top) { | |
let col = from[1]; | |
if (top) { | |
for (let i = from[0]; i >= 1; i -= 1) { | |
this.grid[i][col] = this.grid[i - 1][col]; | |
} | |
this.grid[0][col] = symbol; | |
} else { | |
for (let i = from[0]; i < this.grid.length - 1; i += 1) { | |
this.grid[i][col] = this.grid[i + 1][col] | |
} | |
this.grid[this.grid.length - 1][col] = symbol; | |
} | |
} | |
putrow(symbol, from, front) { | |
let row = from[0]; | |
if (front) { | |
this.grid[row].unshift(symbol); | |
this.grid[row].splice(from[1] + 1, 1); | |
} else { | |
this.grid[row].push(symbol); | |
this.grid[row].splice(from[1], 1); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment