game.js - 01. set
- 建立陣列:
let array = [1, 2, 3];
- 建立空陣列:
let array = [];
- 建立長度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
- 將物件放入陣列
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
- 陣列長度:
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
- 播放音檔的簡單語法
function makeSound(colour) {
var audio = new Audio("sounds/" + colour + ".mp3");
audio.play()
}