抖音很火的召唤神龙的小游戏完整代码-召唤神龙

抖音很火的解压小游戏,完整代码分享。有兴趣的可以试着写一下。

 

1.  index

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">

  <title>召唤神龙</title>

  <!--http://www.html5rocks.com/en/mobile/mobifying/-->
  <meta name="viewport"
        content="width=device-width,user-scalable=no,initial-scale=1, minimum-scale=1,maximum-scale=1"/>

  <!--https://developer.apple.com/library/safari/documentation/AppleApplications/Reference/SafariHTMLRef/Articles/MetaTags.html-->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="format-detection" content="telephone=no">

  <!-- force webkit on 360 -->
  <meta name="renderer" content="webkit"/>
  <meta name="force-rendering" content="webkit"/>
  <!-- force edge on IE -->
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
  <meta name="msapplication-tap-highlight" content="no">

  <!-- force full screen on some browser -->
  <meta name="full-screen" content="yes"/>
  <meta name="x5-fullscreen" content="true"/>
  <meta name="360-fullscreen" content="true"/>
  
  <!-- force screen orientation on some browser -->
  <meta name="screen-orientation" content=""/>
  <meta name="x5-orientation" content="">

  <!--fix fireball/issues/3568 -->
  <!--<meta name="browsermode" content="application">-->
  <meta name="x5-page-mode" content="app">

  <!--<link rel="apple-touch-icon" href=".png" />-->
  <!--<link rel="apple-touch-icon-precomposed" href=".png" />-->
  
  
    <!-- <script>
        pushHistory();
        window.addEventListener("popstate", function(e) {

        }, false);
        function pushHistory() {
            var state = {
                title: "",
                url: window.location.href
            };
            window.history.pushState(state, state.title, state.url);
        }
    </script> -->

  <link rel="stylesheet" type="text/css" href="style-mobile.css"/>

</head>
<!-- <body style="margin: 0; background: #ddd;" align="center"> -->
  <div style="align:center;display: none"><img src="res/share.png" width="10%" /></div>
  
  <!-- <div id="canvasDiv" style="width:100%;height:100%;">
  </div>  -->
  <canvas id="GameCanvas" oncontextmenu="event.preventDefault()" tabindex="0" ></canvas>

  <video id="contentElement" style = "display:none;position: absolute;top:0px;left: 0px;">
            <!-- <source src="http://rmcdn.2mdn.net/Demo/vast_inspector/android.mp4"></source>
            <source src="http://rmcdn.2mdn.net/Demo/vast_inspector/android.webm"></source> -->
  </video> 
  <div id="block-Box" style="display:block;width:100%;height:100%;"></div>
  
  

 <div id="adContainer" style="display:none;position: absolute;top:0px;left: 0px;width:100%;height:100%;z-index:999;"></div> 
 <div id="loadingText"
 style="width:100%;display: none;text-align:center;position:absolute;top:45%;z-index:2;font-size:20px;color:#f99f0a">
 loading......0%
</div>
	
	 <div id="splash">
      <!-- <div class="progress-bar stripes"> -->
        <!-- <span style="width: 0%"></span> -->
      <!-- </div> -->
   </div>

   <div id="loadingImg" style="top:45%;width: 100%;position:absolute; ">
    <img src="res/loading.gif" width="7%" height="7%" />
  </div>
  
     <!-- 判断浏览器是否屏蔽广告 -->
  <script src="http://demo.jb51.net/js/2015/adview_pic_cpc_cpm_cpa_guanggao_gg_ads_300x250.js" type="text/javascript"></script> 
	<script type="text/javascript">
	
	 var killAdT = typeof(killads);
		// <!-- if (typeof(killads)=='undefined'){ -->
		// 	<!-- alert('广告被过滤'); -->
		// 	<!-- } -->
	</script>
   
  
  
  
<!--<div align="center" style="font-size: 10px;color: dimgrey">advertisement</div>-->

<script type="text/javascript" src="//imasdk.googleapis.com/js/sdkloader/ima3.js"></script>
<script type="text/javascript" src="ads.js"></script>

<script src="src/settings.js" charset="utf-8"></script>

