好玩的JS游戏代码!
用JS写游戏,摸鱼也能理直气壮!
引言:当代码遇上游戏,程序员也能成为“造物主”!
大家好,我是你们的老朋友——一个每天都在和bug斗智斗勇的前端程序员。今天,我们不聊枯燥的业务逻辑,也不谈让人头秃的性能优化,我们来点好玩的——用JS写游戏!
是的,你没看错!用JS,你就能在浏览器里打造自己的游戏世界。从经典的贪吃蛇到炫酷的物理弹球,甚至还能做个“社畜快乐球”来发泄一下对老板的不满(嘘,别告诉他)。
最重要的是,代码全公开,复制即运行!老板问起来就说你在“测试浏览器性能”,摸鱼也能理直气壮!
案例1:贪吃蛇——经典永不过时
效果:一条蛇追着自己的尾巴跑,吃到食物变长,撞到墙或自己就GG。简单却让人上瘾,简直是摸鱼界的扛把子!
完整代码:
贪吃蛇
<style>
canvas { background: #000; display: block; margin: 0 auto; }
</style>
<body>
<script>
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
const grid = 20;
let snake = [{ x: 200, y: 200 }];
let food = { x: 0, y: 0 };
let dx = grid;
let dy = 0;
functionplaceFood() {
food.x = Math.floor(Math.random() * (canvas.width / grid)) * grid;
food.y = Math.floor(Math.random() * (canvas.height / grid)) * grid;
}
functiongameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
const head = { x: snake[0].x + dx, y: snake[0].y + dy };
snake.unshift(head);
if (head.x === food.x && head.y === food.y) {
placeFood();
} else {
snake.pop();
}
if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height || snake.slice(1).some(segment => segment.x === head.x && segment.y === head.y)) {
alert('Game Over!');
snake = [{ x: 200, y: 200 }];
dx = grid;
dy = 0;
}
ctx.fillStyle = 'lime';
snake.forEach(segment => ctx.fillRect(segment.x, segment.y, grid, grid));
ctx.fillStyle = 'red';
ctx.fillRect(food.x, food.y, grid, grid);
}
document.addEventListener('keydown', e => {
if (e.key === 'ArrowUp' && dy === 0) { dx = 0; dy = -grid; }
if (e.key === 'ArrowDown' && dy === 0) { dx = 0; dy = grid; }
if (e.key === 'ArrowLeft' && dx === 0) { dx = -grid; dy = 0; }
if (e.key === 'ArrowRight' && dx === 0) { dx = grid; dy = 0; }
});
placeFood();
setInterval(gameLoop, 100);
</script>