JS Project - Simon Game


Posted by pei_______ on 2022-05-31

game.js - 01. set

  1. 建立陣列: let array = [1, 2, 3];
  2. 建立空陣列: let array = [];
  3. 建立長度n的陣列: let arr2 = new Array(n);
let buttonColours = ["red", "blue", "green", "yellow"];

let gamePattern = [];
let userClickedPattern = [];

var isStart = false;
var level = 0;

game.js - 02. listen to keyboard (start)

$(document).keypress(function() {
  if (!isStart) {
    nextSequence();
    isStart = true;
  }
})

game.js - 03. listen to mouse

  1. 將物件放入陣列array.put(item)
$(".btn").click(function() {
  var userChosenColour = this.id;
  userClickedPattern.push(userChosenColour);

  makeSound(userChosenColour);
  animatePress(userChosenColour);

  checkAnswer(level);
})

game.js - 04. check Answer function

  1. 陣列長度: array.length
function checkAnswer(currentLevel) {
  var lenOfUserClickPattern = userClickedPattern.length;

  var rightAnswer = gamePattern[lenOfUserClickPattern - 1]
  var userAnswer = userClickedPattern[lenOfUserClickPattern - 1]

  if (rightAnswer != userAnswer) {

    makeSound("wrong");
    $("h1").text("Game Over, Press Any Key to Restart")
    $("body").addClass("game-over");

    setTimeout(function() {
      $("body").removeClass("game-over");
    }, 200);

    startOver();
    isStart = false;
  }

  if (isStart == true && lenOfUserClickPattern == currentLevel) {

    setTimeout(function() {
      nextSequence();
    }, 1000);
  }

}

game.js - 05. next Sequence function

1.連續效果: $("h1").fadeOut(100).fadeIn(100);

function nextSequence() {
  userClickedPattern = [];
  level ++;
  $("h1").text("Level " + level);

  var randomNumber = Math.floor(Math.random() * 4);
  var randomChosenColour = buttonColours[randomNumber];
  gamePattern.push(randomChosenColour);

  $("#" + randomChosenColour).fadeOut(100).fadeIn(100);
  makeSound(randomChosenColour);
}

game.js - 06. animate Press function

function animatePress(currentColour) {
  $("#" + currentColour).addClass("pressed");
  setTimeout(function() {
    $("#" + currentColour).removeClass("pressed");
  }, 100);
}

game.js - 07. startOver function

function startOver() {
  level = 0;
  gamePattern = [];
}

game.js - 08. make Sound function

  1. 播放音檔的簡單語法
function makeSound(colour) {
  var audio = new Audio("sounds/" + colour + ".mp3");
  audio.play()
}

#javascript #jquery #web系列







Related Posts

[day-2] JS 環境建立流程/賦值運算子/字串型別

[day-2] JS 環境建立流程/賦值運算子/字串型別

【JS基礎】字串處理

【JS基礎】字串處理

[面試]帆擎/和盛/叡揚/達暉/凱發

[面試]帆擎/和盛/叡揚/達暉/凱發


Comments