2012-06-21 4 views
0

나는 물고기의 물고기를 코로나의 샘플 코드에서 분석하고 있는데 그 과제를 이해할 수 없었다. 이 and들과 or들에 관해서루아의 과제 혼란

-- Seed randomizer 
local seed = os.time(); 
math.randomseed(seed) 

display.setStatusBar(display.HiddenStatusBar) 

-- Preload the sound file (theoretically, we should also dispose of it when we are completely done with it) 
local soundID = audio.loadSound("bubble_strong_wav.wav") 

-- Background 
local halfW = display.viewableContentWidth/2 
local halfH = display.viewableContentHeight/2 

-- Create a table to store all the fish and register this table as the 
-- "enterFrame" listener to animate all the fish. 
local bounceAnimation = { 
container = display.newRect(0, 0, display.viewableContentWidth, display.viewableContentHeight), 
reflectX = true, 
} 

local backgroundPortrait = display.newImage("aquariumbackgroundIPhone.jpg", 0, 0) 
local backgroundLandscape = display.newImage("aquariumbackgroundIPhoneLandscape.jpg", -80, 80) 
backgroundLandscape.isVisible = false 
local background = backgroundPortrait 


-- Handle changes in orientation for the background images 
local backgroundOrientation = function(event) 
-- TODO: This requires some setup, i.e. the landscape needs to be centered 
-- Need to add a centering operation. For now, the position is hard coded 
local delta = event.delta 
if (delta ~= 0) then 
    local rotateParams = { rotation=-delta, time=500, delta=true } 

    if (delta == 90 or delta == -90) then 
     local src = background 

     -- toggle background to refer to correct dst 
     background = (backgroundLandscape == background and backgroundPortrait) or  backgroundLandscape 
     background.rotation = src.rotation 
     transition.dissolve(src, background) 
     transition.to(src, rotateParams) 
    else 
     assert(180 == delta or -180 == delta) 
    end 

    transition.to(background, rotateParams) 

    audio.play(soundID)   -- play preloaded sound file 
end 
end 

-- Add a global listener 
Runtime:addEventListener("orientation", backgroundOrientation)  
-- 
-- Fishies 
local numFish = 10 
local file1 = "fish.small.red.png" 
local file2 = "fish.small.blue.png"  
-- 
-- Define touch listener for fish so that fish can behave like buttons. 
-- The listener will receive an 'event' argument containing a "target" property 
-- corresponding to the object that was the target of the interaction. 
-- This eliminates closure overhead (i.e. the need to reference non-local variables) 
local buttonListener = function(event) 
if "ended" == event.phase then 
    local group = event.target 

    -- tap only triggers change from original to different color 
    local topObject = group[1] 

    if (topObject.isVisible) then 
     local bottomObject = group[2] 

     -- Dissolve to bottomObject (different color) 
     transition.dissolve(topObject, bottomObject, 500) 

     -- Restore after some random delay 
     transition.dissolve(bottomObject, topObject, 500, math.random(3000, 10000)) 
    end 

    -- we handled it so return true to stop propagation 
    return true 
end 
    end           
    -- 
    -- 


-- 
-- Add fish to the screen 
for i=1,numFish do 
-- create group which will represent our fish, storing both images (file1 and file2) 
local group = display.newGroup() 

local fishOriginal = display.newImage(file1) 
group:insert(fishOriginal, true) -- accessed in buttonListener as group[1] 

local fishDifferent = display.newImage(file2) 
group:insert(fishDifferent, true) -- accessed in buttonListener as group[2] 
fishDifferent.isVisible = false -- make file2 invisible 

-- move to random position in a 200x200 region in the middle of the screen 
group:translate(halfW + math.random(-100, 100), halfH + math.random(-100, 100)) 

-- connect buttonListener. touching the fish will cause it to change to file2's image 
group:addEventListener("touch", buttonListener) 

-- assign each fish a random velocity 
group.vx = math.random(1, 5) 
group.vy = math.random(-2, 2) 

