반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리


반응형
오늘은 화면에 점수 표시하는 샘플코드를 공부할 겁니다.

이 파일이 전체 소스 파일입니다.
웹 싸이트는 http://techority.com/2011/01/26/how-to-add-a-score-to-your-iphone-app/ 입니다.
이 싸이트로 가면 유튜브 동영상도 있습니다.

이 소스를 보면서 제 식으로 공부 해 보겠습니다.


이 소스를 실행하면 위 화면처럼 나옵니다.
화면을 Tapping 하면 1 포인트씩 숫자가 올라갑니다.

우선 main.lua부터 보겠습니다.

--[[
Related files are score.lua, 1 through 9.png, scorebg.png and space.png
--]]
display.setStatusBar( display.HiddenStatusBar )
local background = display.newImage ("background.png")

score = require ("score")

local border = 5

local scoreInfo = score.getInfo()

score.init({
x = 40,
y = 5}
)
score.setScore(0)

local function addtoit (event)
if event.phase == "ended" then
score.setScore (score.getScore()+1)
end
end
background:addEventListener("touch", addtoit)

처음에 아이폰의 StatusBar를 없앱니다. (원래 소스에는 없는데 그냥 제가 추가 했습니다. 이게 보기에 더 편하더라구요.)
두번째는 백그라운드 이미지를 display 합니다.

세번째는 score.lua 소스를 require (implement) 합니다.
그 다음은 border를 5로 설정합니다.(이 border는 뭐 하는건지 모르겠습니다. 그냥 쓸데없이 있는거 같네요.)

그 다음엔 아까 require했던 score.lua에 있는 getInfo() 함수를 scoreInfo 변수에 담습니다. 이 getInfo() 함수는 이따 score.lua 파일을 살펴 볼 때 어떤 기능인지 공부하겠습니다.

그 다음은 score.lua에 있는 init() 함수에 x,y 파라미터를 넣어서 실행시킵니다.
그리고 setScore()함수에 파라미터 값을 0으로 해서 보냅니다.

로컬 함수 addtoit(event) 함수를 만듭니다.
그 내용은 이벤트가 끝나면 score.lua의 setScore함수에 이전 점수 +1 을 한 파라미터 값을 넣어서 부릅니다.

맨 마지막으로 background 에 touch 리스너를 달구요. 이 이벤트가 일어났을 경우 addtoit() 함수를 실행시킵니다.

지금까지 main.lua의 코드를 분석해 봤습니다.
이제 score.lua 파일을 분석해 보겠습니다.

-- A sample score keeping display
-- This updates a display for a numeric score
-- Example usage:
--    Place the score at 50,50
--         score.init( { x = 50, y = 50 } )
--    Update the score to current value + 10:
--        score.setScore( score.getScore() + 10 )

module(..., package.seeall)
 
-- Init images. This creates a map of characters to the names of their corresponding images.
 local numbers = {
    [string.byte("0")] = "0.png",
    [string.byte("1")] = "1.png",
    [string.byte("2")] = "2.png",
    [string.byte("3")] = "3.png",
    [string.byte("4")] = "4.png",
    [string.byte("5")] = "5.png",
    [string.byte("6")] = "6.png",
    [string.byte("7")] = "7.png",
    [string.byte("8")] = "8.png",
    [string.byte("9")] = "9.png",
    [string.byte(" ")] = "space.png",
}

-- score components
local theScoreGroup = display.newGroup()
local theBackground = display.newImage( "scorebg.png" )
local theBackgroundBorder = 10

theScoreGroup:insert( theBackground )

local numbersGroup = display.newGroup()
theScoreGroup:insert( numbersGroup )

-- the current score
local theScore = 0

-- the location of the score image

-- initialize the score
--         params.x <= X location of the score
--         params.y <= Y location of the score
function init( params )
    theScoreGroup.x = params.x
    theScoreGroup.y = params.y
    setScore( 0 )
end