<script type="text/javascript">

	var preloader;
    var adCompleteFlag = false;
    var resCompleteFlag = false;

    var adEndComplete = false;
    var resEndComplete = false;
	
	judgeLanTitle();
    function judgeLanTitle(){

//        console.log("window.navigator.language",window.navigator.language);

        if( window.navigator.language=="zh-CN" ||window.navigator.language=="zh-cn"){
            document.title = "召唤神龙";
        }else  if(window.navigator.language == "zh-TW" ){
            document.title = "召喚神龍";
        }else  if(window.navigator.language == "zh-HK" ){
            document.title = "召喚神龍";
        }else  if(window.navigator.language == "ko-KR"){
            document.title = "신용 소환";
        }else  if(window.navigator.language == "ja-JP"){
            document.title = "神竜を召喚する";
        }else  if(window.navigator.language == "th-TH"){
            document.title = "เรียกมังกร";
        }else{
            document.title = "Summon the Dragon";
        }
    }

    var loadintT = document.getElementById("loadingText");
    var loadintGif = document.getElementById("loadingImg")
    setTimeout(function () {
      loadintGif.remove();
      loadintT.style.display = ""
      updateLabView(0.1);
    }, 1 * 1000)

    window.timer = null;
    window.tempSeconds = 1;
    window.loadData = {};
    loadData.completedCount = 0;
    loadData.totalCount = 0;

  onload();
 function onload()  {
       var winHeight = document.documentElement.clientHeight;
       document.getElementById("canvasDiv").style.height = winHeight+"px";
  }; 
 window.onload =function() {
       document.getElementById("block-Box").style.display = "none";
 }

 function updateLabView(t) {
      if (timer != null) {
        clearInterval(timer);
      }
      timer = setInterval(function () {
        tempSeconds++;
        actualTotal();
        var loadintT = document.getElementById("loadingText")
        if(!loadintT){
          // clearInterval(timer);
          return;
        }

        loadintT.innerHTML = 'loading......' + parseInt(tempSeconds) + '%';

        switch (tempSeconds) {
          case 20:
            updateLabView(0.2);
            break;
          case 40:
            updateLabView(0.3);
            break;
          case 60:
            updateLabView(0.4);
            break;
          case 96:
            updateLabView(5);
            break;
          case 97:
            updateLabView(10);
            break;
          case 98:
            updateLabView(50);
            break;
          case 99:
            updateLabView(100);
            break;
          default:
            if (tempSeconds >= 80 && tempSeconds < 96) {
              updateLabView(t + 0.1);
            }
            break;
        }
        if (tempSeconds > 100) {
          clearInterval(timer);
          tempSeconds = 100
          loadintT.innerHTML = 'loading......' + parseInt(tempSeconds) + '%';
        }
      }, t * 1000);
    }

    function actualTotal() {
      var percent = parseInt(100 * loadData.completedCount / loadData.totalCount);
      if (percent > tempSeconds && loadData.totalCount > 1) {
        tempSeconds = percent;
      }
    }

    function finishLoad(){
      clearInterval(timer); 
      loadintT.innerHTML = 'loading......100' + '%';
      setTimeout(function(){
        loadintT.remove();
      },0.1 * 1000);
    }
</script>
  
  
  
  
  
<script src="src/settings.js" charset="utf-8"></script>

<script src="main.js" charset="utf-8"></script>


<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- 水工厂 -->
<!-- <ins class="adsbygoogle"
      style="position:absolute;border-top:5px #f0f0f1 solid;background:#f0f0f1;bottom:0px;z-index:1000;display:inline-block;min-width:320px;max-width:970px;width:100%;height:60px"
     data-ad-client="ca-pub-3932234672445376"
     data-ad-slot="1751302463"></ins>

<script>
      var ads = document.getElementsByClassName('adsbygoogle')[0];
      if (document.body.clientHeight > 700){
          ads.style.height = 80+'px';
      }else{
          ads.style.height = 60+'px';
      }
</script>

<script>
    function ShowBannerAD(){
      (adsbygoogle = window.adsbygoogle || []).push({});
    }
</script> -->
<!-- 果盘合合 -->
<script async
        data-ad-client="ca-pub-3932234672445376"
        data-ad-channel="1828757928"
		    data-ad-frequency-hint="15s"
        src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js">
</script>

<script>window.adsbygoogle = window.adsbygoogle || [];
const adBreak =  function(o) {adsbygoogle.push(o);}
</script>


<script type="text/javascript">