-- add fish to animation group so that it will bounce 
bounceAnimation[ #bounceAnimation + 1 ] = group 
end              
-- 
-- Function to animate all the fish 
function bounceAnimation:enterFrame(event) 
local container = self.container 
container:setFillColor(0, 0, 0, 0)  -- make invisible 
local containerBounds = container.contentBounds 
local xMin = containerBounds.xMin 
local xMax = containerBounds.xMax 
local yMin = containerBounds.yMin 
local yMax = containerBounds.yMax 

local orientation = self.currentOrientation 
local isLandscape = "landscapeLeft" == orientation or "landscapeRight" == orientation 

local reflectX = nil ~= self.reflectX 
local reflectY = nil ~= self.reflectY 

-- the fish groups are stored in integer arrays, so iterate through all the 
-- integer arrays 
for i,v in ipairs(self) do 
    local object = v -- the display object to animate, e.g. the fish group 
    local vx = object.vx 
    local vy = object.vy 

    if (isLandscape) then 
     if ("landscapeLeft" == orientation) then 
      local vxOld = vx 
      vx = -vy 
      vy = -vxOld 
     elseif ("landscapeRight" == orientation) then 
      local vxOld = vx 
      vx = vy 
      vy = vxOld 
     end 
    elseif ("portraitUpsideDown" == orientation) then 
     vx = -vx 
     vy = -vy 
    end 

    -- TODO: for now, time is measured in frames instead of seconds... 
    local dx = vx 
    local dy = vy 

    local bounds = object.contentBounds 

    local flipX = false 
    local flipY = false 

    if (bounds.xMax + dx) > xMax then 
     flipX = true 
     dx = xMax - bounds.xMax 
    elseif (bounds.xMin + dx) < xMin then 
     flipX = true 
     dx = xMin - bounds.xMin 
    end 

    if (bounds.yMax + dy) > yMax then 
     flipY = true 
     dy = yMax - bounds.yMax 
    elseif (bounds.yMin + dy) < yMin then 
     flipY = true 
     dy = yMin - bounds.yMin 
    end 

    if (isLandscape) then flipX,flipY = flipY,flipX end 
    if (flipX) then 
     object.vx = -object.vx 
     if (reflectX) then object:scale(-1, 1) end 
    end 
    if (flipY) then 
     object.vy = -object.vy 
     if (reflectY) then object:scale(1, -1) end 
    end 

    object:translate(dx, dy) 
end 
end 

-- Handle orientation of the fish 
function bounceAnimation:orientation(event) 
print("bounceAnimation") 
for k,v in pairs(event) do 
    print(" " .. tostring(k) .. "(" .. tostring(v) .. ")") 
end 

if (event.delta ~= 0) then 
    local rotateParameters = { rotation = -event.delta, time=500, delta=true } 

    Runtime:removeEventListener("enterFrame", self) 
    self.currentOrientation = event.type 

    for i,object in ipairs(self) do 
     transition.to(object, rotateParameters) 
    end 

    local function resume(event) 
     Runtime:addEventListener("enterFrame", self) 
    end 

    timer.performWithDelay(500, resume) 
end 
end 

Runtime:addEventListener("enterFrame", bounceAnimation); 
Runtime:addEventListener("orientation", bounceAnimation) 


-- This function is never called, 
-- but shows how we would unload the sound if we wanted to 
function unloadSound() 
audio.dispose(soundID) 
soundID = nil 
end 
+1

모든 코드를 추가하는 것은 의미가 없습니다. 문제를 보여주는 작업 샘플 만 게시하면 더 많은 답변을 얻을 수 있습니다. * 아무도 * 귀하의 페이지 - 긴 코드를 읽지 않을 것입니다. – jpjacobs

답변

5

루아가 약간 이상한 행동을 가지고 :

background = (backgroundLandscape == background and backgroundPortrait) or backgroundLandscape 

여기에 전체 코드입니다.

a 거짓 간주하는 경우 a and ba 평가 식과 a가 참 고려하면 식 b 평가 (에만 nilfalse 거짓 간주 0이 참 간주 포함한 다른 값).

a가 true로 간주되며 ba 경우가 false로 간주되는 경우 a or ba로 평가 표현.

참고 : 두 경우 모두 표현식이 a 인 것으로 평가되는 경우 b 값도 평가되지 않습니다. 이를 단락 논리라고합니다. and에서 a이 거짓이면 and은 사실 일 수 없으므로 계산 시간을 낭비하지 않아도 b을 평가할 필요가 없습니다. 마찬가지로 이 a or b에서 true 인 경우 b을 평가할 점이 없으므로 or은 false 일 수 없습니다. valiftrue이 거짓로 평가해서는 안 : 문, 한주의와 경우

구축물 cond and valiftrue or valiffalse (또는 인해 연산자 우선 순위, (cond and valiftrue) or valiffalse에 상응하는) 다른 언어의 원에 해당합니다. 이 경우 전체 식은 항상 valiffalse으로 평가됩니다. (시도하고 추론해라, 그것은 내가이 구조에 관해 이해를 얻는 것을 알는 최고의 방법이다.)

1

는 상세하게 게시하려고하고 있었다. 그러나 @JPvdMerwe는 그것에 지점을 알아 들었다. @JPvdMerwe 지적한 바와 backgroundPortrait 다음

background = backgroundLandscape 
거짓이면

정확하게는

background = (backgroundLandscape == background and backgroundPortrait) or backgroundLandscape 

이 경우

if backgroundLandscape == background then 
    background = backgroundPortrait 
else 
    background = backgroundLandscape 
end 

EDIT

로 변환

이 항상 실행됩니다.

+0

내가주의를 끌고 싶은 유일한 이유는 (그리고 이것이 내가이 구조를 좋아하지 않는 이유 인)'backgroundPortrait'가 false로 간주되는 값이어서는 안된다는 것입니다. – JPvdMerwe

+0

좋은 지적! 그걸 몰랐어. 하지만 네, 논리적으로는 일종의 분명한 것입니다. – SatheeshJM