JS小游戏-像素鸟#源码#Javascript

2024-06-22 20:44

本文主要是介绍JS小游戏-像素鸟#源码#Javascript,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1、游戏图片

像素鸟小游戏
在这里插入图片描述

2、HTML部分

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>body{margin: 0;}.game{position: relative;width: 800px;height: 600px;margin: 0 auto;overflow: hidden;}.sky {position: absolute;width: 200%;height: 100%;background-image: url('./img/sky.png');margin: 0 auto;}.game .bird {background: url("./img/bird.png");position: absolute;width: 33px;height: 26px;left: 150px;top: 150px;}.game .bird.swing1{background-position: -8px -10px;}.game .bird.swing2{background-position: -60px -10px;}.game .bird.swing3{background-position: -113px -10px;}.pipeDown{position: absolute;background-image: url('./img/pipeUp.png');width: 52px;height: 100px;left: 500px;bottom: 112px;}.pipeUp{position: absolute;background-image: url('./img/pipeDown.png');background-position: bottom;width: 52px;height: 100px;left: 500px;top: 0;}.ground{position: absolute;background-image: url('./img/land.png');width: 200%;height: 112px;left: 0;bottom: 0;}.score{position: absolute;width: 100px;height: 36px;background-color: lightblue;right: 0;top: 0;text-align: center;line-height: 36px;font-size: 24px;z-index: 100;}p{text-align: center;}</style>
</head>
<body><div class="game"><div class="sky"></div><div class="bird swing1"></div><div class="ground"></div><div class="score">0</div></div><p>按w或者按上开始游戏</p><script src="./JS/Rectangle.js"></script><script src="./JS/Sky.js"></script><script src="./JS/Land.js"></script><script src="./JS/Bird.js"></script><script src="./JS/Pipe.js"></script><script src="./JS/Game.js"></script>
</body>
</html>

3、JS部分