(function () {
    // open web debugger console
    if (typeof VConsole !== 'undefined') {
        window.vConsole = new VConsole();
    }

    var debug = window._CCSettings.debug;
    var splash = document.getElementById('splash');
    splash.style.display = 'block';

    function loadScript (moduleName, cb) {
      function scriptLoaded () {
          document.body.removeChild(domScript);
          domScript.removeEventListener('load', scriptLoaded, false);
          cb && cb();
      };
      var domScript = document.createElement('script');
      domScript.async = true;
      domScript.src = moduleName;
      domScript.addEventListener('load', scriptLoaded, false);
      document.body.appendChild(domScript);
    }

    loadScript(debug ? 'cocos2d-js.js' : 'cocos2d-js-min.js', function () {
      if (CC_PHYSICS_BUILTIN || CC_PHYSICS_CANNON) {
        loadScript(debug ? 'physics.js' : 'physics-min.js', window.boot);
      }
      else {
        window.boot();
      }
    });
})();


</script>
</body>
</html>

2. ads.js

var videoContent = document.getElementById('contentElement');

var adDisplayContainer =
    new google.ima.AdDisplayContainer(
        document.getElementById('adContainer'),
        videoContent);
// Must be done as the result of a user action on mobile
adDisplayContainer.initialize();

// Re-use this AdsLoader instance for the entire lifecycle of your page.
var adsLoader = new google.ima.AdsLoader(adDisplayContainer);

// Add event listeners
adsLoader.addEventListener(
    google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,
    onAdsManagerLoaded,
    false);
adsLoader.addEventListener(
    google.ima.AdErrorEvent.Type.AD_ERROR,
    onAdError,
    false);

function onAdError(adErrorEvent) {
	 console.log("adError");
	 
	 
	document.getElementById("adContainer").style.display = "none";
	 
	 
	 
	 
	     var GameConfig = __require("GameConfig");

          if(GameConfig.playNum == 0){

              adCompleteFlag = true;
            if(adCompleteFlag && resCompleteFlag){

                adCompleteFlag = false;

                var launchScene = GameConfig.launchScene;
                var Bros = GameConfig.Bros;
                var caS = GameConfig.caS;
                cc.director.loadScene(launchScene, null,
                    function () {
                        adCompleteFlag = false;
                        if (Bros) {
                            // show canvas
                            caS = '';
                            var div = document.getElementById('GameDiv');
                            if (div) {
                                 div.style.backgroundImage = '';
                            }
                        }
                        cc.loader.onProgress = null;
                        console.log('Success to load scene: ' + launchScene);
                    }

                );

              

                }

          }
	 
	 
	 
	   adEndComplete = true;
        if(adEndComplete && resEndComplete){
            adEndComplete = false;
            console.log("indexOverErr");
            var MainManger = __require("MainManage");
            MainManger.showGameEndLayer();
        }
	 
  // Handle the error logging and destroy the AdsManager
  console.log(adErrorEvent.getError());
  adsManager.destroy();
}

// An event listener to tell the SDK that our content video
// is completed so the SDK can play any post-roll ads.
var contentEndedListener = function() {adsLoader.contentComplete();};
videoContent.onended = contentEndedListener;

// Request video ads.
var preloader = new google.ima.AdsRequest();
preloader.adTagUrl = 'https://googleads.g.doubleclick.net/pagead/ads?ad_type=video_image&client=ca-games-pub-8708616103041212&description_url=http%3A%2F%2Fwww.vsane.com&videoad_start_delay=-1&hl=zh_CN&max_ad_duration=15000';
// Specify the linear and nonlinear slot sizes. This helps the SDK to
// select the correct creative if multiple are returned.
preloader.linearAdSlotWidth = 640;
preloader.linearAdSlotHeight = 400;
preloader.nonLinearAdSlotWidth = 640;
preloader.nonLinearAdSlotHeight = 400;


// showMyAds();

function showMyAds() {
	// alert("showMy");
		if (typeof(killads)=='undefined'){
			// alert('广告被过滤');
			console.log("AdNo");
			 adEndComplete = false;
			var MainManger = __require("MainManage");
            MainManger.showGameEndLayer();
		}else{
            var winHeight = document.documentElement.clientHeight;

            if (document.body.clientHeight > 700){
                document.getElementById("adContainer").style.height = winHeight-85+"px";
            }else{
                document.getElementById("adContainer").style.height = winHeight-65+"px";
            }
            // document.getElementById("adContainer").style.height = winHeight-60+"px";
         
            document.getElementById("adContainer").style.display = "block";
            adsLoader.requestAds(preloader);
		}
}