-- retrieve score panel info
--        result.x <= current panel x
--        result.y <= current panel y
--        result.xmax <= current panel x max
--        result.ymax <= current panel y max
--        result.contentWidth <= panel width
--        result.contentHeight <= panel height
--        result.score <= current score
function getInfo()
    return {
        x = theScoreGroup.x,
        y = theScoreGroup.y,
        xmax = theScoreGroup.x + theScoreGroup.contentWidth,
        ymax = theScoreGroup.y + theScoreGroup.contentHeight,
        contentWidth = theScoreGroup.contentWidth,
        contentHeight = theScoreGroup.contentHeight,
        score = theScore
    }
end

-- update display of the current score.
-- this is called by setScore, so normally this should not be called
function update()
    -- remove old numerals
    theScoreGroup:remove(2)

    local numbersGroup = display.newGroup()
    theScoreGroup:insert( numbersGroup )

    -- go through the score, right to left
    local scoreStr = tostring( theScore )

    local scoreLen = string.len( scoreStr )
    local i = scoreLen   

    -- starting location is on the right. notice the digits will be centered on the background
    local x = theScoreGroup.contentWidth - theBackgroundBorder
    local y = theScoreGroup.contentHeight / 2
   
    while i > 0 do
        -- fetch the digit
        local c = string.byte( scoreStr, i )
        local digitPath = numbers[c]
        local characterImage = display.newImage( digitPath )

        -- put it in the score group
        numbersGroup:insert( characterImage )
       
        -- place the digit
        characterImage.x = x - characterImage.width / 2
        characterImage.y = y
        x = x - characterImage.width
        --
        i = i - 1
    end
end

-- get current score
function getScore()
    return theScore
end

-- set score to value
--    score <= score value
function setScore( score )
    theScore = score
   
    update()
end

score.lua 파일을 보겠습니다.
score.lua 파일 처음에 module(..., package.seeall) 를 넣습니다. 이러면 이 파일은 모듈로 사용될 수 있습니다.
이것을 했기 때문에 main.lua에서 require("score") 를 할 수 있고 이것을 변수 score에 담아서 score.(score.lua에 있는 함수) 방법으로 score.lua 내의 함수를 main.lua에서 사용할 수 있습니다.

그 다음 numbers 라는 테이블 변수에 0~9 의 이미지 파일을 담습니다.

그 다음은 display.newGroup()으로 객체들을 담을 그룹을 만듭니다.
그리고 score를 표시할 백그라운드 이미지를 넣고 theBackgroundBorder 변수에 10을 담습니다.

아까 만들었던  theScoreGroup에 백그라운드 이미지(theBackground)를 insert 합니다.
보시면 아까 theScoreGroup 말고 또다른 Group인 numberGroup을 만듭니다.
그리고 이 numberGrooup 자체를 처음의 theScoreGroup에 insert 합니다.

다음 줄에서 theScore 변수를 0으로 선언합니다. 처음 0점부터 시작하게 됩니다.
이제 함수가 나오네요. 아까 main.lua에서 불렀던 init(params) 함수가 나옵니다.

여기서는 theScoreGroup.x와 y를 전달받은 파라미터 값으로 넣고 setScore()함수에 0을 던져 줍니다.
아까 main에서 x=40, y=5 으로 보냈기 때문에 그 위치에 theScoreGroup의 객체들이 display 될 겁니다.

다음은 getInfo() 함수입니다. main함수에서는 이 함수에서 세팅된 값을 scoreInfo 변수에 담았었습니다.
getInfo() 함수에서는 7개의 값을 return합니다.
Lua (Corona) 에서는 복수개의 값을 return 할 수 있습니다.
theScoreGrooup,x , y 값과 ymax,ymax, contentWidth,contentHeight, score 등의 값을 return합니다.

