欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript實現(xiàn)一個簡單的圣誕游戲

 更新時間:2021年12月22日 08:38:20   作者:五包辣條!  
圣誕節(jié)即將來臨,大家都在發(fā)圣誕樹,小編今天就為大家介紹一個基于JavaScript實現(xiàn)的圣誕小游戲,文中的示例代碼簡單易懂,感興趣的可以學(xué)習(xí)一下

前言

圣誕節(jié)快來了,熱榜都被一堆圣誕樹攻占了,這樣的流量密碼我怎么會錯過,大家都發(fā)圣誕樹,我就不發(fā)啦,直接分享一個圣誕小游戲給大家玩,代碼太長一定要先贊和收藏。

實現(xiàn)效果

一個簡單的2D網(wǎng)頁小游戲它的制作過程是有規(guī)律可尋的,它每個部分都有一定的套路,我們應(yīng)該

把有規(guī)律的部分總結(jié)在一起,形成一個模板,把相應(yīng)的模板寫好了,到要生產(chǎn)某個對象時就可以用

模板,還有游戲的整個流程每個函數(shù),每個js文件之間都是分工明確的;我們要總結(jié)好了才寫,

不要想到哪就寫哪,這樣雖然結(jié)果是相同的,但可能代碼的可讀性和維護(hù)性不是很強(qiáng),思路不是很

清晰。

代碼

代碼這塊沒啥好說的,直接給大家貼上代碼了,簡單直接,能運行可以玩就可以了,分享給自己的朋友或者自己摸魚玩,就圖一樂。文件我已經(jīng)打包好了,需要的話可以私我哦。

CSS代碼

body { background:rgb(8,8,58);
  margin:0;
}

#wrapper {
  width:500px;
  margin-left:auto;
  margin-right:auto;
  margin-top:20px;
}

JS代碼

?var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d"),
    elfImage = document.getElementById("elf");
greenGiftImage = document.getElementById("green_gift");
redGiftImage = document.getElementById("red_gift");
blueGiftImage = document.getElementById("blue_gift");
bombImage = document.getElementById("bomb");
bangImage = document.getElementById("bang");

var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;
const elfHeight = 70;
const elfWidth = 55;
var elfX = (canvas.width-elfWidth)/2;
const elfSpeed = 10;
var rightPressed = false;
var leftPressed = false;
var spacePressed = false;
var spawnInterval;
var spawnTimer = 50;
var gifts = [];
var maxGift = 0;
const giftWidth = 40;
const giftHeight = 40;
var timer = 0;
var giftRotation = 0;
const TO_RADIANS = Math.PI/180; 
var score = 0;
var health = 3;
const bombChance = 5;
var elfRotation = 0;
var bangX;
var bangTime;
var snowHeight = 6;
var spawnTimeChangeInterval = 3000;
var titleColours = [];

// snowflake stuff
var snowflakes = [];
const maxSnowflakes = 80;
const snowflakeSize = 3;
const snowflakeMinSpeed = 1;
const snowflakeMaxSpeed = 4;
const snowflakeColours = ["rgba(255,255,255,0.95)", "rgba(255,255,255,0.65)","rgba(255,255,255,0.4)"];

const gameModes = {
  TITLE: 'title',
  PLAYING: 'playing',
  GAMEOVER: 'gameover'
};

var gameMode = gameModes.TITLE;

document.addEventListener("keydown", keyDownHandler, false);
document.addEventListener("keyup", keyUpHandler, false);

function keyDownHandler(e) {
  if(e.key == "Right" || e.key == "ArrowRight") {
    rightPressed = true;
  }
  else if(e.key == "Left" || e.key == "ArrowLeft") {
    leftPressed = true;
  } else if(e.code == "Space") {
    spacePressed = true;
  }
}

function keyUpHandler(e) {
  if(e.key == "Right" || e.key == "ArrowRight") {
    rightPressed = false;
  }
  else if(e.key == "Left" || e.key == "ArrowLeft") {
    leftPressed = false;
  } else if(e.code == "Space") {
    spacePressed = false;
  }
}

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawSnow();

  timer++;

  switch (gameMode) {
    case gameModes.TITLE:
      titleScreen(); 
      break;
    case gameModes.GAMEOVER:
      gameOver();
      break;
    case gameModes.PLAYING:
      gameLoop();
      break;
  }
}

