用javascript编写一个数独游戏
时间: 2023-06-10 11:09:12 浏览: 68
好的,以下是一个简单的数独游戏的实现,使用HTML、CSS和JavaScript编写:
HTML代码:
```
<!DOCTYPE html>
<html>
<head>
<title>数独游戏</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>数独游戏</h1>
<table id="game-board"></table>
<button id="check-btn">检查</button>
<script src="script.js"></script>
</body>
</html>
```
CSS代码:
```
table {
border-collapse: collapse;
margin: auto;
}
td {
border: 1px solid black;
width: 30px;
height: 30px;
text-align: center;
font-size: 20px;
}
td input {
width: 100%;
height: 100%;
border: none;
text-align: center;
font-size: 20px;
}
```
JavaScript代码:
```
// 数独游戏的数据
const gameData = [
[0, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 6, 0, 0, 0, 0, 3],
[0, 7, 4, 0, 8, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 3, 0, 0, 2],
[0, 8, 0, 0, 4, 0, 0, 1, 0],
[6, 0, 0, 5, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 7, 8, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 4, 0, 0, 0, 0, 0, 0, 0],
];
// 获取表格元素
const gameBoard = document.getElementById("game-board");
// 生成数独游戏表格
for (let i = 0; i < 9; i++) {
const row = document.createElement("tr");
for (let j = 0; j < 9; j++) {
const cell = document.createElement("td");
const input = document.createElement("input");
input.type = "text";
input.maxLength = 1;
input.value = gameData[i][j] || "";
cell.appendChild(input);
row.appendChild(cell);
}
gameBoard.appendChild(row);
}
// 获取检查按钮元素
const checkBtn = document.getElementById("check-btn");
// 检查数独游戏是否完成
checkBtn.addEventListener("click", function() {
let isComplete = true;
const inputs = document.querySelectorAll("input");
for (let i = 0; i < inputs.length; i++) {
if (inputs[i].value === "") {
isComplete = false;
break;
}
}
if (isComplete) {
alert("恭喜你完成了数独游戏!");
} else {
alert("数独游戏还没有完成,请继续努力!");
}
});
```
这个数独游戏只是一个简单的实现,你可以根据自己的需求和喜好来进行修改和完善。