拼图小游戏制作教程:用HTML5和JavaScript打造经典游戏

拼图小游戏制作教程:用HTML5和JavaScript打造经典游戏

在这篇文章中,我们将一起学习如何从头开始制作一个简单的拼图小游戏。我们将使用HTML5和JavaScript来创建这个小游戏,不需要任何复杂的框架或库。通过这个教程,你将了解基本的网页布局、CSS样式设置以及JavaScript的交互逻辑。

在线体验

洛可可白⚡️拼图
在这里插入图片描述

准备工作

首先,确保你的计算机上安装了文本编辑器,如Notepad++、Sublime Text或Visual Studio Code。这些工具将帮助你编写和编辑代码。

创建HTML结构

打开你的文本编辑器,创建一个新的HTML文件,并输入以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>洛可可白拼图</title>
<style>
/* 在这里添加CSS样式 */
</style>
</head>
<body>
<div id="puzzle-container">
<div id="puzzle-board"></div>
</div>
<button id="shuffle-btn">打乱拼图</button>
<script>
// 在这里添加JavaScript代码
</script>
</body>
</html>

这是我们游戏的基本结构。<head>部分包含了页面的元数据和样式定义,<body>部分则是游戏的主要内容。

添加CSS样式

<style>标签内,我们将添加一些CSS样式来美化我们的拼图游戏。这包括拼图容器的边框、拼图块的大小和样式,以及按钮的样式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#puzzle-container {
width: 300px;
height: 300px;
margin: 0 auto;
border: 2px solid #ccc;
position: relative;
overflow: hidden;
}

#puzzle-board {
width: 300px;
height: 300px;
position: absolute;
}

.puzzle-piece {
width: 100px;
height: 100px;
position: absolute;
background-size: 300px 300px;
border: 2px solid #fff;
transition: all 0.3s ease-in-out;
}

button {
display: block;
margin: 20px auto;
}

编写JavaScript逻辑

现在,我们将在<script>标签内添加JavaScript代码,这是游戏的核心部分。我们将创建拼图块,处理用户交互,并实现打乱拼图的功能。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
document.addEventListener("DOMContentLoaded", () => {
// 获取DOM元素
const puzzleContainer = document.getElementById("puzzle-container");
const puzzleBoard = document.getElementById("puzzle-board");
const shuffleButton = document.getElementById("shuffle-btn");
const imageSrc = "http://example.com/image.jpg"; // 替换为你的图片地址
const rows = 3;
const cols = 3;
const pieces = [];

// 创建拼图块的函数
function createPuzzlePieces() {
// ...(省略代码以节省空间,详见原代码)
}

// 移动拼图块的函数
function movePiece(piece) {
// ...(省略代码以节省空间,详见原代码)
}

// 检查是否完成拼图的函数
function checkWin() {
// ...(省略代码以节省空间,详见原代码)
}

// 打乱拼图的函数
function shufflePuzzle() {
// ...(省略代码以节省空间,详见原代码)
}

// 初始化游戏
createPuzzlePieces();
shuffleButton.addEventListener("click", shufflePuzzle);
});

在这个脚本中,我们首先监听文档加载完成的事件,然后获取页面上的元素。我们定义了几个函数来创建拼图块、移动拼图块、检查游戏胜利条件以及打乱拼图。最后,我们初始化游戏并为打乱按钮添加事件监听器。

测试游戏

保存你的HTML文件,并在浏览器中打开它。你应该能看到一个拼图游戏的界面。点击“打乱拼图”按钮,拼图块会被随机打乱。你可以通过拖动拼图块来完成拼图。

全部代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>洛可可白⚡️拼图</title>
<style>
#puzzle-container {
width: 300px;
height: 300px;
margin: 0 auto;
border: 2px solid #ccc;
position: relative;
overflow: hidden;
}

#puzzle-board {
width: 300px;
height: 300px;
position: absolute;
}

.puzzle-piece {
width: 100px;
height: 100px;
position: absolute;
background-size: 300px 300px;
border: 2px solid #fff;
transition: all 0.3s ease-in-out;
}

button {
display: block;
margin: 20px auto;
}
</style>
</head>