function onAdsManagerLoaded(adsManagerLoadedEvent) {
	console.log("ADLoad");
	
	  adCompleteFlag = true;
	
	 // document.getElementById("adContainer").style.display = "block";
  // Get the ads manager.
  adsManager = adsManagerLoadedEvent.getAdsManager(
      videoContent);  // See API reference for contentPlayback

  // Add listeners to the required events.
  adsManager.addEventListener(
      google.ima.AdErrorEvent.Type.AD_ERROR,
      onAdError);
  adsManager.addEventListener(
      google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED,
      onContentPauseRequested);
  adsManager.addEventListener(
      google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,
      onContentResumeRequested);

var o = document.getElementById("adContainer");
var h = o.offsetHeight; //高度
var w = o.offsetWidth; //宽度
  try {
    // Initialize the ads manager. Ad rules playlist will start at this time.
    adsManager.init(w, h, google.ima.ViewMode.FULLSCREEN);
    // Call start to show ads. Single video and overlay ads will
    // start at this time; this call will be ignored for ad rules, as ad rules
    // ads start when the adsManager is initialized.
    adsManager.start();
  } catch (adError) {
	 
    // An error may be thrown if there was a problem with the VAST response.
    // Play content here, because we won't be getting an ad.
    // videoContent.play();
  }
}

function onContentPauseRequested() {
	
	
  // This function is where you should setup UI for showing ads (e.g.
  // display ad timer countdown, disable seeking, etc.)
  videoContent.removeEventListener('ended', contentEndedListener);
  videoContent.pause();
  
}

//广告结束的时候调用的函数
function onContentResumeRequested() {
	console.log("ADLoadComplete",resEndComplete);
	
	
	
	 var GameConfig = __require("GameConfig");
        console.log("IndexMainManger",GameConfig.launchScene, GameConfig.Bros,GameConfig.caS);

        if(GameConfig.playNum == 1){
            adCompleteFlag = true;
            if(adCompleteFlag && resCompleteFlag){

                var launchScene = GameConfig.launchScene;
                var Bros = GameConfig.Bros;
                var caS = GameConfig.caS;
                cc.director.loadScene(launchScene, null,
                    function () {
						
						
                        adCompleteFlag = false;
						
						
						
                        if (Bros) {
                            // show canvas
                            var canvas = document.getElementById('GameCanvas');
							canvas.style.visibility = '';
                            var div = document.getElementById('GameDiv');
                            if (div) {
                                 div.style.backgroundImage = '';
                            }
                        }
                        cc.loader.onProgress = null;
                        console.log('Success to load scene1: ' + launchScene);
						
						
						
						
						
                    }
                );
				

            }
           

        }
		
		
		
	
	
	
	 adEndComplete = true;
        if(adEndComplete && resEndComplete){
            adEndComplete = false;
            console.log("indexOverErr");
            var MainManger = __require("MainManage");
            MainManger.showGameEndLayer();
        }
	
  // This function is where you should ensure that your UI is ready
  // to play content.
  document.getElementById("adContainer").style.display = "none";
  

  // videoContent.addEventListener('ended', contentEndedListener);
  // videoContent.play();
  
}

function noAdGoToScene(){
	
	
		 var GameConfig = __require("GameConfig");
        console.log("IndexMainMangerMaing",GameConfig.launchScene, GameConfig.Bros,GameConfig.caS);
		
				var launchScene = GameConfig.launchScene;
				var Bros = GameConfig.Bros;
                var caS = GameConfig.caS;
                cc.director.loadScene(launchScene, null,
                    function () {
						
                    adCompleteFlag = false;
						
                        if (Bros) {
                            // show canvas
                            var canvas = document.getElementById('GameCanvas');
							canvas.style.visibility = '';
                            var div = document.getElementById('GameDiv');
                            if (div) {
                                 div.style.backgroundImage = '';
                            }
                        }
                        cc.loader.onProgress = null;
                        console.log('Success to load scene1Main: ' + launchScene);
						
						
						
						
						
                    }
                );
	
	
}



3.mian.js

