耀极客论坛

 找回密码
 立即注册
查看: 537|回复: 0

JavaScript实现一个简单的圣诞游戏

[复制链接]

193

主题

176

帖子

276

积分

中级会员

Rank: 3Rank: 3

积分
276
发表于 2022-5-8 02:04:09 | 显示全部楼层 |阅读模式
  圣诞节即将来临,大家都在发圣诞树,小编今天就为大家介绍一个基于JavaScript实现的圣诞小游戏,文中的示例代码简单易懂,感兴趣的可以学习一下

前言

  圣诞节快来了,热榜都被一堆圣诞树攻占了,这样的流量密码我怎么会错过,大家都发圣诞树,我就不发啦,直接分享一个圣诞小游戏给大家玩,代码太长一定要先赞和收藏。

实现效果
  一个简单的2D网页小游戏它的制作过程是有规律可寻的,它每个部分都有一定的套路,我们应该
  把有规律的部分总结在一起,形成一个模板,把相应的模板写好了,到要生产某个对象时就可以用
  模板,还有游戏的整个流程每个函数,每个js文件之间都是分工明确的;我们要总结好了才写,
  不要想到哪就写哪,这样虽然结果是相同的,但可能代码的可读性和维护性不是很强,思路不是很
  清晰。


代码
  代码这块没啥好说的,直接给大家贴上代码了,简单直接,能运行可以玩就可以了,分享给自己的朋友或者自己摸鱼玩,就图一乐。文件我已经打包好了,需要的话可以私我哦。

CSS代码
  1. body { background:rgb(8,8,58);
  2.   margin:0;
  3. }
  4. #wrapper {
  5.   width:500px;
  6.   margin-left:auto;
  7.   margin-right:auto;
  8.   margin-top:20px;
  9. }
