如何添加游戏菜单

我正在尝试添加带有“开始”的通用游戏菜单来启动游戏。我该怎么做呢?这是代码:

#hero {

  /* background: #ff0000; */

  background-image: url("man-of-space.png");

  width: 40px;

  height: 40px;

  position: absolute;

}


#background {

  background-image: url("space.png");

  /* background: #000000; */

  width: 500px;

  height: 500px;

  position: absolute;

  left: 0px;

  top: 0px;

}


.laser {

  background: #00ff00;

  width: 2px;

  height: 50px;

  position: absolute;

}


.enemy {

  background-image: url("spaceship.png");

  background-size: 40px 40px;

  width: 40px;

  height: 40px;

  position: absolute;

}


#score {

  color: #ffffff;

  font-size: 18pt;

  position: absolute;

  left: 20px;

  top: 20px;

}


#gameover {

  color: #ff0000;

  font-size: 20px;

  position: absolute;

  left: 160px;

  top: 200px;

  visibility: hidden;

}

<div id="background"></div>

<div id="hero"></div>

<div class="laser" id="laser0"></div>

<div class="laser" id="laser1"></div>

<div class="laser" id="laser2"></div>

<div id="score"></div>

<div id="gameover">GAME OVER</div>



繁花不似锦
浏览 107回答 2
2回答

皈依舞

您可以将游戏 UI 包装在一个<div id="game" style="display: none;">元素中,以便在加载页面时它将隐藏。然后将开始菜单包装在一个<div id="startMenu">带有 a 的元素中,该元素<button id="startButton">Start</button>将用于隐藏开始菜单并显示游戏 UI。在 JS 代码中,您可以将游戏包装在一个函数中,以便在您调用它时启动它。HTML:&nbsp; &nbsp; <div id="startMenu">&nbsp; &nbsp; &nbsp; &nbsp; <button id="startButton">Start</button>&nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; <div id="game" style="display: none;">&nbsp; &nbsp; &nbsp; &nbsp; <div id="background"></div>&nbsp; &nbsp; &nbsp; &nbsp; <div id="hero"></div>&nbsp; &nbsp; &nbsp; &nbsp; <div class="laser" id="laser0"></div>&nbsp; &nbsp; &nbsp; &nbsp; <div class="laser" id="laser1"></div>&nbsp; &nbsp; &nbsp; &nbsp; <div class="laser" id="laser2"></div>&nbsp; &nbsp; &nbsp; &nbsp; <div id="score"></div>&nbsp; &nbsp; &nbsp; &nbsp; <div id="gameover">GAME OVER</div>&nbsp; &nbsp; </div>JS:function startGame() {&nbsp; &nbsp; var LEFT_KEY = 37;&nbsp; &nbsp; var UP_KEY = 38;&nbsp; &nbsp; var RIGHT_KEY = 39;&nbsp; &nbsp; var DOWN_KEY = 40;&nbsp; &nbsp; var SPACE_KEY = 32;&nbsp; &nbsp; var HERO_MOVEMENT = 3;&nbsp;&nbsp; &nbsp; [...Your game code...]&nbsp; &nbsp; loop();}document.getElementById('startButton').onclick = function() {&nbsp; &nbsp; document.getElementById('startMenu').style.display = "none";&nbsp; &nbsp; document.getElementById('game').style.display = "";&nbsp; &nbsp; startGame();};<div id="startMenu">现在您有了一个可以根据需要自定义的开始菜单 ( ),以及<div id="game">仅在按下开始按钮后才会显示的游戏 UI ( )。

慕少森

我的建议是添加更多 HTML。也许制作一个div包含您需要的所有开始屏幕元素的项目。当启动函数发生时,将该 div 的 innerHTML 设置为"".例子:document.getElementById('yourDivIdHere').innerHTML&nbsp;=&nbsp;'';
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript