[英]Change text color of a winning line
So I've been working on JS tic tac toe game.所以我一直在研究 JS 井字游戏。 It's pretty much ready to go, the last thing I want to do is change the text color of the winning line but I can't seem to find a way to get the exact winning line contained to then change the text color.
go 几乎已经准备就绪,我要做的最后一件事是更改获胜线的文本颜色,但我似乎无法找到一种方法来获取包含的确切获胜线然后更改文本颜色。
Here's the code for my winning conditions:这是我的获胜条件的代码:
function findCell(x) {
return document.getElementById("cell" + x).innerText;
}
function checkLine(x, y, z, letter) {
var triple = false;
if (findCell(x) == letter && findCell(y) == letter && findCell(z) == letter) {
triple = true;
}
return triple;
}
function victory(letter) {
var winner = false;
if (checkLine(1, 2, 3, letter) ||
checkLine(4, 5, 6, letter) ||
checkLine(7, 8, 9, letter) ||
checkLine(1, 4, 7, letter) ||
checkLine(2, 5, 8, letter) ||
checkLine(3, 6, 9, letter) ||
checkLine(1, 5, 9, letter) ||
checkLine(3, 5, 7, letter)) {
winner = true;
}
return winner;
}
I also have a function to change the color, I just don't know where to apply it我也有一个function可以改色,就是不知道用在哪里
var lettercolor = [0, 0, 0];
var color = ["red"]
function changeColor(i) {
lettercolor[i] = (lettercolor[i] + 1) % color.length;
document.getElementById( ? ? ? ? ? ).style.color = color[lettercolor[i]];
}
Also, I don't want any jQuery stuff... I want to do this simple vanilla JS.另外,我不想要任何 jQuery 的东西......我想做这个简单的香草 JS。
Since you find triples in checkLine
, you can highlight all such cells in that function if a triple is found by iterating over the xyz
cell parameters:由于您在
checkLine
中找到三元组,因此如果通过迭代xyz
单元格参数找到三元组,则可以突出显示 function 中的所有此类单元格:
function checkLine(x, y, z, letter) {
const cells = [x, y z].map(num => document.getElementById("cell" + num));
if (cells.every(cell => cell.textContent === letter)) {
for (const cell of cells) {
cell.style.color = 'red';
}
return true;
}
}
Just split your if statement into different winning sets.只需将您的 if 语句分成不同的获胜集。 Then, after returning the
winner
boolean, you can apply the styles.然后,在返回
winner
boolean 后,您可以申请 styles。
function victory(letter) {
if (checkLine(1, 2, 3, letter)) {
changeWinnerColors([1, 2, 3]);
return true;
}
// Check your other combinations...
// If no combination matches, thereis no winner
return false;
}
function changeWinnerColors(cells) {
for(var cell of cells)
changeColor(cell);
}
function changeColor(i) {
lettercolor[i] = (lettercolor[i] + 1) % color.length;
document.getElementById(`cell${i}`).style.color = color[lettercolor[i]];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.