initial commit

This commit is contained in:
Hector Alfaro
2019-09-24 05:56:34 -04:00
commit 14de4967c0
10 changed files with 245 additions and 0 deletions
+51
View File
@@ -0,0 +1,51 @@
export default class Game {
constructor (p1, p2) {
this.p1 = p1
this.p2 = p2
this.board = [[null, null, null], [null, null, null], [null, null, null]]
this.player = Math.random() < 0.5 ? this.p1 : this.p2
this.sym = 'X'
}
turn (row, col) {
col = col || row
this.board[row][col] = this.sym
}
nextPlayer () {
this.player = this.player === this.p1 ? this.p2 : this.p1
this.sym = this.sym === 'X' ? 'O' : 'X'
}
hasWinner () {
return this.rowWin() || this.colWin() || this.diagWin()
}
rowWin () {
let win = false
for (let r = 0; r < 3; r++) {
const row = this.board[r]
if (row[0] === null) { continue }
win = win || (row[0] === row[1] && row[0] === row[2])
}
return win
}
colWin () {
let win = false
for (let c = 0; c < 3; c++) {
const col = this.board
if (col[0][c] === null) { continue }
win = win || (col[0][c] === col[1][c] && col[0][c] === col[2][c])
}
return win
}
diagWin () {
const b = this.board
return ((b[0][0] !== null && b[0][0] === b[1][1] && b[0][0] === b[2][2]) ||
(b[0][2] !== null && b[0][2] === b[1][1] && b[0][2] === b[2][0]))
}
}
+40
View File
@@ -0,0 +1,40 @@
import Game from './game.js'
let p1, p2
while (!p1) {
p1 = window.prompt('Enter player 1 name:')
}
while (!p2 && p1 !== p2) {
p2 = window.prompt(p1 === p2
? `Please enter a different name than ${p1}.`
: 'Enter player 2 name:')
}
window.onload = () => {
const game = new Game(p1, p2)
const turn = document.getElementById('turn')
const player = document.getElementById('player')
player.innerText = game.player
document.querySelectorAll('td').forEach((el) => {
el.onclick = (evt) => {
el.onclick = undefined
evt.target.innerText = game.sym
evt.target.onclick = undefined
const [row, col] = evt.target.classList
game.turn(row, col)
if (game.hasWinner()) {
turn.innerText = `${game.player} wins!`
document.querySelectorAll('td').forEach(el => {
el.onclick = undefined
})
} else {
game.nextPlayer()
player.innerText = game.player
}
}
})
}
+14
View File
@@ -0,0 +1,14 @@
const path = require('path')
module.exports = {
entry: {
'main.js': [
path.resolve(__dirname, 'index.js'),
path.resolve(__dirname, 'game.js')
]
},
output: {
filename: 'main.js',
path: path.resolve(__dirname, '../public')
}
}