javascript - 模拟计算机的移动并用分数更新玩家的回合
问题描述
我用 JavaScript 写了一个井字游戏。我想模拟电脑的回合,也想更新玩家的分数。
我该如何编写这段代码?我编写了一些适用于播放器 X 和 O 的代码,但它们没有得到更新。我想看看轮到哪个玩家以及每个玩家的得分
const gameState = {
currentPlayer: 'x',
players: ['x', 'o'],
board: [
[null, null, null],
[null, null, null],
[null, null, null]
]
}
var turn = 1;
var P1Score = 0;
var p2Score = 0;
function checkWinner(player) {
if ($(".row-1 .cell." + player).length === 3 ||
$(".row-2 .cell." + player).length === 3 ||
$(".row-3 .cell." + player).length === 3 ||
$(".col1." + player).length === 3 ||
$(".col2." + player).length === 3 ||
$(".col3." + player).length === 3 ||
($("#1").hasClass(player) &&
$("#5").hasClass(player) &&
$("#9").hasClass(player)) ||
($("#3").hasClass(player) &&
$("#5").hasClass(player) &&
$("#7").hasClass(player))) {
$(".cell ").empty();
$(".cell").removeClass("x");
$(".cell").removeClass("o");
$(".cell").css('background', 'blue')
return true;
}
}
$('.cell').click(function() {
if (gameState.currentPlayer == "x" && !$(this).hasClass("o")) {
$(this).text("x")
$(this).addClass("x")
$(".x").css('background', 'gold')
if (checkWinner("x")) {
alert(`${gameState.currentPlayer}is the winner!.Start a new game`)
} else checkTie()
} else if (!$(this).hasClass("x")) {
$(this).text("o")
$(this).addClass("o")
if (checkWinner("o")) {
alert(`${gameState.currentPlayer}is the winner!. Start a new game`)
} else checkTie()
}
changePlayer();
});
function changePlayer(){
if( gameState.currentPlaye == 'x') {
gameState.currentPlayer = 'o'
} else {
gameState.currentPlayer = 'x'
};
};
function checkTie() {
if ($(".x").length + $(".o").length === 9) {
$(".cell ").empty();
$(".x").removeClass("x");
$(".o").removeClass("o");
alert("Its a tie")
};
};
$('.restart').click(function() {
$(".cell ").empty();
$(".cell").removeClass("x");
$(".cell").removeClass("o");
$(".cell").css('background', 'blue')
});
解决方案
推荐阅读
- javascript - 如何使用 react 和 typescript 修复错误对象可能是未定义的?
- pentaho-spoon - 在执行 sql 任务 Pentaho 勺子 7 中提交问题
- java - MQTT 代理和 RabbitMQ 有什么区别
- java - 多个线程处理相同的 ResultSet 记录
- python-3.x - Python 3,递归函数 - 为什么代码 B 可以工作,但代码 A 不行?
- reactjs - Microblink SDK:只拍摄矩形内的照片
- html - 我似乎无法弄清楚我做错了什么,我的悬停在我的网站上不起作用
- c - C在短路表达式中对同一变量进行多次赋值
- ios - 以编程方式为以编程方式制作的 UITextField 创建约束
- php - 如何一次杀死多个 laravel php artisan 命令?