【发布时间】:2014-06-22 11:37:20
【问题描述】:
我对 HTML5 和 JavaScript 还很陌生,我正在尝试学习游戏编程。所以我决定尝试用二维数组渲染棋盘来制作井字游戏。我将其设置为使用 CSS:hover 更改颜色,但现在我只是想让每个框在单击时变为红色,这就是我被卡住的地方。
我不是在寻找任何人来为我完成我的代码,我只是想把事情放慢(ish),我想自己解决这些问题。我的问题是如何让每个框在单击时改变颜色?目前我让数组的每个元素都创建一个,然后我定位它们并将 addEventListener 添加到它们的类中。我的代码 KIND-OF 的工作原理是,当您单击最后一个元素时,它会改变颜色,但其他元素都不会。
这是我的代码。
<!doctype html>
<title>Tic Tac Toe</title>
<style>
#stage
{
position: relative;
}
.cell
{
position: absolute;
width: 100px;
height: 100px;
border: 1px solid black;
background-color: white;
}
.cell:hover
{
background-color: blue;
}
</style>
<div id="stage"></div>
<script>
//get a reference to the stage
var stage = document.querySelector("#stage");
//the 2d array that defines the board
var board =
[
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
];
//the size of each cell
var SIZE = 100;
//the space between each cell
var SPACE = 10;
//display the array
var ROWS = board.length;
var COLUMNS = board[0].length;
for(var row = 0; row < ROWS; row++)
{
for(var column = 0; column < COLUMNS; column++)
{
//create a div HTML element called cell
var cell = document.createElement("div");
//set its CSS class to cell
cell.setAttribute("class", "cell");
//add the div HTML element to the stage
stage.appendChild(cell);
//position the cell
cell.style.top = row * (SIZE + SPACE) + "px";
cell.style.left = column * (SIZE + SPACE) + "px";
}
}
cell.addEventListener("click", clickHandler, false);
function clickHandler()
{
cell.style.backgroundColor = "red";
console.log("worked");
}
</script>
任何帮助将不胜感激!谢谢!
【问题讨论】:
-
就个人而言,我不会使用二维数组。我只使用一个包含九个元素的数组来表示板。如果我感觉特别深奥,我可能会将棋盘表示为 0 到 19682 之间的整数,表示以三为底的游戏棋盘...
-
@NiettheDarkAbsol 是的,单个数组可能会更容易,但我很好奇是否可以制作二维数组。
标签: javascript html multidimensional-array