var loadingNum = 0;
window.boot = function () {
    var settings = window._CCSettings;
    window._CCSettings = undefined;
    var onProgress = null;
    
    var RESOURCES = cc.AssetManager.BuiltinBundleName.RESOURCES;
    var INTERNAL = cc.AssetManager.BuiltinBundleName.INTERNAL;
    var MAIN = cc.AssetManager.BuiltinBundleName.MAIN;


    function setLoadingDisplay () {
        // Loading splash scene
        var splash = document.getElementById('splash');
        var loadintT = document.getElementById("loadingText")
        // var progressBar = splash.querySelector('.progress-bar span');
        cc.loader.onProgress = function (finish, total, item) {
            loadData.completedCount = finish;
            loadData.totalCount = total;
			
			var percent = 100 * finish / total;
			if(loadingNum >= 1 && total > 1){
				if(percent.toFixed(0) >= 100){
                    loadintT.innerHTML = 'loading......100' + '%';
                    clearInterval(timer); 
                    setTimeout(function(){
                        loadintT.remove();
                    },0.1 * 1000);
				}
			}
            loadingNum++;
        };
        splash.style.display = 'block';
        // progressBar.style.width = '0%';

        cc.director.once(cc.Director.EVENT_AFTER_SCENE_LAUNCH, function () {
            splash.style.display = 'none';
        });
    }

    var onStart = function () {

        cc.view.enableRetina(true);
        cc.view.resizeWithBrowserSize(true);

        if (cc.sys.isBrowser) {
            setLoadingDisplay();
        }

        if (cc.sys.isMobile) {
            if (settings.orientation === 'landscape') {
                cc.view.setOrientation(cc.macro.ORIENTATION_LANDSCAPE);
            }
            else if (settings.orientation === 'portrait') {
                cc.view.setOrientation(cc.macro.ORIENTATION_PORTRAIT);
            }
            // cc.view.enableAutoFullScreen([
            //     cc.sys.BROWSER_TYPE_BAIDU,
            //     cc.sys.BROWSER_TYPE_BAIDU_APP,
            //     cc.sys.BROWSER_TYPE_WECHAT,
            //     cc.sys.BROWSER_TYPE_MOBILE_QQ,
            //     cc.sys.BROWSER_TYPE_MIUI,
            //     cc.sys.BROWSER_TYPE_HUAWEI,
            //     cc.sys.BROWSER_TYPE_UC,
            // ].indexOf(cc.sys.browserType) < 0);
            cc.view.enableAutoFullScreen(false);
        }

        // Limit downloading max concurrent task to 2,
        // more tasks simultaneously may cause performance draw back on some android system / browsers.
        // You can adjust the number based on your own test result, you have to set it before any loading process to take effect.
        if (cc.sys.isBrowser && cc.sys.os === cc.sys.OS_ANDROID) {
            cc.assetManager.downloader.maxConcurrency = 2;
            cc.assetManager.downloader.maxRequestsPerFrame = 2;
        }

        var launchScene = settings.launchScene;
        var bundle = cc.assetManager.bundles.find(function (b) {
            return b.getSceneInfo(launchScene);
        });
        var canvas;
        if (cc.sys.isBrowser) {
            canvas = document.getElementById('GameCanvas');
        }
        
        var MainManger = __require("MainManage");
        MainManger.init(launchScene,cc.sys.isBrowser,canvas.style.visibility);
        // bundle.loadScene(launchScene, null, onProgress,
        //     function (err, scene) {
        //         if (!err) {
        //             cc.director.runSceneImmediate(scene);
        //             if (cc.sys.isBrowser) {
        //                 // show canvas
        //                 var canvas = document.getElementById('GameCanvas');
        //                 canvas.style.visibility = '';
        //                 var div = document.getElementById('GameDiv');
        //                 if (div) {
        //                     div.style.backgroundImage = '';
        //                 }
        //                 console.log('Success to load scene: ' + launchScene);
        //             }
        //         }
        //     }
        // );
    };

    var option = {
        id: 'GameCanvas',
        debugMode: settings.debug ? cc.debug.DebugMode.INFO : cc.debug.DebugMode.ERROR,
        showFPS: settings.debug,
        frameRate: 60,
        groupList: settings.groupList,
        collisionMatrix: settings.collisionMatrix,
    };

    cc.assetManager.init({ 
        bundleVers: settings.bundleVers,
        remoteBundles: settings.remoteBundles,
        server: settings.server
    });
    
    var bundleRoot = [INTERNAL];
    settings.hasResourcesBundle && bundleRoot.push(RESOURCES);

    var count = 0;
    function cb (err) {
        if (err) return console.error(err.message, err.stack);
        count++;
        if (count === bundleRoot.length + 1) {
            cc.assetManager.loadBundle(MAIN, function (err) {
                if (!err) cc.game.run(option, onStart);
            });
        }
    }

    cc.assetManager.loadScript(settings.jsList.map(function (x) { return 'src/' + x;}), cb);

    for (var i = 0; i < bundleRoot.length; i++) {
        cc.assetManager.loadBundle(bundleRoot[i], cb);
    }
};