function titleScreen() {
  if (timer > titleColours.length) timer=0;

  ctx.font = "50px Arial";
  ctx.fillStyle = titleColours[timer]; 
  ctx.fillText(`圣誕抓禮物!`, 0, 50);
  ctx.fillStyle = "yellow"; 

  ctx.font = "30px Arial";
  ctx.fillText(`請按空格鍵開始!`, 65, 140);

  var highScore = getHighScore();
  if (highScore != -1) ctx.fillText(`High Score: ${highScore}`, 90, 220);

  drawRotatedImage(elfImage, canvas.width/2 - elfWidth/2, 330, elfRotation, 200);
  elfRotation+=2;
  if (elfRotation > 359) elfRotation = 0;

  if (spacePressed && timer > 5) {
    setGameMode(gameModes.PLAYING);
  }
}

function gameLoop() {
  drawSnowPerson();
  spawnGifts();
  processGifts();
  drawFloor();
  drawHUD();
  drawElf();
  drawBang();

  if(rightPressed) {
    elfX += elfSpeed;
    if (elfX + elfWidth > canvas.width){
      elfX = canvas.width - (elfWidth + 5);
    }
  }
  else if(leftPressed) {
    elfX -= elfSpeed;
    if (elfX < -15){
      elfX = -15;
    }
  }
}

function gameOver() {
  ctx.font = "50px Arial";
  ctx.fillStyle = "yellow";
  ctx.fillText(`GAME OVER!`, 80, 200);
  ctx.font = "30px Arial";
  ctx.fillText(`Final score: ${score}`,130, 240);
  ctx.fillText('Press space to continue',80, 280);

  if (spacePressed && timer > 5) {
    initialiseGame();
    setGameMode(gameModes.TITLE);
  }
}

function processGifts() {
  gifts.forEach((g) => {
    if (g && g.alive) { 
      // draw gift
      drawGift(g);
      if (g.y > canvas.height) {
        g.alive = false;
        if (!g.bomb) score--;
      }

      // move gift
      g.y+=g.speed;

      // rotate gift
      g.rotation+=5;
      if ( g.rotation > 359) g.rotation = 0;

      // check for collision
      if ((g.y + (giftHeight/2)) >= ((canvas.height - elfHeight - snowHeight) + 20)
          && (g.y<canvas.height-snowHeight+20)) {
        if ((elfX + 25) <= (g.x + (giftWidth/2)) && ((elfX+20) + (elfWidth)) >= g.x )
        {
          g.alive = false;
          if (!g.bomb) { 
            score+=5;
          } else {
            doBombCollision();
          }
        }
      }
    }
  });
}

function drawGift(g) {
  switch (g.colour) {
    case 1:
      drawColouredGift(greenGiftImage, g);
      break;
    case 2:
      drawColouredGift(redGiftImage, g);
      break;
    case 3:
      drawColouredGift(blueGiftImage, g);
      break;
    case 4:
      drawRotatedImage(bombImage, g.x, g.y, 180, 45);
      break;
  }
}

function drawColouredGift(colourImage, g) {
  drawRotatedImage(colourImage, g.x, g.y, g.rotation, 35);
}

function doBombCollision() {
  health--;
  bangX=elfX;
  bangTime = 5;
  if (health == 0) {
    setHighScore();
    setGameMode(gameModes.GAMEOVER);
  }
}

function drawBang() {
  if (bangTime > 0) {
    bangTime--;
    ctx.drawImage(bangImage, bangX, (canvas.height-75)-snowHeight, 75,75);
  }
}


function drawElf() {
  ctx.drawImage(elfImage, elfX,(canvas.height - elfHeight) - (snowHeight - 2),80,80);
}

function spawn() {
  var newX = 5 + (Math.random() * (canvas.width - 5));

  var colour;
  var bomb = false;

  if (randomNumber(1,bombChance) == bombChance) {
    colour = 4;
    bomb = true;
  } else {
    colour = randomNumber(1,3);
  }

  var newGift = {
    x: newX,
    y: 0,
    speed: randomNumber(2,6),
    alive: true,
    rotation: 0,
    colour: colour,
    bomb: bomb,
  };

  gifts[maxGift] = newGift;
  maxGift++;
  if (maxGift > 75) {
    maxGift = 0;
  }
}

function spawnGifts() {
  if (timer > spawnTimer) {
    spawn();
    timer = 0;
  }
}

function drawRotatedImage(image, x, y, angle, scale)
{ 
  ctx.save(); 
  ctx.translate(x, y);
  ctx.rotate(angle * TO_RADIANS);
  ctx.drawImage(image, -(image.width/2), -(image.height/2), scale, scale);
  ctx.restore(); 
}

function drawHUD() {
  ctx.font = "20px Arial";
  ctx.fillStyle = "yellow";
  ctx.fillText(`Score: ${score}`, 0, 25);

  var heart = '?';
  var hearts = health > 0 ? heart.repeat(health) : " ";
  ctx.fillText("Helf:", canvas.width - 120, 25);
  ctx.fillStyle = "red";
  ctx.fillText(`${hearts}`, canvas.width - 60, 26);
}

