2013-12-05 2 views
0

Я прочитал другие темы, связанные с этой темой, и не могу понять их в смысле моего кода. В приведенном ниже коде я не могу заставить сделать другие текстовые кнопки в таблицу. Я могу генерировать слова, но они не пойдут в таблицу. Предыдущая функция с правильным словом работает нормально. Что я делаю не так? У меня проблемы в другом месте кода?Corona SDK: Вставка в таблицы

--main text 

local content = require "content" 

--chooses a random number according to the maximum number available in the table 

local defaultWidth = 1024 
local defaultHeight = 768 
local displayWidth = display.viewableContentWidth 
local displayHeight = display.viewableContentHeight 
local yMargin = 20 
local centerX = defaultWidth/2; 
local centerY = defaultHeight/2; 
local xAdjust = (defaultWidth - display.viewableContentWidth)/2 
local yAdjust = (defaultHeight - display.viewableContentHeight)/2 
local rnd = math.random 
local maxSightwords = 3 
local currQuestion = 0 
local playOrder 
local letterButtons 
local wrongGraphic 
local correctButton 
--local wordButtons 


function getRandomOrder(amount) 
    local order ={} 
    local i 
    local temp 
    local temp1 
    for n = 1,amount do 
     order[n] = n 
    end 
    for i=0,9 do 
     for temp = 1,amount do 
      n = math.random(1, amount) 
      temp1 = order[temp] 
      order[temp] = order[n] 
      order[n] = temp1 
     end 
    end 
    return order 

end 

    -- assign random order for words 
    playOrder = getRandomOrder(#content) 


function nextQuestion() 

    -- update question number index 
    currQuestion = currQuestion+1 
    if currQuestion > #playOrder then 
     currQuestion = 1 
    end 

    local questionNumber = playOrder[currQuestion] 

    print("Question# "..currQuestion) 
    print("id "..content[questionNumber].id) 

    -- make word buttons 
    wordButtons = {} 

    -- make word button for correct word 
    local word = content[playOrder[currQuestion]].word 
    table.insert(wordButtons, newWordButton(word)) 
    correctButton = wordButtons[1].graphics 
    local buttonWidth = 150 

    print ("correct: "..word) 
    print (#wordButtons) 


    ---[[ 
    -- ****make other word buttons*** 
    local otherWords = getRandomWords(content.word) 

    --print (otherWords) 
    for i=1, maxSightwords-1 do 
     table.insert(wordButtons, otherWords) 

    end 
    --]] 
    print (#wordButtons) 



    -- position letter buttons and add touch event listener 
    local randomWordOrder = getRandomOrder(#wordButtons) 
    local buttonSpacing = buttonWidth * 1.5 
    local buttonsWidth = (#wordButtons * buttonWidth) + ((#wordButtons-1) * (buttonSpacing/4)) 
    local buttonsX = centerX - (buttonWidth) 
    for i=1, #wordButtons do 
     local button = wordButtons[i].graphics 
     button.y = centerY 
     button.x = buttonsX + (buttonSpacing * (randomWordOrder[i]-1)) 
     button:addEventListener("touch", onWordTouch) 
     --local randomDelay = transitionDuration + (math.random(1,10) * 10) 
     --transition.from(button, {time = 500, delay = randomDelay, y = defaultHeight + button.height}) 
    end 

end 

function clearQuestion() 
    -- remove wrongGraphic if present 
    if wrongGraphic then 
     wrongGraphic:removeSelf() 
     wrongGraphic = nil 
    end 

    -- remove all word buttons 
    for i=1,#wordButtons do 
     wordButtons[i].graphics:removeSelf() 
     wordButtons[i].graphics = nil 
    end 
end 


function onWordTouch(event) 
    local t = event.target 
    if "ended" == event.phase then 
     if t == correctButton then 
      onCorrect() 
     else 
      onIncorrect(t) 
     end 

    end 
end 

function onIncorrect(incorrectButton) 
    media.playSound("sounds/splat.wav") 
    wrongGraphic = display.newImageRect("images/graphics/wrong.png", 137, 136) 
    wrongGraphic.x = incorrectButton.x + incorrectButton.width/2 
    wrongGraphic.y = incorrectButton.y + incorrectButton.height/2 
    transition.to(incorrectButton, {time=100, delay=500, alpha=0}) 
    transition.to(wrongGraphic, {time=200, delay=500, alpha=0, onComplete=wrongCompleteListener}) 
    local wrongCompleteListener = function(obj) 
     obj:removeSelf() 
     obj = nil 
     incorrectButton:removeSelf() 
     incorrectButton = nil 
    end 
end 

function onCorrect() 
    -- play correct sound then display word 
    media.playSound("sounds/correct.mp3", playWord) 

    -- remove the letter buttons 
    clearQuestion() 

    -- disable the home button until new screen is shown 
    homeEnabled = false 
end 



function newWordButton(word) 
    local wordGraphic = display.newImageRect("images/words/"..word..".png", 150, 75) 
    local wordButton = {} 
    wordButton.graphics = display.newGroup() 
    wordButton.graphics:insert(wordGraphic) 
    wordButton.word = word 
    return wordButton 
end 

function getRandomWords() 
    local wordGraphic = display.newGroup() 
    for i=1,maxSightwords-1 do 
    --remove a word from content using a random index # 
    --Since the index will be between 1 and the number of words in content 
    --and each time through the loop a word is removed, you can be sure 
    --You will get 3 different words without repeats. 
    local next_word = table.remove(content, math.random(#content)) 

    --next_word is a table with 'word' and 'id' fields so you can make the text display object from next_word.word 
    local wordText = display.newImageRect("images/words/"..next_word.id..".png", 150, 75) 
      wordText.x = display.contentWidth/2 
      wordText.y = display.contentHeight/2 - 100 
      wordGraphic:insert(wordText) 
     print (next_word.id) 
    end 
end 

nextQuestion() 

ответ

0

Я думаю, ваша проблема в том, что вы сброса wordButton = {} снова в функции newWordButton. Вы уже сделали таблицу в function nextQuestion(), поэтому, вызывая ее снова в функции newWordButton, вы пересылаете всю таблицу.

Посмотрите на это ссылки:

http://www.coronalabs.com/blog/2011/06/21/understanding-lua-tables-in-corona-sdk/

http://docs.coronalabs.com/api/library/table/insert.html

Я уверен, что функция должна выглядеть следующим образом:

function newWordButton(word) 
    local wordGraphic = display.newImageRect("images/words/"..word..".png", 150, 75) 
    wordButton.graphics = display.newGroup() 
    wordButton.graphics:insert(wordGraphic) 
    wordButton.word = word 
    return wordButton 
end 
+0

Спасибо за предложение но таблицы на самом деле разные: wordButtons и wordButton – user3029068

+0

О, мой плохой не заметил этого. Тем не менее, эти ссылки должны помочь вам решить вашу проблему. Возможно, вы захотите создать отдельный документ и попытаться просто вставить нужные значения в таблицу, а затем поместить его в свой код. –

+0

Кажется, что-то о значении или клавишах, созданных в случайных словарных функциях. Я проверил упомянутые вами учебники и нашел других, но все еще не могу понять. – user3029068