게임 플레이 기능 구현
요구 사항:
- JavaScript 루프 및 조건문에 대한 숙련도.
- JavaScript 를 사용하여 DOM 을 조작하는 방법.
기능:
- 핵심 게임 역학을 구현합니다.
- 게임 오버 시나리오를 설계합니다.
- 블록 생성 및 이동 메커니즘을 구현합니다.
단계:
- 플레이어가 검은색 블록 또는 흰색 블록을 클릭했는지 확인합니다. 플레이어의 클릭에 따라 게임 상태를 업데이트합니다.
// Determine whether to click on a black or white block
function judge(ev) {
if (
ev.target.className.indexOf("black") == -1 &&
ev.target.className.indexOf("cell") !== -1
) {
ev.target.parentNode.pass1 = 1; // Defines the pass attribute, which indicates that the white block of this row has been clicked
}
if (ev.target.className.indexOf("black") !== -1) {
// Clicking a target with black in the class name is a black block
ev.target.className = "cell";
ev.target.parentNode.pass = 1; // Defines the pass attribute, indicating the black block in this row was clicked
score();
}
}
- 플레이어 상호 작용을 기반으로 게임이 종료되는 시점을 결정합니다. 게임이 종료되면 게임 종료 작업을 트리거합니다.
// Check if the game is over
function over() {
var rows = con.childNodes;
if (rows.length == 5 && rows[rows.length - 1].pass !== 1) {
fail();
}
for (let i = 0; i < rows.length; i++) {
if (rows[i].pass1 == 1) {
fail();
}
}
}
// Game Over
function fail() {
clearInterval(clock);
flag = false;
confirm("The final score is " + parseInt($("score").innerHTML));
var con = $("con");
con.innerHTML = "";
$("score").innerHTML = 0;
con.style.top = "-408px";
}
- 게임 플레이를 위해 블록 행을 생성합니다. 다른 블록들 중에서 "black" 블록을 무작위로 배치합니다.
// Create a <div class="row"> with four children <div class="cell">
function createrow() {
var con = $("con");
var row = creatediv("row"); // Create div: className=row
var arr = createcell(); // Define the class name of the div cell, one of which is cell black
con.appendChild(row); // Add child node with row as con
for (var i = 0; i < 4; i++) {
row.appendChild(creatediv(arr[i])); // Add child nodes of row cell
}
if (con.firstChild == null) {
con.appendChild(row);
} else {
con.insertBefore(row, con.firstChild);
}
}
// Create an array of class names; one of them is "cell black", others are "cell"
function createcell() {
var temp = ["cell", "cell", "cell", "cell"];
var i = Math.floor(Math.random() * 4); // Randomly generate the position of the black block Math.random() function parameters 0~1 random number
temp[i] = "cell black";
return temp;
}
- 블록이 지속적으로 아래로 이동하도록 합니다. 화면에서 벗어나는 오래된 행을 삭제합니다.
// Move the black blocks down
function move() {
var con = $("con");
var top = parseInt(window.getComputedStyle(con, null)["top"]);
if (speed + top > 0) {
top = 0;
} else {
top += speed;
}
con.style.top = top + "px"; // Keep moving the top value so it moves
over();
if (top == 0) {
createrow();
con.style.top = "-102px";
delrow();
}
}
// Delete a row
function delrow() {
var con = $("con");
if (con.childNodes.length == 6) {
con.removeChild(con.lastChild);
}
}