다음은 update() 함수입니다.
처음엔 이전 score를 없앱니다.
그 다음은 numbersGroup이라는 그룹을 만들고 이를 통째로 theScoreGroup에 넣습니다.
다음줄은 theScore를 String 값으로 변환해서 scoreStr 변수에 담습니다.
Score가 한자리 수 인지 두자리 수인지 세자리 수인지 에 대한 정보를 담는 변수도 있네요.
scoreLen변수에 scoreStr 의 length를 담습니다.
local x, y는 점수가 표시되는 위치 입니다. 한자리 수일때 두자리 수일때 표시되는 위치가 조금씩 다르겠죠?

그 다음 while 문에서 어떤 점수 이미지를 어디에 뿌려줄지 계산하는 로직이 있습니다.
이미지를 출력하고 그 이미지를 numbersGroup에 담습니다.
그리고 나서 이미지의 x,y 좌표를 설정하구요.
이 while 문은 scoreLen 만큼 돌아갈 겁니다.

다음 함수는 getScore() 함수인데 여기서는 theScore를 리턴해 줍니다.

그리고 setScore() 함수에서는 theScore 함수에 score 값을 넣어 준 후 update() 함수를 실행시킵니다.

여기 까지 하면 scoring 샘플이 모두 완성된거구요.
이걸 실행 한 후 background를 누르면 점수가 1씩 증가하게 될 겁니다.

이 소스를 가지고 있으면 나중에 게임 개발할 때 아주 유용하게 사용할 수 있을 겁니다.

그럼.........

반응형

함수 (function) 공부

2011. 10. 3. 02:05 | Posted by 솔웅


반응형
오늘은 글로벌, 로컬 함수 사용법에 대해 자세히 살펴 보겠습니다.

함수의 기본

local function main()
   print("Hello from CoronaSDK")
end
main()

아주 평범하고 간단한 함수 작성 및 함수 불러오기 예제입니다.
main()함수는 로컬로 선언 됐고 터미널에 Hello from CoronaSDK 를 출력합니다.
이 함수는 맨 아랫 줄 에서 call 했습니다. (main() )

local main
  local function init()
    main()
  end
  function main()
   print("Hello from CoronaSDK")
  end
  init()

이번엔 main 을 로컬로 미리 선언해 놓고 함수 선언 시 local 을 따로 표시하지 않았습니다.
프로그램을 실행하면 로컬 init() 함수를 부를 것이고 이 init() 함수는 main() 함수를 부를겁니다. 문제없이 작동됩니다.
그런데 여기서

local main
  local function init()
    main()
  end
  local function main()
   print("Hello from CoronaSDK")
  end
  init()
이렇게 main() 함수 작성할 때도 local로 또 선언을 하면 에러가 나게 됩니다.
바로 init() 함수 안에서 main()함수를 불러올 때 에러가 납니다.
왜냐하면 main()을 불러올 때는 main() 함수가 없었기 때문에 main 이 nil 이기 때문에 불러오지 못하겠다고 에러 메세지를 뿌리는 겁니다.

local main

  local function main()
   print("Hello from CoronaSDK")
  end
  local function init()
    main()
  end
  init()
위 소스는 어떨까요. init()안에서 main()을 불러올 때 이미 그 위에서 로컬 main() 함수가 구현 돼 있죠? 이 경우는 제대로 실행이 될 겁니다.

Encapsulated Function (함수 캡슐화)

local function main()
    print ("Hello from CoronaSDK")

    function insideMain()
      print("This is a function inside of main, not available to be called from any other")
    end

   insideMain()
  end
 
  main()

자 이렇게 함수 안에 함수가 있는 경우 제대로 실행 됩니다.

local function spawnObject()
   local resultingObject = display.newRect(10,10,100,100)
   local function onTouch(event)
     if "ended" == event.phase then
      print("touched rectangle")
     end
   end
   resultingObject:addEventListener("touch",onTouch)
   return resultingObject
  end

  local xTemp = spawnObject()

