我目前正在学习javascript,并且只学习入门(第一个月,因此代码非常成熟)。我正试图纯粹用JavaScript编写井字游戏,应该是这样的Example,但我不知道为什么它不起作用。
(功能startgame和endgame只需设置正确的html标记)
class Player {
constructor(id, isTurn, css, img) {
this.id = id;
this.isTurn = isTurn;
this.css = css;
this.img = img;
}
checkStatus(boxes){
let point=[]; let allpoint=0;
for (let i=0; i< boxes.children.length; i++){
let li = boxes.children[i];
if (li.className.includes(this.css)) {
point.push(i);
}
if (li.className!='box'){
allpoint++;
}
}
for (let i=0; i<winCombo.length; i++) {
let st = winCombo[i].every(val => point.includes(val));
if (st === true) {
return this.id;
}
}
if (allpoint == 9) {
return 'tie';
}
return 'game';
}
}
class Game {
constructor(players) {
this.players = players;
}
get player() {
for (let i=0; i< this.players.length; i++) {
if (this.players[i].isTurn === true)
return this.players[i];
}
}
get css() {
return this.player.css;
}
shiftTurn() {
for (let i=0; i< this.players.length; i++) {
this.players[i].isTurn = !this.players[i].isTurn;
}
}
set turn(id) {
for (let i=0; i< this.players.length; i++) {
if (this.players[i].id === id) {
this.players[i].isTurn = true;
}
else {
this.players[i].isTurn = false;
}
}
}
updateLi() {
const playersLi = document.querySelectorAll('.players');
for (let i=0; i<playersLi.length; i++) {
playersLi[i].className='players';
}
const li = document.querySelector(`#${this.player.id}`);
li.className='players active';
}
}
document.querySelector('a').addEventListener('click', () => {
startGame();
const boxes = document.querySelector('.boxes');
const game = new Game([new Player('player1', true, 'box-filled-1',
`url(../img/o.svg)`), new Player('player2', false, 'box-filled-2',
`url(../img/x.svg)`)]);
game.updateLi();
boxes.addEventListener('mouseover', (e) => {
if (e.target.className=='box') {
/* if (document.querySelector('a').innerText=='New
game'&&game.player.id=='player2'){
console.log(game.player.img);
} */
e.target.style.backgroundImage=game.player.img;
}
})
boxes.addEventListener('mouseout', (e) => {
if (e.target.className=='box') {
// if (document.querySelector('a').innerText!='New game'){
e.target.style.backgroundImage='none';
// }
}
})
boxes.addEventListener('click', (e) => {
if (e.target.className=='box') {
e.target.removeAttribute('style');
e.target.className='box '+game.css;
let status = game.player.checkStatus(e.target.parentNode);
if (status != 'game') {
if (document.querySelector('a').innerText=='New game'){
console.log(status);
}
endGame(status);
game.turn='player1';
}
else {
game.shiftTurn();
game.updateLi();
}
// console.log(status);
}
})
})
});