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

相关文章

Java五子棋之坐标校正

上篇针对了Java项目中的解构思维,在这篇内容中我们不妨从整体项目中拆解拿出一个非常重要的五子棋逻辑实现:坐标校正,我们如何使漫无目的鼠标点击变得有序化和可控化呢? 目录 一、从鼠标监听到获取坐标 1.MouseListener和MouseAdapter 2.mousePressed方法 二、坐标校正的具体实现方法 1.关于fillOval方法 2.坐标获取 3.坐标转换 4.坐

Spring Cloud:构建分布式系统的利器

引言 在当今的云计算和微服务架构时代,构建高效、可靠的分布式系统成为软件开发的重要任务。Spring Cloud 提供了一套完整的解决方案,帮助开发者快速构建分布式系统中的一些常见模式(例如配置管理、服务发现、断路器等)。本文将探讨 Spring Cloud 的定义、核心组件、应用场景以及未来的发展趋势。 什么是 Spring Cloud Spring Cloud 是一个基于 Spring

Javascript高级程序设计(第四版)--学习记录之变量、内存

原始值与引用值 原始值:简单的数据即基础数据类型,按值访问。 引用值:由多个值构成的对象即复杂数据类型,按引用访问。 动态属性 对于引用值而言,可以随时添加、修改和删除其属性和方法。 let person = new Object();person.name = 'Jason';person.age = 42;console.log(person.name,person.age);//'J

java8的新特性之一(Java Lambda表达式)

1:Java8的新特性 Lambda 表达式: 允许以更简洁的方式表示匿名函数(或称为闭包)。可以将Lambda表达式作为参数传递给方法或赋值给函数式接口类型的变量。 Stream API: 提供了一种处理集合数据的流式处理方式,支持函数式编程风格。 允许以声明性方式处理数据集合(如List、Set等)。提供了一系列操作,如map、filter、reduce等,以支持复杂的查询和转

Java面试八股之怎么通过Java程序判断JVM是32位还是64位

怎么通过Java程序判断JVM是32位还是64位 可以通过Java程序内部检查系统属性来判断当前运行的JVM是32位还是64位。以下是一个简单的方法: public class JvmBitCheck {public static void main(String[] args) {String arch = System.getProperty("os.arch");String dataM

详细分析Springmvc中的@ModelAttribute基本知识(附Demo)

目录 前言1. 注解用法1.1 方法参数1.2 方法1.3 类 2. 注解场景2.1 表单参数2.2 AJAX请求2.3 文件上传 3. 实战4. 总结 前言 将请求参数绑定到模型对象上,或者在请求处理之前添加模型属性 可以在方法参数、方法或者类上使用 一般适用这几种场景: 表单处理:通过 @ModelAttribute 将表单数据绑定到模型对象上预处理逻辑:在请求处理之前

eclipse运行springboot项目,找不到主类

解决办法尝试了很多种,下载sts压缩包行不通。最后解决办法如图: help--->Eclipse Marketplace--->Popular--->找到Spring Tools 3---->Installed。

JAVA读取MongoDB中的二进制图片并显示在页面上

1:Jsp页面: <td><img src="${ctx}/mongoImg/show"></td> 2:xml配置: <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001

Java面试题:通过实例说明内连接、左外连接和右外连接的区别

在 SQL 中,连接(JOIN)用于在多个表之间组合行。最常用的连接类型是内连接(INNER JOIN)、左外连接(LEFT OUTER JOIN)和右外连接(RIGHT OUTER JOIN)。它们的主要区别在于它们如何处理表之间的匹配和不匹配行。下面是每种连接的详细说明和示例。 表示例 假设有两个表:Customers 和 Orders。 Customers CustomerIDCus

22.手绘Spring DI运行时序图

1.依赖注入发生的时间 当Spring loC容器完成了 Bean定义资源的定位、载入和解析注册以后,loC容器中已经管理类Bean 定义的相关数据,但是此时loC容器还没有对所管理的Bean进行依赖注入,依赖注入在以下两种情况 发生: 、用户第一次调用getBean()方法时,loC容器触发依赖注入。 、当用户在配置文件中将<bean>元素配置了 lazy-init二false属性,即让