위 코드를 실행하면 어떻게 될까요?
우선 맨 밑에 로클 xTemp 변수에 spawnObject() 가 담기변서 spawnObject() 가 실행 됩니다.
spawnObject()에서는 처음에 resultingObject라는 사각형을 그리게 됩니다.
그리고 event를 받는 onTouch라는 함수를 만들구요.
여기서는 touch 이벤트가 끝날 때 터미널에 문자열을 출력합니다.
그 다음엔 아까 그린 사각형에 리스너를 답니다. touch 가 일어났을 경우 onTouch 함수롤 불러오도록 설정합니다.
그 다음에 이 사각형을 리턴합니다.
이제 화면에 있는 사각형을 클릭하면 터미널에 문자열이 찍히게 됩니다.

Member functions (멤버 함수들)

멤버함수들은 객체가 되는 방법이 일반 함수들과 조금 다릅니다. 바로 전 코드에다가 색을 바꾸는 함수도 한번 추가해 봅시다.
일단 사각형 색을 바꾸는 함수 부분을 아래와 같이 추가합니다.
local function spawnObject()
   local resultingObject = display.newRect(10,10,100,100)

   function changeColor(theColor)
     resultingObject:setFillColor(theColor[1],theColor[2],theColor[3])
   end

   local function onTouch(event)
     if "ended" == event.phase then
      print("touched rectangle")
     end
   end

   resultingObject:addEventListener("touch",onTouch)

   return resultingObject
  end

  local xTemp = spawnObject()

자.. 이제 저 함수에 theColor라는 파라미터를 넣어서 불러오는 것을 해야 하는데요.
이 함수는 local로 선언돼 있지 않지만 spawnObject() 함수 밖에서는 불러올 수 없습니다.
spawnObject() 함수 안에 이 함수가 있으니까요.
그럼 밖에서 불러올 수 있도록 살짝 바꿔 보겠습니다.

local function spawnObject()
   local resultingObject = display.newRect(10,10,100,100)

   function resultingObject.changeColor(theColor)
     resultingObject:setFillColor(theColor[1],theColor[2],theColor[3])
   end

   local function onTouch(event)
     if "ended" == event.phase then
      print("touched rectangle")
     end
   end

   resultingObject:addEventListener("touch",onTouch)

   return resultingObject
  end

  local xTemp = spawnObject()
  xTemp.changeColor({255,0,255})

changeColor(theColor) 함수를 spawnObject()의 멤버인 resultingObject 의 멤버 함수로 선언했습니다.
이렇게 하면 spawnObject() 함수 밖에서 불러올 수 있습니다.
spawnObject() 를 xTemp 변수에 담았으니까. xTemp.changeColor({255,0,255}) 하게 되면 spawnObject()함수 안에 있는 changeColor를 불러오게 됩니다. 이 함수는 멤버인 사각형의 함수이니까요.

단순히 이 기능만 실행되게 하려면 여러 방법이 있습니다.
아래와 같이 해도 되구요.
local function spawnObject()
   local resultingObject = display.newRect(10,10,100,100)

   function changeColor(theColor)
     resultingObject:setFillColor(theColor[1],theColor[2],theColor[3])
   end

   local function onTouch(event)
     if "ended" == event.phase then
      print("touched rectangle")
     end
   end

   resultingObject:addEventListener("touch",onTouch)
    changeColor({255,0,255})
   return resultingObject
  end

  local xTemp = spawnObject()
  --xTemp.changeColor({255,0,255})

그런데 함수내 함수를 함수 바깥에서 부르기 위해서 멤버 변수를 사용한다는 예제를 배우는게 목적이니까 그걸 염두에 두고 보시면 될 거예요.

이 강좌의 원래 원본은 아래에 있습니다.
http://blog.anscamobile.com/2011/09/tutorial-scopes-for-functions/
코로나 SDK 만든 회사인 Ansca Mobile 에 있는 블로그에 있는 글입니다.

