QML 고급 튜토리얼 2 - 게임 캔버스에 요소 채우기
JavaScript를 사용하여 블록 생성하기
이제 몇 가지 타입을 정의했으니, 게임을 작성해 보겠습니다.
첫 번째 작업은 게임 블록을 생성하는 것입니다. ‘New Game’ 버튼을 클릭할 때마다 게임 캔버스에 무작위로 선택된 새로운 블록 세트가 채워집니다. 새로운 게임이 시작될 때마다 동적으로 새로운 블록을 생성해야 하므로, Repeater 를 사용하여 블록을 정의할 수는 없습니다. 대신 자바스크립트로 블록을 생성할 것입니다.
다음은 새로운 파일인 ` samegame.js`에 포함된 블록 생성용 자바스크립트 코드입니다. 코드에 대한 설명은 아래에 나와 있습니다.
var blockSize = 40;
var maxColumn = 10;
var maxRow = 15;
var maxIndex = maxColumn * maxRow;
var board = new Array(maxIndex);
var component;
//Index function used instead of a 2D array
function index(column, row) {
return column + (row * maxColumn);
}
function startNewGame() {
//Delete blocks from previous game
for (var i = 0; i < maxIndex; i++) {
if (board[i] != null)
board[i].destroy();
}
//Calculate board size
maxColumn = Math.floor(background.width / blockSize);
maxRow = Math.floor(background.height / blockSize);
maxIndex = maxRow * maxColumn;
//Initialize Board
board = new Array(maxIndex);
for (var column = 0; column < maxColumn; column++) {
for (var row = 0; row < maxRow; row++) {
board[index(column, row)] = null;
createBlock(column, row);
}
}
}
function createBlock(column, row) {
if (component == null)
component = Qt.createComponent("Block.qml");
// Note that if Block.qml was not a local file, component.status would be
// Loading and we should wait for the component's statusChanged() signal to
// know when the file is downloaded and ready before calling createObject().
if (component.status == Component.Ready) {
var dynamicObject = component.createObject(background);
if (dynamicObject == null) {
console.log("error creating block");
console.log(component.errorString());
return false;
}
dynamicObject.x = column * blockSize;
dynamicObject.y = row * blockSize;
dynamicObject.width = blockSize;
dynamicObject.height = blockSize;
board[index(column, row)] = dynamicObject;
} else {
console.log("error loading block component");
console.log(component.errorString());
return false;
}
return true;
}startNewGame() 함수는 이전 게임에서 생성된 블록을 삭제하고, 새로운 게임의 게임 창을 채우는 데 필요한 블록의 행과 열 수를 계산합니다. 그런 다음 모든 게임 블록을 저장할 배열을 생성하고, createBlock() 함수를 호출하여 게임 창을 채울 만큼의 블록을 생성합니다.
createBlock() 함수는 Block.qml 파일에서 블록을 생성하고, 새로운 블록을 게임 캔버스상의 해당 위치로 이동시킵니다. 이 과정은 다음과 같은 여러 단계를 거칩니다:
- Qt.createComponent
Block.qml에서 타입을 생성하기 위해 ()가 호출됩니다. 컴포넌트가 준비되었다면, 를 호출하여 항목의 인스턴스를 생성할 수 있습니다.createObject()Block createObject()가 null을 반환한 경우(즉, 객체를 불러오는 동안 오류가 발생한 경우), 오류 정보를 출력합니다.- 블록을 보드상의 지정된 위치에 배치하고 너비와 높이를 설정합니다. 또한, 나중에 참조할 수 있도록 블록 배열에 저장합니다.
- 마지막으로, 어떤 이유로든 컴포넌트를 불러올 수 없는 경우(예: 파일이 없는 경우) 콘솔에 오류 정보를 출력합니다.
JavaScript 컴포넌트를 QML에 연결하기
이제 QML 파일에서 samegame.js 에 있는 JavaScript 코드를 호출해야 합니다. 이를 위해 samegame.qml 파일에 다음 줄을 추가하여 JavaScript 파일을 모듈로 임포트합니다:
import "samegame.js" as SameGame이렇게 하면 "SameGame"을 접두사로 사용하여 samegame.js 내의 모든 함수를 참조할 수 있습니다. 예를 들어, SameGame.startNewGame() 또는 SameGame.createBlock() 과 같이 사용할 수 있습니다. 즉, 이제 'New Game' 버튼의 onClicked 핸들러를 다음과 같이 startNewGame() 함수에 연결할 수 있습니다:
Button {
anchors { left: parent.left; verticalCenter: parent.verticalCenter }
text: "New Game"
onClicked: SameGame.startNewGame()
}따라서 'New Game' 버튼을 클릭하면 startNewGame() 가 호출되어 다음과 같이 블록 필드가 생성됩니다:

이제 블록으로 구성된 화면이 완성되었으므로, 게임 메커니즘을 추가하기 시작할 수 있습니다.
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.