baseGame class
/*** 基础的游戏类* 属性: 宽度 高度、横坐标、纵坐标、横向速度、纵向速度、对应的dom元素*/
class Rectangle {constructor(width,height,x,y,vx,vy,dom){this.width = width;this.height = height;this.x = x;this.y = y;this.vx = vx;this.vy = vy;this.dom = dom;this.render();}/*** 渲染*/render(){this.dom.style.width = this.width + "px";this.dom.style.height = this.height + "px";this.dom.style.left = this.x + "px";this.dom.style.top = this.y + "px";}onMove(){}/***  在duration时间下物体移动* @param {number} duration  间隔*/move(duration){this.x += this.vx * duration;this.y += this.vy * duration;if(this.onMove) this.onMove();this.render();}
}
sky ground class
const skyDom = document.querySelector('.sky');
skyStyle = getComputedStyle(skyDom);
const widthSky = parseFloat(skyStyle.width);
const heightSky = parseFloat(skyStyle.width);class Sky extends Rectangle{constructor(){super(widthSky, heightSky, 0, 0, -100, 0, skyDom);}onMove(){if(this.x <= -widthSky / 2) {this.x = 0;}}
}
const landDom = document.querySelector('.ground');
landStyle = getComputedStyle(landDom);
const widthLand = parseFloat(landStyle.width);
const heightLand = parseFloat(landStyle.width);class Land extends Rectangle{constructor(){super(widthLand, heightLand, 0, 488, -100, 0, landDom);}onMove(){if(this.x <= -widthLand / 2) {this.x = 0;}}
}
bird class
const birdDom = document.querySelector('.bird');
birdStyle = getComputedStyle(birdDom);
const widthBird = parseFloat(birdStyle.width);
const heightBird = parseFloat(birdStyle.height);class Bird extends Rectangle{gravity = 1000;   constructor(){super(widthBird, heightBird, 150, 200, 0, 100, birdDom);this.swingState = 1;this.bindEvent();}// 綁定鼠標按下bindEvent(){document.addEventListener('keydown', (e) => {if(e.key === 'w' || e.key === 'ArrowUp'){this.vy += -550;}})this.startSwing();}// 小鳥扇翅膀startSwing(){if(this.timer){return ;}this.timer = setInterval( () => {birdDom.classList.remove('swing'+this.swingState);this.swingState = (++this.swingState % 3) + 1;birdDom.classList.add('swing'+this.swingState);},300)}stopSwing(){clearInterval(this.timer);this.timer = null;}onMove(){if(this.y >= 463) {this.y = 463;this.vy =0;}if(this.y <= 0 ){this.y = 0;this.vy = 0;}}move(duration){super.move(duration);this.vy += this.gravity * duration;}}
pipe class
const game = document.querySelector('.game');
const gameWidth = game.clientWidth;
class Pipe extends Rectangle{isExited = true;constructor(height, top, speed, dom){super(52, height, gameWidth, top, speed, 0, dom);}onMove(){if(this.x < -this.width){this.dom.remove();this.isExited = false;}}}function getRandomNumber(min, max){return Math.floor(Math.random() * (max - min)) + min;
}class PipePare{stopTimer = null;constructor(speed){this.up = document.createElement('div');this.down = document.createElement('div');this.up.classList.add('pipeUp');this.down.classList.add('pipeDown');game.appendChild(this.up);game.appendChild(this.down);this.spaceHeihgt = 150;  // 柱子之間的空隙 const fristPipeHeight = getRandomNumber(0, 488-150);this.upPipe = new Pipe(fristPipeHeight, 0, speed, this.up);this.downPipe = new Pipe(338 - fristPipeHeight, 150 + fristPipeHeight, speed, this.down);}stop(){if(this.stopTimer){clearInterval(this.stopTimer);this.stopTimer = null;}this.down.remove();this.up.remove();}move(duration){this.stopTimer = setInterval( () => {this.upPipe.move(duration);this.downPipe.move(duration);},10)}isCollision(bird){const birdStyle = getComputedStyle(document.querySelector('.bird'))let y = Number.parseInt(birdStyle.top);if(this.upPipe.x < bird.x + bird.width && this.upPipe.x > bird.x){return y < this.upPipe.height || y + bird.height > this.upPipe.height + this.spaceHeihgt;}}
}class GamePipePair{pipeTimer = null;pipeArr = [];  // 用于显示的管道数组// 记录小鸟越过的数组scoreArr = [];constructor(speed){this.speed = speed;this.pair = new PipePare(speed);this.init();}init(){this.pipeTimer = setInterval( ()=> {let tmp = new PipePare(this.speed);tmp.move(0.01);this.pipeArr.push(tmp);this.scoreArr.push(tmp);}, 2000) }getScore(bird){return this.scoreArr.filter(item => item.upPipe.x <= bird.x).length;}stop(){this.pipeArr.forEach(item => {item.stop();})if(this.pipeTimer){clearInterval(this.pipeTimer);this.pipeTimer = null;}}collisionDetection(bird){  // 小鸟对象传入this.pipeArr = this.pipeArr.filter(item => item.upPipe.isExited); // 过滤掉了不存在的// 检查小鸟是否碰撞到柱子for(let i = 0 ;i < this.pipeArr.length;i++){if(this.pipeArr[i].isCollision(bird)){return true;}}return false;}}
game class
class Game {score = 0;land;sky;bird;backgroundTimer = null;pipeController = null;constructor(){this.land = new Land();this.sky = new Sky();this.bird = new Bird();this.state = 0;   // 0 遊戲結束  1遊戲開始進行中this.init();   }init(){document.onkeydown =  (e) => {if((e.key === 'w' || e.key === 'ArrowUp') && this.state === 0){console.log('開始遊戲');this.state = 1;this.startGame();}}}startGame(){this.pipeController = new GamePipePair(-100);if(this.backgroundTimer) return ;this.backgroundTimer = setInterval(() => {this.land.move(0.01);this.sky.move(0.01);this.bird.move(0.01);this.updateScore();if(this.pipeController){if(this.pipeController.collisionDetection(this.bird)){this.endGame();console.log('game ended');}}}, 10)}updateScore(){const score = document.querySelector('.score');this.score = this.pipeController.getScore(this.bird)score.innerHTML = this.score;}endGame(){if(this.backgroundTimer && this.state === 1){this.pipeController.stop();this.state = 0;this.bird.stopSwing();clearInterval(this.backgroundTimer);this.backgroundTimer = null;document.onkeydown = null;if(confirm(`游戏结束!! 你最后的得分是${this.score}分你想要再玩一局嘛 想玩点确定哦!!!`)){this.init();}}}}const birdGame = new Game();

4、源码+静态资源

像素鸟源码地址

这篇关于JS小游戏-像素鸟#源码#Javascript的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1085370

相关文章

springboot的调度服务与异步服务使用详解

《springboot的调度服务与异步服务使用详解》本文主要介绍了Java的ScheduledExecutorService接口和SpringBoot中如何使用调度线程池,包括核心参数、创建方式、自定... 目录1.调度服务1.1.JDK之ScheduledExecutorService1.2.spring

将java程序打包成可执行文件的实现方式

《将java程序打包成可执行文件的实现方式》本文介绍了将Java程序打包成可执行文件的三种方法:手动打包(将编译后的代码及JRE运行环境一起打包),使用第三方打包工具(如Launch4j)和JDK自带... 目录1.问题提出2.如何将Java程序打包成可执行文件2.1将编译后的代码及jre运行环境一起打包2

Java使用Tesseract-OCR实战教程

《Java使用Tesseract-OCR实战教程》本文介绍了如何在Java中使用Tesseract-OCR进行文本提取,包括Tesseract-OCR的安装、中文训练库的配置、依赖库的引入以及具体的代... 目录Java使用Tesseract-OCRTesseract-OCR安装配置中文训练库引入依赖代码实

Java中对象的创建和销毁过程详析

《Java中对象的创建和销毁过程详析》:本文主要介绍Java中对象的创建和销毁过程,对象的创建过程包括类加载检查、内存分配、初始化零值内存、设置对象头和执行init方法,对象的销毁过程由垃圾回收机... 目录前言对象的创建过程1. 类加载检查2China编程. 分配内存3. 初始化零值4. 设置对象头5. 执行

SpringBoot整合easy-es的详细过程

《SpringBoot整合easy-es的详细过程》本文介绍了EasyES,一个基于Elasticsearch的ORM框架,旨在简化开发流程并提高效率,EasyES支持SpringBoot框架,并提供... 目录一、easy-es简介二、实现基于Spring Boot框架的应用程序代码1.添加相关依赖2.添

通俗易懂的Java常见限流算法具体实现

《通俗易懂的Java常见限流算法具体实现》:本文主要介绍Java常见限流算法具体实现的相关资料,包括漏桶算法、令牌桶算法、Nginx限流和Redis+Lua限流的实现原理和具体步骤,并比较了它们的... 目录一、漏桶算法1.漏桶算法的思想和原理2.具体实现二、令牌桶算法1.令牌桶算法流程:2.具体实现2.1

SpringBoot中整合RabbitMQ(测试+部署上线最新完整)的过程

《SpringBoot中整合RabbitMQ(测试+部署上线最新完整)的过程》本文详细介绍了如何在虚拟机和宝塔面板中安装RabbitMQ,并使用Java代码实现消息的发送和接收,通过异步通讯,可以优化... 目录一、RabbitMQ安装二、启动RabbitMQ三、javascript编写Java代码1、引入

spring-boot-starter-thymeleaf加载外部html文件方式

《spring-boot-starter-thymeleaf加载外部html文件方式》本文介绍了在SpringMVC中使用Thymeleaf模板引擎加载外部HTML文件的方法,以及在SpringBoo... 目录1.Thymeleaf介绍2.springboot使用thymeleaf2.1.引入spring

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满