<body>
<div id="puzzle-container">
<div id="puzzle-board"></div>
</div>
<button id="shuffle-btn">打乱拼图</button>
</body>
<script>
document.addEventListener("DOMContentLoaded", () => {
const puzzleContainer = document.getElementById("puzzle-container");
const puzzleBoard = document.getElementById("puzzle-board");
const shuffleButton = document.getElementById("shuffle-btn");
const imageSrc =
"http://cdn-hw-static2.shanhutech.cn/bizhi/staticwp/202312/d989b0fbf30d985ee89f15ef2fd640db--2492230555.jpg"; // 替换为你的图片地址
const rows = 3;
const cols = 3;
const pieces = [];

let emptyPiece;
let isShuffling = false;

// 创建拼图块
function createPuzzlePieces() {
const pieceWidth = puzzleContainer.offsetWidth / cols;
const pieceHeight = puzzleContainer.offsetHeight / rows;
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
const piece = document.createElement("div");
piece.className = "puzzle-piece";
piece.style.width = `${pieceWidth}px`;
piece.style.height = `${pieceHeight}px`;
piece.style.backgroundImage = `url(${imageSrc})`;
piece.style.backgroundPosition = `${-col * pieceWidth}px ${
-row * pieceHeight
}px`;
piece.style.top = `${row * pieceHeight}px`;
piece.style.left = `${col * pieceWidth}px`;
piece.dataset.row = row;
piece.dataset.col = col;

if (row === rows - 1 && col === cols - 1) {
emptyPiece = piece;
piece.classList.add("empty");
} else {
piece.addEventListener("click", () => {
if (!isShuffling) {
movePiece(piece);
}
});
}

puzzleBoard.appendChild(piece);
pieces.push(piece);
}
}
}

// 移动拼图块
function movePiece(piece) {
const emptyPieceRow = parseInt(emptyPiece.dataset.row);
const emptyPieceCol = parseInt(emptyPiece.dataset.col);
const pieceRow = parseInt(piece.dataset.row);
const pieceCol = parseInt(piece.dataset.col);

if (
(pieceRow === emptyPieceRow &&
Math.abs(pieceCol - emptyPieceCol) === 1) ||
(pieceCol === emptyPieceCol &&
Math.abs(pieceRow - emptyPieceRow) === 1)
) {
const tempRow = emptyPieceRow;
const tempCol = emptyPieceCol;
emptyPiece.style.top = `${pieceRow * piece.offsetHeight}px`;
emptyPiece.style.left = `${pieceCol * piece.offsetWidth}px`;
emptyPiece.dataset.row = pieceRow;
emptyPiece.dataset.col = pieceCol;

piece.style.top = `${tempRow * piece.offsetHeight}px`;
piece.style.left = `${tempCol * piece.offsetWidth}px`;
piece.dataset.row = tempRow;
piece.dataset.col = tempCol;
}

checkWin();
}

let isWin = false; // 添加标志位

// 检查是否完成拼图
function checkWin() {
let isPuzzleComplete = true;
for (let i = 0; i < pieces.length; i++) {
const piece = pieces[i];
const row = parseInt(piece.dataset.row);
const col = parseInt(piece.dataset.col);
if (row !== Math.floor(i / cols) || col !== i % cols) {
isPuzzleComplete = false;
break;
}
}

if (isPuzzleComplete && !isWin && !isShuffling) {
// 添加条件判断
isWin = true; // 设置标志位为true
setTimeout(() => {
alert("恭喜!你完成了拼图!");
shuffleButton.disabled = false;
isWin = false; // 重置标志位为false
}, 200);
}
}
// 打乱拼图
function shufflePuzzle() {
isShuffling = true;
shuffleButton.disabled = true;
isWin = false; // 重置标志位为false

const shuffleCount = 100;
let count = 0;

const intervalId = setInterval(() => {
const randomIndex = Math.floor(Math.random() * pieces.length);
const randomPiece = pieces[randomIndex];
movePiece(randomPiece);
count++;

if (count >= shuffleCount) {
clearInterval(intervalId);
isShuffling = false;
shuffleButton.disabled = false;
}
}, 10);
}
createPuzzlePieces();
shuffleButton.addEventListener("click", shufflePuzzle);
});
</script>
</html>

结语

恭喜你,你已经成功创建了一个简单的拼图小游戏!这个教程涵盖了从创建基本的HTML结构到添加CSS样式,再到编写JavaScript交互逻辑的全过程。通过这个项目,你不仅学会了如何制作一个小游戏,还对前端开发有了基本的了解。随着你技能的提升,你可以尝试添加更多的功能,比如计时器、得分系统或者更复杂的拼图形状。祝你编程愉快!

打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2022-2024 何福海
  • 访问人数: | 浏览次数:

请我喝杯奶茶吧~

支付宝
微信