复制代码
JS代码
  1. ​var canvas = document.getElementById("canvas"),
  2.     ctx = canvas.getContext("2d"),
  3.     elfImage = document.getElementById("elf");
  4. greenGiftImage = document.getElementById("green_gift");
  5. redGiftImage = document.getElementById("red_gift");
  6. blueGiftImage = document.getElementById("blue_gift");
  7. bombImage = document.getElementById("bomb");
  8. bangImage = document.getElementById("bang");
  9. var x = canvas.width/2;
  10. var y = canvas.height-30;
  11. var dx = 2;
  12. var dy = -2;
  13. const elfHeight = 70;
  14. const elfWidth = 55;
  15. var elfX = (canvas.width-elfWidth)/2;
  16. const elfSpeed = 10;
  17. var rightPressed = false;
  18. var leftPressed = false;
  19. var spacePressed = false;
  20. var spawnInterval;
  21. var spawnTimer = 50;
  22. var gifts = [];
  23. var maxGift = 0;
  24. const giftWidth = 40;
  25. const giftHeight = 40;
  26. var timer = 0;
  27. var giftRotation = 0;
  28. const TO_RADIANS = Math.PI/180;
  29. var score = 0;
  30. var health = 3;
  31. const bombChance = 5;
  32. var elfRotation = 0;
  33. var bangX;
  34. var bangTime;
  35. var snowHeight = 6;
  36. var spawnTimeChangeInterval = 3000;
  37. var titleColours = [];
  38. // snowflake stuff
  39. var snowflakes = [];
  40. const maxSnowflakes = 80;
  41. const snowflakeSize = 3;
  42. const snowflakeMinSpeed = 1;
  43. const snowflakeMaxSpeed = 4;
  44. const snowflakeColours = ["rgba(255,255,255,0.95)", "rgba(255,255,255,0.65)","rgba(255,255,255,0.4)"];
  45. const gameModes = {
  46.   TITLE: 'title',
  47.   PLAYING: 'playing',
  48.   GAMEOVER: 'gameover'
  49. };
  50. var gameMode = gameModes.TITLE;
  51. document.addEventListener("keydown", keyDownHandler, false);
  52. document.addEventListener("keyup", keyUpHandler, false);
  53. function keyDownHandler(e) {
  54.   if(e.key == "Right" || e.key == "ArrowRight") {
  55.     rightPressed = true;
  56.   }
  57.   else if(e.key == "Left" || e.key == "ArrowLeft") {
  58.     leftPressed = true;
  59.   } else if(e.code == "Space") {
  60.     spacePressed = true;
  61.   }
  62. }
  63. function keyUpHandler(e) {
  64.   if(e.key == "Right" || e.key == "ArrowRight") {
  65.     rightPressed = false;
  66.   }
  67.   else if(e.key == "Left" || e.key == "ArrowLeft") {
  68.     leftPressed = false;
  69.   } else if(e.code == "Space") {
  70.     spacePressed = false;
  71.   }
  72. }
  73. function draw() {
  74.   ctx.clearRect(0, 0, canvas.width, canvas.height);
  75.   drawSnow();
  76.   timer++;
  77.   switch (gameMode) {
  78.     case gameModes.TITLE:
  79.       titleScreen();
  80.       break;
  81.     case gameModes.GAMEOVER:
  82.       gameOver();
  83.       break;
  84.     case gameModes.PLAYING:
  85.       gameLoop();
  86.       break;
  87.   }
  88. }
  89. function titleScreen() {
  90.   if (timer > titleColours.length) timer=0;
  91.   ctx.font = "50px Arial";
  92.   ctx.fillStyle = titleColours[timer];
  93.   ctx.fillText(`圣诞抓礼物!`, 0, 50);
  94.   ctx.fillStyle = "yellow";
  95.   ctx.font = "30px Arial";
  96.   ctx.fillText(`请按空格键开始!`, 65, 140);
  97.   var highScore = getHighScore();
  98.   if (highScore != -1) ctx.fillText(`High Score: ${highScore}`, 90, 220);
  99.   drawRotatedImage(elfImage, canvas.width/2 - elfWidth/2, 330, elfRotation, 200);
  100.   elfRotation+=2;
  101.   if (elfRotation > 359) elfRotation = 0;
  102.   if (spacePressed && timer > 5) {
  103.     setGameMode(gameModes.PLAYING);
  104.   }
  105. }
  106. function gameLoop() {
  107.   drawSnowPerson();
  108.   spawnGifts();
  109.   processGifts();
  110.   drawFloor();
  111.   drawHUD();
  112.   drawElf();
  113.   drawBang();
  114.   if(rightPressed) {
  115.     elfX += elfSpeed;
  116.     if (elfX + elfWidth > canvas.width){
  117.       elfX = canvas.width - (elfWidth + 5);
  118.     }
  119.   }
  120.   else if(leftPressed) {
  121.     elfX -= elfSpeed;
  122.     if (elfX ‹ -15){
  123.       elfX = -15;
  124.     }
  125.   }
  126. }
  127. function gameOver() {
  128.   ctx.font = "50px Arial";
  129.   ctx.fillStyle = "yellow";
  130.   ctx.fillText(`GAME OVER!`, 80, 200);
  131.   ctx.font = "30px Arial";
  132.   ctx.fillText(`Final score: ${score}`,130, 240);
  133.   ctx.fillText('Press space to continue',80, 280);
  134.   if (spacePressed && timer > 5) {
  135.     initialiseGame();
  136.     setGameMode(gameModes.TITLE);
  137.   }
  138. }
  139. function processGifts() {
  140.   gifts.forEach((g) => {
  141.     if (g && g.alive) {
  142.       // draw gift
  143.       drawGift(g);
  144.       if (g.y > canvas.height) {
  145.         g.alive = false;
  146.         if (!g.bomb) score--;
  147.       }
  148.       // move gift
  149.       g.y+=g.speed;
  150.       // rotate gift
  151.       g.rotation+=5;
  152.       if ( g.rotation > 359) g.rotation = 0;
  153.       // check for collision
  154.       if ((g.y + (giftHeight/2)) >= ((canvas.height - elfHeight - snowHeight) + 20)
  155.           && (g.y‹canvas.height-snowHeight+20)) {
  156.         if ((elfX + 25) ‹= (g.x + (giftWidth/2)) && ((elfX+20) + (elfWidth)) >= g.x )
  157.         {
  158.           g.alive = false;
  159.           if (!g.bomb) {
  160.             score+=5;
  161.           } else {
  162.             doBombCollision();
  163.           }
  164.         }
  165.       }
  166.     }
  167.   });
  168. }
  169. function drawGift(g) {
  170.   switch (g.colour) {
  171.     case 1:
  172.       drawColouredGift(greenGiftImage, g);
  173.       break;
  174.     case 2:
  175.       drawColouredGift(redGiftImage, g);
  176.       break;
  177.     case 3:
  178.       drawColouredGift(blueGiftImage, g);
  179.       break;
  180.     case 4:
  181.       drawRotatedImage(bombImage, g.x, g.y, 180, 45);
  182.       break;
  183.   }
  184. }
  185. function drawColouredGift(colourImage, g) {
  186.   drawRotatedImage(colourImage, g.x, g.y, g.rotation, 35);
  187. }
  188. function doBombCollision() {
  189.   health--;
  190.   bangX=elfX;
  191.   bangTime = 5;
  192.   if (health == 0) {
  193.     setHighScore();
  194.     setGameMode(gameModes.GAMEOVER);
  195.   }
  196. }
  197. function drawBang() {
  198.   if (bangTime > 0) {
  199.     bangTime--;
  200.     ctx.drawImage(bangImage, bangX, (canvas.height-75)-snowHeight, 75,75);
  201.   }
  202. }
  203. function drawElf() {
  204.   ctx.drawImage(elfImage, elfX,(canvas.height - elfHeight) - (snowHeight - 2),80,80);
  205. }
  206. function spawn() {
  207.   var newX = 5 + (Math.random() * (canvas.width - 5));
  208.   var colour;
  209.   var bomb = false;
  210.   if (randomNumber(1,bombChance) == bombChance) {
  211.     colour = 4;
  212.     bomb = true;
  213.   } else {
  214.     colour = randomNumber(1,3);
  215.   }
  216.   var newGift = {
  217.     x: newX,
  218.     y: 0,
  219.     speed: randomNumber(2,6),
  220.     alive: true,
  221.     rotation: 0,
  222.     colour: colour,
  223.     bomb: bomb,
  224.   };
  225.   gifts[maxGift] = newGift;
  226.   maxGift++;
  227.   if (maxGift > 75) {
  228.     maxGift = 0;
  229.   }
  230. }
  231. function spawnGifts() {
  232.   if (timer > spawnTimer) {
  233.     spawn();
  234.     timer = 0;
  235.   }
  236. }
  237. function drawRotatedImage(image, x, y, angle, scale)
  238. {
  239.   ctx.save();
  240.   ctx.translate(x, y);
  241.   ctx.rotate(angle * TO_RADIANS);
  242.   ctx.drawImage(image, -(image.width/2), -(image.height/2), scale, scale);
  243.   ctx.restore();
  244. }
  245. function drawHUD() {
  246.   ctx.font = "20px Arial";
  247.   ctx.fillStyle = "yellow";
  248.   ctx.fillText(`Score: ${score}`, 0, 25);
  249.   var heart = '❤';
  250.   var hearts = health > 0 ? heart.repeat(health) : " ";
  251.   ctx.fillText("Helf:", canvas.width - 120, 25);
  252.   ctx.fillStyle = "red";
  253.   ctx.fillText(`${hearts}`, canvas.width - 60, 26);
  254. }
  255. function initialiseGame() {
  256.   health = 3;
  257.   elfX = (canvas.width-elfWidth)/2;
  258.   bangTime = 0;
  259.   score = 0;
  260.   snowHeight = 6;
  261.   timer = 0;
  262.   spawnTimer = 50;
  263.   gifts = [];
  264. }
  265. function initialiseSnow() {
  266.   for (i=0; i‹maxSnowflakes; i++) {
  267.     var startY = -randomNumber(0, canvas.height);
  268.     snowflakes[i] = {
  269.       x: randomNumber(0, canvas.width-snowflakeSize),
  270.       y: startY,
  271.       startY: startY,
  272.       colour: snowflakeColours[randomNumber(0,3)],
  273.       radius: (Math.random() * 3 + 1),
  274.       speed: randomNumber(snowflakeMinSpeed, snowflakeMaxSpeed)
  275.     };
  276.   }
  277. }
  278. function drawSnow() {
  279.   for (i=0; i‹maxSnowflakes; i++) {
  280.     snowflakes[i].y+=snowflakes[i].speed;
  281.     if (snowflakes[i].y>canvas.height) snowflakes[i].y = snowflakes[i].startY;
  282.     ctx.beginPath();
  283.     ctx.arc(snowflakes[i].x, snowflakes[i].y, snowflakes[i].radius, 0, 2 * Math.PI, false);
  284.     ctx.fillStyle = snowflakes[i].colour;
  285.     ctx.fill();
  286.   }
  287. }
  288. function drawFloor() {
  289.   var snowTopY = canvas.height - snowHeight;
  290.   ctx.fillStyle = '#fff';
  291.   ctx.beginPath();
  292.   ctx.moveTo(0, snowTopY);
  293.   ctx.lineTo(canvas.width, snowTopY);
  294.   ctx.lineTo(canvas.width, canvas.height);
  295.   ctx.lineTo(0, canvas.height);
  296.   ctx.closePath();
  297.   ctx.fill();
  298. }
  299. function drawSnowPerson() {
  300.   var snowTopY = canvas.height - snowHeight;
  301.   drawCircle("#fff", 100, snowTopY-20, 40);
  302.   drawCircle("#fff", 100, snowTopY-70, 20);
  303.   drawRectangle("#835C3B", 85, snowTopY-105, 30, 20);
  304.   drawRectangle("#835C3B", 75, snowTopY-90, 50, 6);
  305.   drawTriangle("#ffa500", 100, snowTopY-64, 7);
  306.   drawCircle("#000", 93, snowTopY-76, 3);
  307.   drawCircle("#000", 108, snowTopY-76, 3);
  308.   drawCircle("#000", 100, snowTopY-40, 2);
  309.   drawCircle("#000", 100, snowTopY-30, 2);
  310.   drawCircle("#000", 100, snowTopY-20, 2);
  311. }
  312. function drawTriangle(color, x, y, height) {
  313.   ctx.strokeStyle = ctx.fillStyle = color;
  314.   ctx.beginPath();
  315.   ctx.moveTo(x, y);
  316.   ctx.lineTo(x - height, y - height);
  317.   ctx.lineTo(x + height, y - height);
  318.   ctx.fill();
  319. }
  320. function drawCircle(color, x, y, radius) {
  321.   ctx.strokeStyle = ctx.fillStyle = color;
  322.   ctx.beginPath();
  323.   ctx.arc(x, y, radius, 0, Math.PI * 2, true);
  324.   ctx.closePath();
  325.   ctx.stroke();
  326.   ctx.fill();
  327. }
  328. function drawRectangle(color, x, y, width, height) {
  329.   ctx.strokeStyle = ctx.fillStyle = color;
  330.   ctx.fillRect(x, y, width, height);
  331. }
  332. function randomNumber(low, high) {
  333.   return Math.floor(Math.random() * high) + low;
  334. }
  335. function makeColorGradient(frequency1, frequency2, frequency3,
  336.                             phase1, phase2, phase3,
  337.                             center, width, len) {
  338.   var colours = [];
  339.   for (var i = 0; i ‹ len; ++i)
  340.   {
  341.     var r = Math.sin(frequency1*i + phase1) * width + center;
  342.     var g = Math.sin(frequency2*i + phase2) * width + center;
  343.     var b = Math.sin(frequency3*i + phase3) * width + center;
  344.     colours.push(RGB2Color(r,g,b));
  345.   }
  346.   return colours;
  347. }
  348. function RGB2Color(r,g,b) {
  349.   return '#' + byte2Hex(r) + byte2Hex(g) + byte2Hex(b);
  350. }
  351. function byte2Hex(n) {
  352.   var nybHexString = "0123456789ABCDEF";
  353.   return String(nybHexString.substr((n >> 4) & 0x0F,1)) + nybHexString.substr(n & 0x0F,1);
  354. }
  355. function setColourGradient() {
  356.   center = 128;
  357.   width = 127;
  358.   steps = 6;
  359.   frequency = 2*Math.PI/steps;
  360.   return makeColorGradient(frequency,frequency,frequency,0,2,4,center,width,50);
  361. }
  362. function initialiseSpawnInterval() {
  363.   if (gameMode === gameModes.PLAYING && spawnTimer>2) {
  364.     spawnTimer--;
  365.     spawnTimeChangeInterval-=50;
  366.   }
  367. }
  368. function setGameMode(mode) {
  369.   gameMode = mode;
  370.   timer=0;
  371. }
  372. function raiseSnow() {
  373.   if (gameMode === gameModes.PLAYING && snowHeight ‹ canvas.height) {
  374.     snowHeight++;
  375.   }
  376. }
  377. function setHighScore() {
  378.   var currentHighScore = getHighScore();
  379.   if (currentHighScore !=-1 && score > currentHighScore) {
  380.     localStorage.setItem("highScore", score);
  381.   }
  382. }
  383. function getHighScore() {
  384.   if (!localStorage) return -1;
  385.   var highScore = localStorage.getItem("highScore");
  386.   return highScore || 0;
  387. }
  388. titleColours = setColourGradient();
  389. initialiseSnow();
  390. setInterval(draw, 30);
  391. setInterval(initialiseSpawnInterval, spawnTimeChangeInterval);
  392. setInterval(raiseSnow, 666);
复制代码
html代码
  1. ‹!DOCTYPE html>
  2. ‹html lang="en" >
  3. ‹head>
  4. ‹meta charset="UTF-8">
  5. ‹title>Elf Gift Catch‹/title>
  6. ‹link rel="stylesheet" href="css/style.css" rel="external nofollow" >#中间省略N个代码太长了
  7. ‹/head>
  8. ‹body>
  9. ‹div id="wrapper">
  10. ‹canvas id="canvas" width="450" height="540">‹/canvas>
  11. ‹/div>
  12.   
  13. ‹/div>
  14. ‹script  src="js/script.js">‹/script>
  15. ‹/body>
  16. ‹/html>
复制代码
演示流程
  打包的文件就三个,一个css的代码,一个JS的代码,还有一个html的文件,打包好之后,点击html的文件就能直接运行了呢。

  以上就是JavaScript实现一个简单的圣诞游戏的详细内容,更多关于JavaScript圣诞游戏的资料请关注脚本之家其它相关文章!


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|耀极客论坛 ( 粤ICP备2022052845号-2 )|网站地图

GMT+8, 2022-11-28 20:15 , Processed in 0.072725 second(s), 20 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表