按空格键时加载脚本

时间:2017-03-14 23:15:57

标签: javascript html

var s;
var scl = 20;
var food;
var audio = new Audio("background.mp3");
var audioDeath = new Audio("death.wav");
var audioEat = new Audio("ding.wav");
var img = new Image("imagine.png");

function setup() {
  audio.volume = 0.1;
  createCanvas(500, 500);
  frameRate(10);
  input(start);
}

function start() {
  audio.play();
  s = new Snake();
  pickLocation();

}

function pickLocation() {
  var cols = floor(width / scl);
  var rows = floor(height / scl);
  food = createVector(floor(random(cols)), floor(random(rows)));
  food.mult(scl);
}

function draw() {
  background('black');
  if (s.eat(food)) {
    audioEat.pause();
    audioEat.currentTime = 0;
    audioEat.play();
    pickLocation();
    if ((food.x == s.x && food.y == s.y) || (s.tail.indexOf(food) > -1)) {
      pickLocation();
    }

  }
  if (s.death() == true) {
    audio.pause();
    audio.currentTime = 0;
    audioDeath.volume = 0.5;
    audioDeath.play();
    start();
  }
  s.update();
  s.show();



  fill(255, 0, 100);
  rect(food.x, food.y, scl, scl);
}

function keyPressed() {
  if (keyCode === UP_ARROW && s.yspeed != 1) {
    s.dir(0, -1);
  } else if (keyCode === DOWN_ARROW && s.yspeed != -1) {
    s.dir(0, 1);
  } else if (keyCode === RIGHT_ARROW && s.xspeed != -1) {
    s.dir(1, 0);
  } else if (keyCode === LEFT_ARROW && s.xspeed != 1) {
    s.dir(-1, 0);
  }
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title> SNAKE GAME</title>
  <script src="libraries/p5.js" type="text/javascript"></script>
  <script src="libraries/p5.dom.js" type="text/javascript"></script>
  <script src="libraries/p5.sound.js" type="text/javascript"></script>
  <script src="sketch.js" type="text/javascript"></script>
  <script src="snake.js" type="text/javascript"></script>
</head>

<body>
  <img src="imagine.png"></img>
</body>

</html>

所以基本上我今天想尝试使用Javascript,并且在一些教程的帮助下设法编写游戏Snake。我唯一的问题是脚本在页面加载后立即运行,我希望它只在用户按空格键后运行。我一直在网上看几个小时,但仍然无法做到。

1 个答案:

答案 0 :(得分:0)

您可以像这样添加一个事件监听器

&#13;
&#13;
var main = document.getElementsByClassName("main")[0];
window.addEventListener("keypress", doSomething, false);

function doSomething(e) {
  if (e.keyCode === 32)
    main.style.background = "red";
  
}
&#13;
.main {
  height: 100vh;
  width: 100vw;
  background: pink;
}
&#13;
<div class="main">
Press Space
</div>
&#13;
&#13;
&#13;