本文小编为大家详细介绍“基于JS怎么实现Flappy Bird游戏”,内容详细,步骤清晰,细节处理妥当,希望这篇“基于JS怎么实现Flappy Bird游戏”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
实现代码
HTML 部分:在此部分中,创建和加载游戏的元素。选择背景、鸟类、障碍和得分元素的图像。接下来,我们创建并链接 style.css 和 index.js 文件。
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css" rel="external nofollow" >
</head>
<body>
<div class="background"></div>
<img class="bird" src="https://lf3-cdn-tos.bytescm.com/obj/static/xitu_juejin_web/e08da34488b114bd4c665ba2fa520a31.svg" alt="bird-img">
<div class="message">
按 Enter 开始游戏
</div>
<div class="score">
<span class="score_title"></span>
<span class="score_val"></span>
</div>
<script src="gfg.js"></script>
</body>
</html>
CSS 部分:在此部分中,根据需要修改游戏对象的大小、位置和样式。
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 100vh;
width: 100vw;
}
.background {
height: 100vh;
width: 100vw;
background-color: skyblue;
}
.bird {
height: 100px;
width: 160px;
position: fixed;
top: 40vh;
left: 30vw;
z-index: 100;
}
.pipe_sprite {
position: fixed;
top: 40vh;
left: 100vw;
height: 70vh;
width: 6vw;
background-color: green;
}
.message {
position: fixed;
z-index: 10;
height: 10vh;
font-size: 10vh;
font-weight: 100;
color: black;
top: 12vh;
left: 20vw;
text-align: center;
}
.score {
position: fixed;
z-index: 10;
height: 10vh;
font-size: 10vh;
font-weight: 100;
color: goldenrod;
top: 0;
left: 0;
}
.score_val {
color: gold;
}
JavaScript 部分:此部分包含控制游戏状态和移动对象的代码部分。在本节中必须遵循以下步骤。
在 JavaScript 文件中获取对鸟类和背景图像的引用。
为背景滚动速度、小鸟的飞行速度和重力设置一些值。
创建无限滚动背景。可以从此链接阅读执行此操作的指南。
添加一个事件侦听器来侦听“enter”按键以将游戏状态更改为播放状态,并通过每帧从鸟的 y 坐标减小重力值来将重力应用于鸟。
在视图宽度的末端生成障碍(管道),以便它们最初不可见,但随着背景的移动,将管道的 x 坐标减小背景滚动值,使其看起来像鸟在移动。
应用与地面和管道的碰撞,如果小鸟发生碰撞,则将游戏状态更改为结束状态并显示一条消息以重新开始游戏。
每次在管道之间成功导航后增加分数值。
背景滚动速度
let move_speed = 3;
重力常数值
let gravity = 0.5;
获取 bird 元素的引用
let bird = document.querySelector('.bird');
获取 bird 元素属性
let bird_props = bird.getBoundingClientRect();
部分 js 代码
let background =
document.querySelector('.background')
.getBoundingClientRect();
// 获取对 score 元素的引用
let score_val =
document.querySelector('.score_val');
let message =
document.querySelector('.message');
let score_title =
document.querySelector('.score_title');
// 设置初始游戏状态开始
let game_state = 'Start';
// 为按键添加事件监听器
document.addEventListener('keydown', (e) => {
// 按下回车键开始游戏
if (e.key == 'Enter' &&
game_state != 'Play') {
document.querySelectorAll('.pipe_sprite')
.forEach((e) => {
e.remove();
});
bird.style.top = '40vh';
game_state = 'Play';
message.innerHTML = '';
score_title.innerHTML = 'Score : ';
score_val.innerHTML = '0';
play();
}
});
读到这里,这篇“基于JS怎么实现Flappy Bird游戏”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。