function initialiseGame() {
  health = 3;
  elfX = (canvas.width-elfWidth)/2;
  bangTime = 0;
  score = 0;
  snowHeight = 6;
  timer = 0;
  spawnTimer = 50;
  gifts = [];
}

function initialiseSnow() {
  for (i=0; i<maxSnowflakes; i++) {
    var startY = -randomNumber(0, canvas.height);
    snowflakes[i] = {
      x: randomNumber(0, canvas.width-snowflakeSize),
      y: startY,
      startY: startY,
      colour: snowflakeColours[randomNumber(0,3)],
      radius: (Math.random() * 3 + 1),
      speed: randomNumber(snowflakeMinSpeed, snowflakeMaxSpeed)
    };
  }
}

function drawSnow() {
  for (i=0; i<maxSnowflakes; i++) {
    snowflakes[i].y+=snowflakes[i].speed;
    if (snowflakes[i].y>canvas.height) snowflakes[i].y = snowflakes[i].startY;
    ctx.beginPath();
    ctx.arc(snowflakes[i].x, snowflakes[i].y, snowflakes[i].radius, 0, 2 * Math.PI, false);
    ctx.fillStyle = snowflakes[i].colour;
    ctx.fill();
  }
}

function drawFloor() {
  var snowTopY = canvas.height - snowHeight;

  ctx.fillStyle = '#fff';
  ctx.beginPath();
  ctx.moveTo(0, snowTopY);
  ctx.lineTo(canvas.width, snowTopY);
  ctx.lineTo(canvas.width, canvas.height);
  ctx.lineTo(0, canvas.height);
  ctx.closePath();
  ctx.fill();
}

function drawSnowPerson() {
  var snowTopY = canvas.height - snowHeight;

  drawCircle("#fff", 100, snowTopY-20, 40);
  drawCircle("#fff", 100, snowTopY-70, 20);
  drawRectangle("#835C3B", 85, snowTopY-105, 30, 20);
  drawRectangle("#835C3B", 75, snowTopY-90, 50, 6);
  drawTriangle("#ffa500", 100, snowTopY-64, 7);
  drawCircle("#000", 93, snowTopY-76, 3);
  drawCircle("#000", 108, snowTopY-76, 3);
  drawCircle("#000", 100, snowTopY-40, 2);
  drawCircle("#000", 100, snowTopY-30, 2);
  drawCircle("#000", 100, snowTopY-20, 2);
}

function drawTriangle(color, x, y, height) {
  ctx.strokeStyle = ctx.fillStyle = color;
  ctx.beginPath();
  ctx.moveTo(x, y);
  ctx.lineTo(x - height, y - height);
  ctx.lineTo(x + height, y - height);
  ctx.fill();
}

function drawCircle(color, x, y, radius) {
  ctx.strokeStyle = ctx.fillStyle = color;
  ctx.beginPath();
  ctx.arc(x, y, radius, 0, Math.PI * 2, true);
  ctx.closePath();
  ctx.stroke();
  ctx.fill();
}

function drawRectangle(color, x, y, width, height) {
  ctx.strokeStyle = ctx.fillStyle = color;
  ctx.fillRect(x, y, width, height);
}

function randomNumber(low, high) {
  return Math.floor(Math.random() * high) + low; 
}

function makeColorGradient(frequency1, frequency2, frequency3,
                            phase1, phase2, phase3,
                            center, width, len) {
  var colours = [];

  for (var i = 0; i < len; ++i)
  {
    var r = Math.sin(frequency1*i + phase1) * width + center;
    var g = Math.sin(frequency2*i + phase2) * width + center;
    var b = Math.sin(frequency3*i + phase3) * width + center;
    colours.push(RGB2Color(r,g,b));
  }
  return colours;
}

function RGB2Color(r,g,b) {
  return '#' + byte2Hex(r) + byte2Hex(g) + byte2Hex(b);
}

function byte2Hex(n) {
  var nybHexString = "0123456789ABCDEF";
  return String(nybHexString.substr((n >> 4) & 0x0F,1)) + nybHexString.substr(n & 0x0F,1);
}

function setColourGradient() {
  center = 128;
  width = 127;
  steps = 6;
  frequency = 2*Math.PI/steps;
  return makeColorGradient(frequency,frequency,frequency,0,2,4,center,width,50);
}

function initialiseSpawnInterval() {
  if (gameMode === gameModes.PLAYING && spawnTimer>2) {
    spawnTimer--;
    spawnTimeChangeInterval-=50;
  }
}

