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处理跨域的实现方式(附Demo)

《Springboot处理跨域的实现方式(附Demo)》:本文主要介绍Springboot处理跨域的实现方式(附Demo),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不... 目录Springboot处理跨域的方式1. 基本知识2. @CrossOrigin3. 全局跨域设置4.

springboot security使用jwt认证方式

《springbootsecurity使用jwt认证方式》:本文主要介绍springbootsecurity使用jwt认证方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录前言代码示例依赖定义mapper定义用户信息的实体beansecurity相关的类提供登录接口测试提供一

Spring Boot 3.4.3 基于 Spring WebFlux 实现 SSE 功能(代码示例)

《SpringBoot3.4.3基于SpringWebFlux实现SSE功能(代码示例)》SpringBoot3.4.3结合SpringWebFlux实现SSE功能,为实时数据推送提供... 目录1. SSE 简介1.1 什么是 SSE?1.2 SSE 的优点1.3 适用场景2. Spring WebFlu

基于SpringBoot实现文件秒传功能

《基于SpringBoot实现文件秒传功能》在开发Web应用时,文件上传是一个常见需求,然而,当用户需要上传大文件或相同文件多次时,会造成带宽浪费和服务器存储冗余,此时可以使用文件秒传技术通过识别重复... 目录前言文件秒传原理代码实现1. 创建项目基础结构2. 创建上传存储代码3. 创建Result类4.

Java利用JSONPath操作JSON数据的技术指南

《Java利用JSONPath操作JSON数据的技术指南》JSONPath是一种强大的工具,用于查询和操作JSON数据,类似于SQL的语法,它为处理复杂的JSON数据结构提供了简单且高效... 目录1、简述2、什么是 jsONPath?3、Java 示例3.1 基本查询3.2 过滤查询3.3 递归搜索3.4

Tomcat版本与Java版本的关系及说明

《Tomcat版本与Java版本的关系及说明》:本文主要介绍Tomcat版本与Java版本的关系及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Tomcat版本与Java版本的关系Tomcat历史版本对应的Java版本Tomcat支持哪些版本的pythonJ

springboot security验证码的登录实例

《springbootsecurity验证码的登录实例》:本文主要介绍springbootsecurity验证码的登录实例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录前言代码示例引入依赖定义验证码生成器定义获取验证码及认证接口测试获取验证码登录总结前言在spring

SpringBoot日志配置SLF4J和Logback的方法实现

《SpringBoot日志配置SLF4J和Logback的方法实现》日志记录是不可或缺的一部分,本文主要介绍了SpringBoot日志配置SLF4J和Logback的方法实现,文中通过示例代码介绍的非... 目录一、前言二、案例一:初识日志三、案例二:使用Lombok输出日志四、案例三:配置Logback一

springboot security快速使用示例详解

《springbootsecurity快速使用示例详解》:本文主要介绍springbootsecurity快速使用示例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝... 目录创www.chinasem.cn建spring boot项目生成脚手架配置依赖接口示例代码项目结构启用s

java之Objects.nonNull用法代码解读

《java之Objects.nonNull用法代码解读》:本文主要介绍java之Objects.nonNull用法代码,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录Java之Objects.nonwww.chinasem.cnNull用法代码Objects.nonN