if (window.jsb) {
    var isRuntime = (typeof loadRuntime === 'function');
    if (isRuntime) {
        require('src/settings.js');
        require('src/cocos2d-runtime.js');
        if (CC_PHYSICS_BUILTIN || CC_PHYSICS_CANNON) {
            require('src/physics.js');
        }
        require('jsb-adapter/engine/index.js');
    }
    else {
        require('src/settings.js');
        require('src/cocos2d-jsb.js');
        if (CC_PHYSICS_BUILTIN || CC_PHYSICS_CANNON) {
            require('src/physics.js');
        }
        require('jsb-adapter/jsb-engine.js');
    }

    cc.macro.CLEANUP_IMAGE_CACHE = true;
    window.boot();
}

 

  • 9
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
### 回答1: 召唤神龙是一款经典的小游戏,可以使用JavaScript来实现。以下是一种简单的实现方式。 首先,我们需要在HTML文件中创建一个画布(canvas)用来显示游戏界面。这可以通过在body元素中添加一个canvas标签来实现。 ```html <canvas id="gameCanvas" width="800" height="600"></canvas> ``` 接下来,在JavaScript文件中,我们需要获取这个canvas元素并保存到一个变量中。 ```javascript var canvas = document.getElementById("gameCanvas"); var ctx = canvas.getContext("2d"); ``` 然后,我们可以定义一些游戏所需的变量,比如神龙的位置、大小、速度等。 ```javascript var dragonX = canvas.width / 2; var dragonY = canvas.height - 100; var dragonSize = 80; var dragonSpeed = 5; ``` 接着,我们需要编写一些函数来处理游戏的逻辑。比如,我们可以编写一个函数来绘制神龙。 ```javascript function drawDragon() { ctx.beginPath(); ctx.arc(dragonX, dragonY, dragonSize, 0, Math.PI * 2); ctx.fillStyle = "green"; ctx.fill(); ctx.closePath(); } ``` 还可以编写一个函数来更新神龙的位置。 ```javascript function updateDragon() { if (ArrowLeft键按下) { dragonX -= dragonSpeed; } if (ArrowRight键按下) { dragonX += dragonSpeed; } if (ArrowUp键按下) { dragonY -= dragonSpeed; } if (ArrowDown键按下) { dragonY += dragonSpeed; } } ``` 最后,在主循环中调用这些函数。 ```javascript function main() { ctx.clearRect(0, 0, canvas.width, canvas.height); drawDragon(); updateDragon(); requestAnimationFrame(main); } main(); ``` 这只是一个简单的召唤神龙小游戏的实现方式。你可以根据自己的需求添加更多的功能,比如添加障碍物、得分系统等。 ### 回答2: 召唤神龙小游戏是一款基于JavaScript开发的互动游戏,它依据热门日本动画《龙珠》中的情节设计而成。以下是一个使用JavaScript实现召唤神龙小游戏的简单示例: ```javascript <!DOCTYPE html> <html> <body> <button onclick="summonDragon()">召唤神龙</button> <script> function summonDragon() { var randomNum = Math.floor(Math.random() * 7) + 1; // 生成一个1-7之间的随机数 var dragon = ""; switch(randomNum) { case 1: dragon = "神龙:满足你一个愿望"; break; case 2: dragon = "神龙:给你1000年寿命"; break; case 3: dragon = "神龙:让你变成超级赛亚人"; break; case 4: dragon = "神龙:帮你找到七龙珠"; break; case 5: dragon = "神龙:让你获得无限力量"; break; case 6: dragon = "神龙:解散你的死党"; break; case 7: dragon = "神龙:让你在下次召唤时无法实现愿望"; break; default: dragon = "神龙:满足你一个愿望"; break; } alert(dragon); } </script> </body> </html> ``` 在这个小游戏中,当用户点击"召唤神龙"按钮时,利用JavaScript的Math.random()函数生成一个1到7之间的随机数,并用switch语句根据不同的随机数生成不同的神龙愿望。最后,通过alert()弹窗将神龙的愿望展示给用户。用户每次点击按钮,都会获得不同的神龙愿望,增加了游戏的趣味性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值