function setGameMode(mode) {
  gameMode = mode;
  timer=0;
}

function raiseSnow() {
  if (gameMode === gameModes.PLAYING && snowHeight < canvas.height) {
    snowHeight++;
  }
}

function setHighScore() {
  var currentHighScore = getHighScore();
  if (currentHighScore !=-1 && score > currentHighScore) {
    localStorage.setItem("highScore", score);
  }
}

function getHighScore() {
  if (!localStorage) return -1;
  var highScore = localStorage.getItem("highScore");
  return highScore || 0;
}

titleColours = setColourGradient();
initialiseSnow();
setInterval(draw, 30);
setInterval(initialiseSpawnInterval, spawnTimeChangeInterval);
setInterval(raiseSnow, 666);

html代碼

<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Elf Gift Catch</title>

<link rel="stylesheet" href="css/style.css" rel="external nofollow" >#中間省略N個代碼太長了

</head>
<body>

<div id="wrapper">

	<canvas id="canvas" width="450" height="540"></canvas>
	
</div>


  
</div>

<script  src="js/script.js"></script>

</body>
</html>

演示流程

打包的文件就三個,一個css的代碼,一個JS的代碼,還有一個html的文件,打包好之后,點擊html的文件就能直接運行了呢。

以上就是JavaScript實現(xiàn)一個簡單的圣誕游戲的詳細(xì)內(nèi)容,更多關(guān)于JavaScript圣誕游戲的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • javascript關(guān)于open.window子頁面執(zhí)行完成后刷新父頁面的問題分析

    javascript關(guān)于open.window子頁面執(zhí)行完成后刷新父頁面的問題分析

    這篇文章主要介紹了javascript關(guān)于open.window子頁面執(zhí)行完成后刷新父頁面的問題,實例分析了javascript操作子頁面的執(zhí)行與父頁面的刷新技巧,非常具有實用價值,需要的朋友可以參考下
    2015-04-04
  • React Native登錄之指紋登錄篇的示例代碼

    React Native登錄之指紋登錄篇的示例代碼

    這篇文章主要介紹了React Native登錄之指紋登錄篇,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-11-11
  • 小程序?qū)崿F(xiàn)訂單評價和商家評價

    小程序?qū)崿F(xiàn)訂單評價和商家評價

    這篇文章主要為大家詳細(xì)介紹了小程序?qū)崿F(xiàn)訂單評價和商家評價功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-04-04
  • JS實現(xiàn)選擇TextArea內(nèi)文本的方法

    JS實現(xiàn)選擇TextArea內(nèi)文本的方法

    這篇文章主要介紹了JS實現(xiàn)選擇TextArea內(nèi)文本的方法,涉及javascript針對頁面TextArea元素焦點設(shè)置及文本獲取的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-08-08
  • 基于webpack.config.js 參數(shù)詳解

    基于webpack.config.js 參數(shù)詳解

    下面小編就為大家分享一篇基于webpack.config.js 參數(shù)詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-03-03
  • DataTables添加額外的查詢參數(shù)和刪除columns等無用參數(shù)實例

    DataTables添加額外的查詢參數(shù)和刪除columns等無用參數(shù)實例

    下面小編就為大家?guī)硪黄狣ataTables添加額外的查詢參數(shù)和刪除columns等無用參數(shù)實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-07-07
  • 淺談移動端之js touch事件 手勢滑動事件

    淺談移動端之js touch事件 手勢滑動事件

    這篇文章主要和大家聊一聊移動端之js touch事件,即手指的滑動事件,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-11-11
  • JS鼠標(biāo)滾動分頁效果示例

    JS鼠標(biāo)滾動分頁效果示例

    在開發(fā)的時候為什么左邊的數(shù)據(jù)出來比右邊的慢呢?因為這里沒有進(jìn)行分頁,左邊的數(shù)據(jù)多,所以查詢相對較慢。怎么解決此問題呢?下面小編給大家?guī)砹薐S鼠標(biāo)滾動分頁效果示例,需要的的朋友參考下吧
    2017-07-07
  • 讀懂CommonJS的模塊加載

    讀懂CommonJS的模塊加載

    這篇文章主要介紹了CommonJS的模塊加載,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • js事件觸發(fā)操作實例分析

    js事件觸發(fā)操作實例分析

    這篇文章主要介紹了js事件觸發(fā)操作,結(jié)合實例形式分析了javascript事件觸發(fā)機(jī)制原理、使用方法及相關(guān)操作注意事項,需要的朋友可以參考下
    2019-06-06

最新評論