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

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

JS常用组件收集

收集了一些平时遇到的前端比较优秀的组件,方便以后开发的时候查找!!! 函数工具: Lodash 页面固定: stickUp、jQuery.Pin 轮播: unslider、swiper 开关: switch 复选框: icheck 气泡: grumble 隐藏元素: Headroom

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听