nexacroAPI

nexacroAPI 정적 메소드 소개

자바스크립트에서 제공하는 메소드를 확장하거나 앱 구현을 위해 필요한 기능을 정적 메소드 형태로 제공합니다. 정적 메소드이므로 생성이나 선언 없이 바로 사용할 수 있습니다.

간단한 틱택토(Tic-Tac-Toe) 게임 만들기

setTimeout 메서드를 사용해 컴퓨터와 같이 게임을 하는 분위기를 만듭니다.

예제

가로, 세로, 대각선 중 한 줄이 완성되면 이기는 게임입니다. 각 칸을 클릭하면 플레이어가 선택한 영역이 "X"로 표시되고, 일정 시간 후에 컴퓨터가 선택한 영역이 "O"로 표시됩니다.

sample_nexacro_01.xfdl

예제에서 사용한 핵심 기능

setTimeout

지정된 시간 후에 설정한 함수를 실행하는 메서드입니다. 타이머와 달리 한 번만 실행됩니다.

예제 구현 방법

1

Div 컴포넌트를 화면에 배치합니다.

2

Div 컴포넌트 Layout 오브젝트의 type 속성값을 "table"로 설정합니다.

3

Div 컴포넌트 편집 모드에서 3x3 형태로 테이블 영역을 변경합니다.

4

Div 컴포넌트 내 각 테이블 셀에 Static 컴포넌트를 배치합니다.

Static 컴포넌트의 id는 순서대로 "Static00"부터 "Static08"까지 지정합니다.

5

TextArea 컴포넌트와 Button 컴포넌트를 배치합니다.

TextArea 컴포넌트는 진행 상황에 대한 안내를 제공하며, Button 컴포넌트는 초기화를 위해 사용합니다.

6

Div 컴포넌트와 각 Static 컴포넌트의 border 속성값을 "1px solid black"으로 설정합니다.

7

각 Static 컴포넌트의 onclick 이벤트 핸들러 함수를 아래와 같이 작성합니다.

모든 Static 컴포넌트의 onclick 이벤트 핸들러 함수는 같은 함수를 사용합니다.

this.Static_onclick = function(obj:nexacro.Static,e:nexacro.ClickEventInfo)
{
	this.handlePlayerMove(e.fromobject);
};

handlePlayerMove 함수에서는 사용자가 선택한 셀 위치 정보를 Static 컴포넌트의 id를 통해 확인하고 해당 위치의 Static 컴포넌트의 text 속성값을 변경합니다. 매번 실행 시마다 승패 여부를 확인하고, 아직 게임이 진행 중이라면 setTimeout 메서드를 사용해 컴퓨터에게 순서를 넘깁니다.

checkWinner 함수에서는 틱택토(Tic-Tac-Toe)의 게임 규칙에 따라 승패 여부를 확인합니다. 한쪽이 이긴 경우에는 해당 셀 배경색을 노란색으로 변경합니다.

this.handlePlayerMove = function (targetObj) {
	let index = Number((targetObj.id).substring(7));
	if (!isPlayerTurn || board[index] || gameOver) return;
	
	board[index] = player;
	targetObj.text = player;

	const result = this.checkWinner(player, "Player");
	if (result.winner) {
		return;
	}
	if (result.isDraw) {
		return;
	}
	this.TextArea00.insertText("It's the computer's turn. Thinking about"+"\n");
	isPlayerTurn = false;
	nexacro.setTimeout(this, this.computerMove, 2000);
}

this.checkWinner = function(symbol, messageTarget) {
	const winPatterns = [
		[0,1,2],[3,4,5],[6,7,8],
		[0,3,6],[1,4,7],[2,5,8],
		[0,4,8],[2,4,6]
	];
	for (let pattern of winPatterns) {
		if (pattern.every(function(idx) {
			return board[idx] === symbol;
		})) {
			for(let index of pattern) {
				this.Div00.form.components["Static0"+index].background = "yellow";
			}
			this.TextArea00.insertText(messageTarget + " wins!\n");
			gameOver = true;
			return { winner: symbol, pattern: pattern, isDraw: false };
		}
	}
    if (!board.includes(null)) {
        this.TextArea00.insertText("Tie!\n");
        gameOver = true;
        return { winner: null, pattern: null, isDraw: true };
    }
    return { winner: null, pattern: null, isDraw: false };
}

computerMove 함수에서는 채워지지 않은 셀을 확인하고 그 중 하나를 랜덤하게 선택합니다.

this.computerMove = function () {
	if (gameOver) return;
	
	const emptyIndices = board.map((cell, idx) => cell ? null : idx).filter(idx => idx !== null);
	if (emptyIndices.length === 0) return;
	const randomIndex = emptyIndices[Math.floor(Math.random() * emptyIndices.length)];
	board[randomIndex] = computer;
	
	this.Div00.form.components["Static0"+randomIndex].text = computer;
	this.TextArea00.insertText("The index specified by the computer: "+randomIndex+"\n");

	const result = this.checkWinner(player, "Computer");
	if (result.winner) {
		return;
	}
	if (result.isDraw) {
		return;
	}
	isPlayerTurn = true;
	this.TextArea00.insertText("It's your turn."+"\n");
}

8

Button 컴포넌트의 onclick 이벤트 핸들러 함수를 아래와 같이 작성합니다.

this.Button00_onclick = function(obj:nexacro.Button,e:nexacro.ClickEventInfo)
{
	for (let i = 0; i < 9; i++) {
		board[i] = null;
		this.Div00.form.components["Static0"+i].text = "";
		this.Div00.form.components["Static0"+i].background = "";
	}
	gameOver = false;
	this.TextArea00.value = "It's your turn."+"\n";
};

9

QuickView(Ctrl + F6)로 실행한 후, 게임을 즐겨보세요.