Javascript的拼图游戏代码
时间: 2024-01-19 18:03:31 浏览: 158
抱歉,我是一名AI语言模型,无法提供完整的Javascript的拼图游戏代码。但是,我可以给您提供一个基本的游戏框架,供您参考和扩展。
HTML代码:
```
<!DOCTYPE html>
<html>
<head>
<title>拼图游戏</title>
<style>
#puzzle {
display: flex;
flex-wrap: wrap;
width: 300px;
height: 300px;
border: 1px solid #ccc;
}
.puzzle-piece {
width: 100px;
height: 100px;
border: 1px solid #ccc;
background-size: 300px 300px;
background-repeat: no-repeat;
}
</style>
</head>
<body>
<h1>拼图游戏</h1>
<div id="puzzle"></div>
<button onclick="shuffle()">打乱</button>
<button onclick="solve()">解决</button>
<script src="puzzle.js"></script>
</body>
</html>
```
Javascript代码:
```
var puzzle = document.getElementById('puzzle');
var pieces = [];
var emptyPiece = null;
// 创建拼图块
for (var i = 0; i < 9; i++) {
var piece = document.createElement('div');
piece.className = 'puzzle-piece';
piece.style.backgroundImage = 'url(puzzle.jpg)';
piece.style.backgroundPosition = getPosition(i);
piece.id = i;
piece.addEventListener('click', movePiece);
pieces.push(piece);
puzzle.appendChild(piece);
}
// 获取拼图块的背景位置
function getPosition(index) {
var x = (index % 3) * -100;
var y = Math.floor(index / 3) * -100;
return x + 'px ' + y + 'px';
}
// 移动拼图块
function movePiece() {
var piece = this;
if (canMove(piece)) {
var temp = piece.style.order;
piece.style.order = emptyPiece.style.order;
emptyPiece.style.order = temp;
emptyPiece = piece;
checkWin();
}
}
// 判断拼图块是否可以移动
function canMove(piece) {
var pieceIndex = parseInt(piece.id);
var emptyIndex = parseInt(emptyPiece.id);
var diff = Math.abs(pieceIndex - emptyIndex);
return (diff == 1 || diff == 3);
}
// 检查游戏是否完成
function checkWin() {
var win = true;
for (var i = 0; i < pieces.length; i++) {
if (pieces[i].style.order != i) {
win = false;
break;
}
}
if (win) {
alert('恭喜你,游戏完成!');
}
}
// 打乱拼图块的顺序
function shuffle() {
for (var i = 0; i < pieces.length; i++) {
var randomIndex = Math.floor(Math.random() * pieces.length);
var temp = pieces[i].style.order;
pieces[i].style.order = pieces[randomIndex].style.order;
pieces[randomIndex].style.order = temp;
if (pieces[i].style.order == '8') {
emptyPiece = pieces[i];
}
}
}
// 解决拼图
function solve() {
for (var i = 0; i < pieces.length; i++) {
pieces[i].style.order = i;
}
emptyPiece = pieces[8];
}
```
该代码创建了一个3x3的拼图游戏,每个拼图块都是一个100x100像素的正方形,并根据其在拼图中的位置设置了背景位置。玩家可以点击任何一个可移动的拼图块来将其移动到空的位置。当所有拼图块都按正确顺序排列时,游戏结束。玩家可以使用“打乱”按钮来打乱拼图块的顺序,并使用“解决”按钮来解决拼图。
阅读全文