Cross calling

 다른 함수 안에 있는 함수 불러오는 방법 두번째 인데요. 이건 약간 복잡합니다.

local function spawnObject()
   local resultingObject = display.newRect(10,10,100,100)

   function resultingObject.changeColor(theColor)
     resultingObject:setFillColor(theColor[1],theColor[2],theColor[3])
   end

   local function onTouch(event)
     if "ended" == event.phase then
      print("touched rectangle")
     end
   end

  function wrap(event)
   if self.x < 25 then self.x = 25 end
   if self.x > 743 then self.x = 743 end
  end

   resultingObject:addEventListener("touch",onTouch)

   return resultingObject
  end

  local xTemp = spawnObject()
  Runtime:addEventListener("enterFrame", xTemp.wrap)

이 코드는 spawnObject() 안에 wrap(event) 함수를 만들고 spawnObject()
바깥에서 이 함수안의 wrap함수에 리스너를 답니다.

그런데 조금 이상하네요. 에러도 나구요. 아래 코드를 보겠습니다.

local function spawnObject() local resultingObject = display.newRect(10,10,100,100) function resultingObject.changeColor(theColor) resultingObject:setFillColor(theColor[1],theColor[2],theColor[3]) end local function onTouch(event) if "ended" == event.phase then print("touched rectangle") end end local function wrap(event)
print("in function wrap")
 if resultingObject.x < 25 then resultingObject.x = 25 end if resultingObject.x > 743 then resultingObject.x = 743 end end resultingObject:addEventListener("touch",onTouch) Runtime:addEventListener("enterFrame", wrap) return resultingObject end local xTemp = spawnObject()

이건 제대로 작동합니다.
spawnObject() 이 실행 됐을 때 이와 관련된 모든 함수들이 캡슐화 됐습니다.
이 코드의 목적은 이렇게 캡슐화 시키는 건가 봅니다.

Advanced Function

local hide = print
local print = math.random
local function main()
hide("What do you have to hide?")
hide( print(5) )
end

main()

루아는 위와 같이 함수를 변수에 담아서 편리하게 사용할 수 있습니다.

오늘은 함수와 관련된 좋은 아티클이 있길래 한번 공부해 봤습니다.
제가 100% 다 이해하지는 못한 것 같습니다.

저보다 더 프로그래밍 기초가 튼튼하신 분들은 좀 더 확실해 이해 하셨겠죠?
제가 잘못 이해했거나 부족한부분.... 덧 붙이고 싶으신 부분 있으면 언제든지 코멘트 해 주세요.

감사합니다.
반응형


반응형
accelerometer 는 가속도계라는 의미입니다.

이걸 적용하면 디바이스 기울기 이벤트에 따라 핸들링 할 수 있습니다.

어제 샘플로 드렸던 사람 인형 예제에 이 기능을 적용하도록 하겠습니다.

맨 밑줄에 아래 리스너를 다세요.

Runtime:addEventListener ("accelerometer", onAccelerate)

앱이 실행중에 이 리스너를 단다는 얘기예요. accelerometer 가 일어 날 때 onAccelerate 함수를 실행 하라는 의미구요.

그럼 저 리스너 위에 onAccelerate 함수를 만들어 넣을까요?

local function onAccelerate( event )
physics.setGravity( 10 * event.xGravity, -10 * event.yGravity )
end

이 함수는 중력을 세팅해주는 함수입니다.
기울기를 구해서 그것에 맞게 중력을 주는 겁니다.

아주 간단하죠?

이건 시뮬레이터에서는 못하구요. 직접 디바이스에 인스톨 하신 후에 테스트 할 수 있어요.

참고로 리스너 다는 방법은 아래와 같습니다.

object:addEventListener( eventName, listener )

eventName 에 들어갈 수 있는 것들은 touch, enterFrame, tap, accelerometer , collisiion, sprite 등 여러가지가 있습니다.

API 의 events 부분을 참고하세요.



반응형