-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbreakout.html
More file actions
399 lines (358 loc) · 12.6 KB
/
Copy pathbreakout.html
File metadata and controls
399 lines (358 loc) · 12.6 KB
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
<title>打砖块 - 单文件</title>
<style>
:root { color-scheme: light dark; }
html, body {
height: 100%;
margin: 0;
background: radial-gradient(1200px 800px at 50% 20%, rgba(0,0,0,0.08), transparent) ,
linear-gradient(180deg, #0e1116, #1b2130);
font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", Arial, sans-serif;
color: #eee;
display: grid;
place-items: center;
}
#wrap {
width: min(92vw, 560px);
aspect-ratio: 3/4; /* 让画布自适应,避免被拉伸 */
position: relative;
}
canvas {
width: 100%;
height: 100%;
display: block;
background: #0d0f14;
border-radius: 12px;
box-shadow: 0 18px 60px rgba(0,0,0,.4), inset 0 0 0 1px rgba(255,255,255,.06);
}
.hud {
position: absolute; inset: 10px 12px auto 12px;
display: flex; justify-content: space-between; align-items: center;
pointer-events: none; font-weight: 600; letter-spacing: .3px;
text-shadow: 0 1px 0 rgba(0,0,0,.5);
}
.hud .btns { pointer-events: auto; display: flex; gap: 8px; }
.hud button {
appearance: none; border: none; border-radius: 8px; padding: 6px 10px;
background: rgba(255,255,255,.08); color: #fff; font-weight: 600; cursor: pointer;
transition: transform .06s ease, background .2s ease;
}
.hud button:active { transform: translateY(1px) scale(.98); }
.tips {
position: absolute; inset: auto 0 8px 0; text-align: center; font-size: 12px; opacity: .7;
user-select: none;
}
</style>
</head>
<body>
<div id="wrap" aria-label="打砖块游戏容器">
<canvas id="game" aria-label="游戏画布" role="img"></canvas>
<div class="hud">
<div id="info">分数: 0 关卡: 1 生命: 3 最佳: 0</div>
<div class="btns">
<button id="btnPause" title="暂停(P)">暂停</button>
<button id="btnReset" title="重开(R)">重开</button>
</div>
</div>
<div class="tips">键盘 ←/→ 或 A/D 移动挡板 · 鼠标/触摸可拖动 · P 暂停 · R 重开</div>
</div>
<script>
(() => {
const canvas = document.getElementById('game');
const infoEl = document.getElementById('info');
const btnPause = document.getElementById('btnPause');
const btnReset = document.getElementById('btnReset');
const ctx = canvas.getContext('2d');
// ====== 设备像素比处理,保持高清 ======
function fitCanvas() {
const dpr = Math.max(1, Math.min(window.devicePixelRatio || 1, 2));
const rect = canvas.getBoundingClientRect();
canvas.width = Math.round(rect.width * dpr);
canvas.height = Math.round(rect.height * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
}
// ====== 游戏状态 ======
const state = {
running: true,
level: 1,
score: 0,
lives: 3,
best: Number(localStorage.getItem('breakout_best') || 0),
};
// ====== 对象定义 ======
const paddle = { x: 0, y: 0, w: 96, h: 12, speed: 480, targetX: null };
const ball = { x: 0, y: 0, r: 7, dx: 0, dy: 0, speed: 320, launched: false };
const bricks = {
rows: 6,
cols: 8,
marginTop: 64,
marginSide: 18,
padding: 8,
w: 0,
h: 20,
list: []
};
function resetLevel(firstTime = false) {
const W = canvas.clientWidth, H = canvas.clientHeight;
// 随关卡变化
bricks.rows = Math.min(3 + state.level, 12);
bricks.cols = Math.min(6 + Math.floor(state.level/2), 12);
paddle.w = Math.max(56, 110 - state.level * 6);
ball.speed = Math.min(650, 320 + state.level * 30);
bricks.h = Math.max(16, 22 - Math.floor(state.level/3));
bricks.marginTop = 56;
// 计算砖块尺寸
const usableW = W - bricks.marginSide * 2;
bricks.w = (usableW - (bricks.cols - 1) * bricks.padding) / bricks.cols;
// 创建砖块
bricks.list = [];
for (let r = 0; r < bricks.rows; r++) {
for (let c = 0; c < bricks.cols; c++) {
const x = bricks.marginSide + c * (bricks.w + bricks.padding);
const y = bricks.marginTop + r * (bricks.h + bricks.padding);
const hp = 1 + Math.floor((r + state.level) / 5); // 偶尔两层血
bricks.list.push({ x, y, w: bricks.w, h: bricks.h, hp });
}
}
// 放置挡板与球
paddle.x = (W - paddle.w) / 2;
paddle.y = H - 48;
ball.x = W / 2;
ball.y = H - 60 - ball.r;
ball.launched = false;
const angle = randBetween(35, 145) * Math.PI / 180;
ball.dx = Math.cos(angle);
ball.dy = -Math.abs(Math.sin(angle));
if (firstTime) {
state.score = 0;
state.lives = 3;
state.level = 1;
}
}
function allBricksCleared() {
return bricks.list.every(b => b.hp <= 0);
}
// ====== 输入控制 ======
const keys = new Set();
window.addEventListener('keydown', (e) => {
if (['ArrowLeft','ArrowRight','a','d','A','D','p','P','r','R',' '].includes(e.key)) e.preventDefault();
if (e.key === 'p' || e.key === 'P') { togglePause(); return; }
if (e.key === 'r' || e.key === 'R') { hardReset(); return; }
if (e.key === ' ') { ball.launched = true; return; }
keys.add(e.key);
});
window.addEventListener('keyup', (e) => keys.delete(e.key));
// 鼠标/触控移动挡板
function movePaddleTo(clientX) {
const rect = canvas.getBoundingClientRect();
paddle.targetX = Math.min(Math.max(clientX - rect.left - paddle.w/2, 0), rect.width - paddle.w);
}
canvas.addEventListener('mousemove', (e) => movePaddleTo(e.clientX));
canvas.addEventListener('touchstart', (e) => { ball.launched = true; movePaddleTo(e.touches[0].clientX); }, {passive:false});
canvas.addEventListener('touchmove', (e) => { movePaddleTo(e.touches[0].clientX); e.preventDefault(); }, {passive:false});
canvas.addEventListener('click', () => { if (!state.running) togglePause(); else ball.launched = true; });
btnPause.addEventListener('click', togglePause);
btnReset.addEventListener('click', hardReset);
function togglePause() {
state.running = !state.running;
btnPause.textContent = state.running ? '暂停' : '继续';
}
function hardReset() {
state.running = true;
state.level = 1; state.score = 0; state.lives = 3;
btnPause.textContent = '暂停';
resetLevel();
}
// ====== 工具函数 ======
function randBetween(min, max) { return Math.random() * (max - min) + min; }
function clamp(v, lo, hi) { return Math.min(Math.max(v, lo), hi); }
// ====== 渲染 ======
function drawBackground() {
const W = canvas.clientWidth, H = canvas.clientHeight;
// 顶部渐变光
const g = ctx.createLinearGradient(0, 0, 0, H);
g.addColorStop(0, 'rgba(0,180,255,0.08)');
g.addColorStop(1, 'rgba(0,0,0,0)');
ctx.fillStyle = g;
ctx.fillRect(0, 0, W, H);
}
function drawPaddle() {
ctx.fillStyle = '#8bd3dd';
roundRect(ctx, paddle.x, paddle.y, paddle.w, paddle.h, 6, true);
}
function drawBall() {
const g = ctx.createRadialGradient(ball.x-2, ball.y-2, 1, ball.x, ball.y, ball.r);
g.addColorStop(0, '#fff');
g.addColorStop(1, '#80b3ff');
ctx.fillStyle = g;
ctx.beginPath();
ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI*2);
ctx.fill();
}
function drawBricks() {
bricks.list.forEach((b, i) => {
if (b.hp <= 0) return;
const hue = (i * 17 + state.level * 23) % 360;
ctx.fillStyle = `hsl(${hue} 70% ${b.hp > 1 ? 48 : 58}% / 0.95)`;
roundRect(ctx, b.x, b.y, b.w, b.h, 5, true);
});
}
function drawOverlay(text, sub) {
const W = canvas.clientWidth, H = canvas.clientHeight;
ctx.fillStyle = 'rgba(0,0,0,.35)';
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#fff';
ctx.font = '600 24px system-ui, sans-serif';
ctx.textAlign = 'center';
ctx.fillText(text, W/2, H/2 - 8);
ctx.font = '14px system-ui, sans-serif';
ctx.fillStyle = 'rgba(255,255,255,.9)';
ctx.fillText(sub, W/2, H/2 + 20);
}
function roundRect(ctx, x, y, w, h, r, fill) {
const rr = Math.min(r, w/2, h/2);
ctx.beginPath();
ctx.moveTo(x+rr, y);
ctx.arcTo(x+w, y, x+w, y+h, rr);
ctx.arcTo(x+w, y+h, x, y+h, rr);
ctx.arcTo(x, y+h, x, y, rr);
ctx.arcTo(x, y, x+w, y, rr);
ctx.closePath();
if (fill) ctx.fill();
}
// ====== 逻辑更新 ======
let lastTime = 0;
function update(dt) {
const W = canvas.clientWidth, H = canvas.clientHeight;
// 键盘控制
let vx = 0;
if (keys.has('ArrowLeft') || keys.has('a') || keys.has('A')) vx -= 1;
if (keys.has('ArrowRight') || keys.has('d') || keys.has('D')) vx += 1;
if (paddle.targetX != null) {
// 平滑跟随鼠标/触控
const desired = paddle.targetX;
const diff = desired - paddle.x;
paddle.x += clamp(diff, -paddle.speed*dt, paddle.speed*dt);
if (Math.abs(diff) < 0.5) paddle.targetX = null;
}
if (vx !== 0) {
paddle.x += vx * paddle.speed * dt;
paddle.targetX = null; // 键盘输入时忽略鼠标锁定
}
paddle.x = clamp(paddle.x, 0, W - paddle.w);
// 球发射前跟随挡板
if (!ball.launched) {
ball.x = clamp(paddle.x + paddle.w/2, ball.r, W - ball.r);
return;
}
// 球运动
const v = ball.speed;
ball.x += ball.dx * v * dt;
ball.y += ball.dy * v * dt;
// 撞墙
if (ball.x < ball.r) { ball.x = ball.r; ball.dx *= -1; }
if (ball.x > W - ball.r) { ball.x = W - ball.r; ball.dx *= -1; }
if (ball.y < ball.r) { ball.y = ball.r; ball.dy *= -1; }
// 掉落
if (ball.y > H + ball.r) {
state.lives -= 1;
if (state.lives <= 0) {
state.best = Math.max(state.best, state.score);
localStorage.setItem('breakout_best', state.best);
state.running = false;
} else {
// 复位当前球
ball.launched = false;
ball.y = H - 60 - ball.r;
}
}
// 挡板碰撞(圆-矩形)
if (circleRectOverlap(ball, paddle)) {
// 让反弹角度由击中位置决定,中心为 0,左负右正
const hit = (ball.x - (paddle.x + paddle.w/2)) / (paddle.w/2);
const maxAngle = 75 * Math.PI/180;
const angle = hit * maxAngle;
const speed = Math.hypot(ball.dx, ball.dy); // 单位向量
ball.dx = Math.sin(angle);
ball.dy = -Math.cos(angle);
// 确保向上
if (ball.dy > -0.2) ball.dy = -0.2;
// 轻微提速
ball.speed = Math.min(ball.speed * 1.01, 760);
// 把球移出挡板以免卡住
ball.y = paddle.y - ball.r - 0.5;
}
// 砖块碰撞(简化:逐个检测,命中就反弹一次)
for (const b of bricks.list) {
if (b.hp <= 0) continue;
if (circleRectOverlap(ball, b)) {
b.hp -= 1;
state.score += 10;
// 判断撞击侧:比较与矩形中心的差值
const cx = clamp(ball.x, b.x, b.x + b.w);
const cy = clamp(ball.y, b.y, b.y + b.h);
const dx = ball.x - cx;
const dy = ball.y - cy;
if (Math.abs(dx) > Math.abs(dy)) {
ball.dx *= -1;
} else {
ball.dy *= -1;
}
break; // 一帧只反弹一次,避免穿透
}
}
// 过关检测
if (allBricksCleared()) {
state.level += 1;
// 奖励生命(每两关 +1)
if (state.level % 2 === 0) state.lives = Math.min(5, state.lives + 1);
resetLevel();
}
}
function circleRectOverlap(c, r) {
// 最近点法
const nx = clamp(c.x, r.x, r.x + r.w);
const ny = clamp(c.y, r.y, r.y + r.h);
const dx = c.x - nx, dy = c.y - ny;
return (dx*dx + dy*dy) <= (c.r * c.r);
}
// ====== 主循环 ======
function loop(t) {
requestAnimationFrame(loop);
const now = t / 1000;
const dt = Math.min(0.033, now - (lastTime || now));
lastTime = now;
fitCanvas();
const W = canvas.clientWidth, H = canvas.clientHeight;
// 渲染
ctx.clearRect(0, 0, W, H);
drawBackground();
if (state.running) update(dt);
drawBricks();
drawPaddle();
drawBall();
infoEl.textContent = `分数: ${state.score} 关卡: ${state.level} 生命: ${state.lives} 最佳: ${Math.max(state.best, state.score)}`;
if (!state.running) {
drawOverlay('游戏结束', '点击画布或按 R 重开');
} else if (!ball.launched) {
drawOverlay('准备发射', '按空格 / 点击 / 触摸以发射小球');
}
}
// 初始
fitCanvas();
resetLevel(true);
requestAnimationFrame(loop);
// 响应窗口尺寸变化(节流)
let resizeTimer = null;
window.addEventListener('resize', () => {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => { fitCanvas(); resetLevel(); }, 150);
});
})();
</script>
</body>
</html>