Corona SDK: Displaying Word from Table - lua

OK my first question was too vague so I'm going to start simple here. I am trying to get a random word from a table in another lua file (content.lua). I have gotten the code to run without errors but cannot get a word to display on the screen or via print in the command console. What am I missing?
game.lua
--lua for game
--Loading the local variables
--creates the storyboard variable and calls the storyboard api
local storyboard = require ("storyboard")
--calls the mydata.lua module
local myData = require( "mydata" )
--calls the sfx.lua where sounds are stored
local sfx = require( "sfx" )
--calls the operations.lua
local operations = require("operations")
local content = require("content")
local playOrder
local wordGraphic
local currQuestion = 1
local homeButton
--tells storyboard to create a new scene
local scene = storyboard.newScene()
function scene:createScene(event)
local gameScreen = self.view
--creates a transparent background image centered on the display
local gameBackground = display.newImage("images/graphics/jungle1.jpg")
gameBackground.x = display.contentWidth/2
gameBackground.y = display.contentHeight/2
gameScreen:insert(gameBackground)
homeButton = display.newImage("images/buttons/home.png")
homeButton.alpha = .8
homeButton.y = 70
gameScreen:insert(homeButton)
playOrder = operations.getRandomOrder(#content)
end
local function onHomeTouch(event)
if event.phase == "began" then
storyboard.gotoScene("start")
end
end
function scene:enterScene(event)
homeButton:addEventListener("touch", onHomeTouch)
audio.play(sfx.Bkgd)
--uses the operations.lua to get words in a random order from the content.lua
--shows a random word from the content.lua table
function showWord()
local word = content[playOrder[currQuestion]].word
print(word)
wordGraphic = self.view
wordGraphic:insert(word)
wordGraphic.x = display.contentWidth/2
wordGraphic.y = display.contentHeight/2
end
end
--next question function which clears the screen and loads a new random word
function scene:exitScene(event)
homeButton:removeEventListener("touch", onHomeTouch)
end
function scene:destroyScene(event)
end
--the actual event listeners that make the functions work
scene:addEventListener("createScene", scene)
scene:addEventListener("enterScene", scene)
scene:addEventListener("exitScene", scene)
scene:addEventListener("destroyScene", scene)
return scene
Here is the operations.lua that gets the random order function
--operations.lua
module(..., package.seeall)
--function to get a random piece of data
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
This is where the words I am attempting to display are stored. I did not include all of them.
--content.lua
return {
{
id = "after",
word = "after"
},
{
id = "again",
word = "again"
},
{
id = "an",
word = "an"
},
{
id = "any",
word = "any"
},
{
id = "ask",
word = "ask"
},
{
id = "as",
word = "as"
},
{
id = "by",
word = "by"
}
}

You're not calling showWord in any of the code that you've shown so far. This is probably why it isn't even printing to the console. The function is just contained within scene:enterScene and exits to the outer scope, defining itself as a global variable when enterScene is called.

Related

dictionary help/DataStore

The Issue is I have a dictionary that holds all my data and its supposed to be able to turn into a directorys in replicated storage with all the values being strings then turn back into a dictionary with all the keys when the player leave. However, I cant figure out how to turn into a dictionary(With keys).
ive sat for a few hours testing things but after the first layer of values I cant get figure out a way to get the deeper values and keys into the table
local DataTable =
{
["DontSave_Values"] =
{
["Stamina"] = 100;
};
["DontSave_Debounces"] =
{
};
["TestData"] = 1;
["Ship"] =
{
["Hull"] = "Large_Ship";
["Mast"] = "Iron_Tall";
["Crew"] =
{
["Joe One"] =
{
["Shirt"] = "Blue";
["Pants"] = "Green"
};
["Joe Two"] =
{
["Shirt"] = "Silver";
["Pants"] = "Brown";
["Kids"] =
{
["Joe Mama1"] =
{
["Age"] = 5
};
["Joe Mama2"]=
{
["Age"] = 6
};
}
};
}
};
["Level"] =
{
};
["Exp"] =
{
};
}
------Test to see if its an array
function isArray(Variable)
local Test = pcall(function()
local VarBreak = (Variable.." ")
end)
if Test == false then
return true
else
return false
end
end
------TURNS INTO FOLDERS
function CreateGameDirectory(Player, Data)
local mainFolder = Instance.new("Folder")
mainFolder.Parent = game.ReplicatedStorage
mainFolder.Name = Player.UserId
local function IterateDictionary(Array, mainFolder)
local CurrentDirectory = mainFolder
for i,v in pairs(Array) do
if isArray(v) then
CurrentDirectory = Instance.new("Folder", mainFolder)
CurrentDirectory.Name = i
for o,p in pairs(v) do
if isArray(p) then
local TemporaryDir = Instance.new("Folder", CurrentDirectory)
TemporaryDir.Name = o
IterateDictionary(p, TemporaryDir)
else
local NewValue = Instance.new("StringValue", CurrentDirectory)
NewValue.Name = o
NewValue.Value = p
end
end
else
local value = Instance.new("StringValue", mainFolder)
value.Name = i
value.Value = v
end
end
end
IterateDictionary(Data, mainFolder)
end
------To turn it back into a table
function CreateTable(Player)
local NewDataTable = {}
local Data = RS:FindFirstChild(Player.UserId)
local function DigDeep(newData, pData, ...)
local CurrentDir = newData
for i,v in pairs(pData:GetChildren()) do
if string.sub(v.Name,1,8) ~= "DontSave" then
end
end
end
DigDeep(NewDataTable, Data)
return NewDataTable
end
I expected to when the player leaves run createtable function and turn all the instances in replicated storage back into a dictionary with keys.
Why not just store extra information in your data table to help make it easy to convert back and forth. As an example, why not have your data look like this :
local ExampleData = {
-- hold onto your special "DON'T SAVE" values as simple keys in the table.
DONTSAVE_Values = {
Stamina = 0,
},
-- but every element under ReplicatedStorage will be used to represent an actual Instance.
ReplicatedStorage = {
-- store an array of Child elements rather than another map.
-- This is because Roblox allows you to have multiple children with the same name.
Name = "ReplicatedStorage",
Class = "ReplicatedStorage",
Properties = {},
Children = {
{
Name = "Level",
Class = "NumberValue",
Properties = {
Value = 0,
},
Children = {},
},
{
Name = "Ship",
Class = "Model",
Properties = {},
Children = {
{
-- add all of the other instances following the same pattern :
-- Name, Class, Properties, Children
},
},
},
}, -- end list of Children
}, -- end ReplicatedStorage element
};
You can create this table with a simple recursive function :
-- when given a Roblox instance, generate the dataTable for that element
local function getElementData(targetInstance)
local element = {
Name = targetInstance.Name,
Class = targetInstance.ClassName,
Properties = {},
Children = {},
}
-- add special case logic to pull out specific properties for certain classes
local c = targetInstance.ClassName
if c == "StringValue" then
element.Properties = { Value = targetInstance.Value }
-- elseif c == "ADD MORE CASES HERE" then
else
warn(string.format("Not sure how to parse information for %s", c))
end
-- iterate over the children and populate their data
for i, childInstance in ipairs(targetInstance:GetChildren()) do
table.insert( element.Children, getElementData(childInstance))
end
-- give the data back to the caller
return element
end
-- populate the table
local Data = {
ReplicatedStorage = getElementData(game.ReplicatedStorage)
}
Now Data.ReplicatedStorage.Children should have a data representation of the entire folder. You could even save this entire table as a string by passing it to HttpService:JSONEncode() if you wanted to.
When you're ready to convert these back into instances, use the data you've stored to give you enough information on how to recreate the elements :
local function recreateElement(tableData, parent)
-- special case ReplicatedStorage
if tableData.Class == "ReplicatedStorage" then
-- skip right to the children
for i, child in ipairs(tableData.Children) do
recreateElement(child, parent)
end
-- quick escape from this node
return
end
-- otherwise, just create elements from their data
local element = Instance.new(tableData.Class)
element.Name = tableData.Name
-- set all the saved properties
for k, v in pairs(tableData.Properties) do
element[k] = v
end
-- recreate all of the children of this element
for i, child in ipairs(tableData.Children) do
recreateElement(child, element)
end
-- put the element into the workspace
element.Parent = parent
end
-- populate the ReplicatedStorage from the stored data
recreateElement( Data.ReplicatedStorage, game.ReplicatedStorage)
You should be careful about how and when you choose to save this data. If you are playing a multiplayer game, you should be careful that this kind of logic only updates ReplicatedStorage for the first player to join the server. Otherwise, you run the risk of a player joining and overwriting everything that everyone else has been doing.
Since there isn't a way to iterate over properties of Roblox Instances, you'll have to manually update the getElementData function to properly store the information you care about for each type of object. Hopefully this helps!
If anyone else has this problem the solution I used was just to convert the instances strait into JSON format(I used the names as keys). so that way I can save it, and then when the player rejoins I just used JSONDecode to turn it into the dictionary I needed.
function DirToJSON(Player)
local NewData = RS:FindFirstChild(Player.UserId)
local JSONstring="{"
local function Recurse(Data)
for i, v in pairs(Data:GetChildren()) do
if v:IsA("Folder") then
if #v:GetChildren() < 1 then
if i == #Data:GetChildren()then
JSONstring=JSONstring..'"'..v.Name..'":[]'
else
JSONstring=JSONstring..'"'..v.Name..'":[],'
end
else
JSONstring=JSONstring..'"'..v.Name..'":{'
Recurse(v)
if i == #Data:GetChildren()then
JSONstring=JSONstring..'}'
else
JSONstring=JSONstring..'},'
end
end
else
if i == #Data:GetChildren()then
JSONstring=JSONstring..'"'..v.Name..'":"'..v.Value..'"'
else
JSONstring=JSONstring..'"'..v.Name..'":"'..v.Value..'",'
end
end
end
end
Recurse(NewData)
JSONstring = JSONstring.."}"
return(JSONstring)
end

Why is Corona not reloading the scene?

I try to make a card game that will change scenes when the player touches on the card but the initial page does not load again.
My code follows:
main.lua
local storyboard = require("storyboard")
local background = display.newImage("Icon-72.png")
storyboard.gotoScene("level1")
level1.lua
local storyboard = require("storyboard")
local level1 = storyboard.newScene()
function level1:createScene( event )
print("level 1 create scene")
local group = self.view
local x = 3
group:insert(display.newText(x,40,50))
-- body
local card = display.newImage("Icon-Small.png")
card.x = 50 ; card.y = 150
group:insert(card)
function card:touch(event )
display.remove(card)
storyboard.gotoScene("level2")
end
card:addEventListener("touch",card)
end
function level1:enterScene( event )
local group = self.view
local card = display.newImage("Icon-Small.png")
card.x = 50 ; card.y = 150
group:insert(card)
function card:touch(event )
display.remove(card)
storyboard.gotoScene("level2")
end
card:addEventListener("touch",card)
-- body
end
level1:addEventListener("createScene",level1)
level1:addEventListener("enterScene",level1)
return level1
level 2 :
local storyboard = require("storyboard")
local level2 = storyboard.newScene()
function level2:createScene( event )
print("level2 create")
local group = self.view
storyboard.purgeScene("level1")
storyboard.gotoScene("level1")
end
level2:addEventLister("createScene",level2)
return level2
You have a typo at the bottom of level2.lua:
level2:addEventLister("createScene",level2)
Should be:
level2:addEventListener("createScene",level2)

Corona Sdk - Is there a way to call and group:insert() an object from another lua file?

As stated in the title I would like to not only call an object from an external Lua file, but I would also like to group:insert() this object into my Menu page with the properties given to it in the external lua file. Is this possible and/or efficient? I would just really like to make sure data isn't repeated through out my project.
EDIT
Here's my code so far:
The group:insert() function is throwing me an error stating it was expecting a table and that I might have been trying to call a function in which case i should use ":" instead of "."
This is menu.lua:
local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
local widget = require "widget"
local m = require ("myData")
local menuFunction = require("menuFunction")
local menuSwipe
-- =======================
-- menuSwipe()
-- =======================
menuSwipe = function(self, event)
local phase = event.phase
local touchID = event.id
if(phase == "began") then
elseif(phase == "moved") then
elseif(phase == "ended" or phase == "cancelled") then
if(m.menuActivator > 0) then
menuDown(m.invisiBar, event)
else
--m.layerInfo = layers
transition.to( menuFunction.menuBar, { x = menuFunction.menuBar.x, y = 0, time = 200 } )
--transition.to( layers, { x = menuFunction.menuBar.x, y = h, time = 100 } )
m.invisiBar = display.newRect( 0,0,w,25,6)
m.invisiBar.alpha = 0
m.menuActivator = 1
end
end
end
-- ++++++++++++++++++++++
-- menuDown()
-- ++++++++++++++++++++++
function menuDown(self, event)
local phase = event.phase
local touchID = event.id
if(phase == "began") then
elseif(phase == "moved") then
elseif(phase == "ended" or phase == "cancelled") then
if(m.menuActivator == 1) then
transition.to( menuFunction.menuBar, { x = m.menuInfo.x, y = h*.964, time = 200 } )
--transition.to( group, { x = 0, y = 0, time = 10 } )
m.menuActivator = 0
end
end
end
function scene:createScene( event )
local group = self.view
group:insert( menuFunction.menuBar ) -- *** ERROR occurs here
end
function scene:enterScene( event )
local group = self.view
end
function scene:exitScene( event )
local group = self.view
end
function scene:destroyScene( event )
local group = self.view
end
scene:addEventListener( "createScene", scene )
scene:addEventListener( "enterScene", scene )
scene:addEventListener( "exitScene", scene )
scene:addEventListener( "destroyScene", scene )
return scene
This is menuFunction.lua:
local m = require("myData")
local menu = require ("menu")
local w = display.contentWidth
local h = display.contentHeight
local menuFunction = {}
--menuBar
menuFunction.menuBar = display.newImage( "images/menuBar1.png")
menuFunction.menuBar.x = w*(1/2)
menuFunction.menuBar.y = h*1.465
menuFunction.menuBar.height = h
menuFunction.menuBar:setReferencePoint(display.TopLeftReferencePoint)
menuFunction.menuBar.touch = menu.menuSwipe
menuFunction.menuBar:addEventListener("touch", menuFunction.menuBar)
return menuFunction
This is the exact error message:
ERROR: table expected. If this is a function call, you might have used '.' instead of ':'
message**
Does this happen every time this code is called, or does it by any chance work the first time and then crashes? In your case, code could work the first time you enter the scene, but the second time you do, it may crash [if you remove scenes in between].
When you do a 'require' of a file, its contents are executed and returned value is saved in the global packages table. When you require the same file again, the returned value is taken from the global packages table instead, the code is not executed again.
So if you by any chance require this file in one spot of your app, and then call :removeSelf() and nil the reference of the menuBar, the display object will be removed and its reference will cease to exist, and calling the require again, will not recreate the object. Fully removing a scene will also remove the display objects.
So what you wanted to achieve is very sensible [contrary to what #Schollii says], but your "module" should allow creation of multiple objects if you want to get rid of them during runtime.
I'm not going to correct your code, just a simple example of how you can achieve this:
-- menu.lua
local menuCreator = {}
menuCreator.newMenu = function(params)
local menu = display.newGroup()
-- create your menu here
return menu
end
return menuCreator
Now anytime you do:
local menuCreator = require("menu.lua")
you will be able to call:
local menu = menuCreator.newMenu(someParams)
and get yourself a nice new menu wherever you need.
If it's not shown all the time on screen, it may be better to create a new one whenever you need it, and then remove it from the memory.
There are several issues with this, and none of them seem related to your error but fixing them will either also fix the error or make the cause of the error more obvious. Please fix following and update:
Although Lua allows it, don't use circular includes, where A includes B which includes A. Instead have menu require menuFunction and then call a creation function in menuFuntion:
-- menuFunction.lua
local m = require("myData")
-- require("menu") -- BAD! :)
local w = display.contentWidth
local h = display.contentHeight
local menuBar = display.newImage( "images/menuBar1.png")
menuBar.x = w*(1/2)
menuBar.y = h*1.465
menuBar.height = h
menuBar:setReferencePoint(display.TopLeftReferencePoint)
local menuFunction = { menuBar = menuBar }
function createMenuBar(menuSwipe)
menuFunction.menuBar.touch = menuSwipe
menuFunction.menuBar:addEventListener("touch", menuFunction.menuBar)
return menuFunction
end
-- menu.lua
function createScene(event)
local mf = require('menuFunction')
mfFunction = mf.createMenuBar(menuSwipe)
group:insert(menuFunction.menuBar)
end
Secondly out of the four calls to group:insert() the first 3 refer to objects that are not shown in the code and don't see relevant to problem, they should be removed or if you think relevant, comment why their code now shown, or show their code.

Lua/Corona Attempt to Index a Boolean Value

It looks like I am having problems with transitioning from my level select page to my first level. I think it might be that I am missing something in my level 1, but I don't know exactly.
levelSelect.lua
module(..., package.seeall)
local director = require ("director")
local physics = require("physics")
physics.start()
local widget = require( "widget" )
-- Function to handle button events
local function handleButtonEventLevel1( event )
local phase = event.phase
if "ended" == phase then
director:changeScene("lvl1")
end
end
--local function goLevel1()
--director:changeScene("lvl1")
--return true
--end
--widget.newButton:addEventListener("tap", goLevel1)
local function handleButtonEventToPage( event )
local phase = event.phase
if "ended" == phase then
director:changeScene("page")
end
end
-- Main function - MUST return a display.newGroup()
function new()
local localGroup = display.newGroup()
local background = display.newImage("bigtestsky.png")
background.x=150
background.y=250
local myButton = widget.newButton
{
left = 25,
top = 25,
width = 100,
height = 50,
defaultFile = "default.png",
overFile = "over.png",
label = "1",
font = "LS",
fontSize = 20,
labelColor = { default = {0,0,50}, over = {0,0,255} },
onEvent = handleButtonEventLevel1,
}
local myButton = widget.newButton
{
left = 25,
top = 415,
width = 100,
height = 50,
defaultFile = "default.png",
overFile = "over.png",
label = "BACK",
font = "LS",
fontSize = 20,
labelColor = { default = {0,0,50}, over = {0,0,255} },
onEvent = handleButtonEventToPage,
}
return localGroup
end
lvl1.lua
local physics = require("physics")
physics.start()
local widget = require( "widget" )
(This is what I mean about missing something in the first level. Could someone please help?)
stack traceback:
[C]: ?
.../myName/Desktop/Bubbles! App/director.lua:116: in function 'loadScene'
.../myName/Desktop/Bubbles! App/director.lua:394: in function 'changeScene'
...myName/Desktop/Bubbles! App/levelSelect.lua:14: in function '_onEvent'
?: in function '?'
?: in function <?:405>
?: in function <?:218>
These are due to some issues with your class: lvl1.lua.
If such error occurs, open director.lua analyse the error return line. This will help you to find what the real problem is.
Here, you must write more lines in your lvl1.lua as below:
module(...,package.seeall) -- If this line is not written, then the package will not be loaded.
function new() -- Module 'lvl1' must have a new() function
local localGroup = display.newGroup() -- The scene should create a display group
local physics = require("physics")
physics.start()
local widget = require( "widget" )
print("Inside lvl1...")
return localGroup; -- And the scene should return the previously created display group.
end
Keep Coding.............. :)

Changing Scenes in Corona objects stay on screen

I have been modifying code from the memory match game to use scenes, sounds, and a 2d table. Adding the scenes has been the hard part. I have it set up to randomly select items from my 2d table. Load those into a temporary table, shuffle them shuffle(), then boardSet(); to load their sounds and place them on the screen. Basically after the game is over I want the scene to reload or go back to the menu to start again. Selecting random data{} elements over and over.
I have tried returning to the menu, or going to a duplicate scene however I can't seem to correctly unload the objects created by my 2d array, as I can't properly add each item into a display group. I have tried everything I can think of. Right now my game loop is setup to add the play again btn that I want to restart the game after one match is found.
This link was a start in the right direction I believe with information about dealing with tables and groups. I still don't know how to cycle thru my 2d table to include everything in a group and then properly unload it.
http://developer.coronalabs.com/content/application-programming-guide-graphics-and-drawing#Variable_References
---------------------------------------------------------------------------------
--
-- level1.lua
--
---------------------------------------------------------------------------------
local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
local widget = require "widget"
---------------------------------------------------------------------------------
-- BEGINNING OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
local image, text1, text2, text3, memTimer
-- forward declarations and other locals
local againBtn
-- 'onRelease' event listener for playBtn
local function onPlayBtnRelease()
-- go to level1.lua scene
storyboard.gotoScene( "menu", "fade", 500 )
return true -- indicates successful touch
end
-- Preload the sound file (needed for Android)
--
local playBeep = function( testSound )
media.playEventSound( testSound )
end
---Preload sounds
ki = audio.loadSound("ki-nawaneyoo.mp3")
u = audio.loadSound("u.mp3")
mayuhoo = audio.loadSound("mayuhoo.mp3")
--End Sound Test
--Set Global width and height variables
_W = display.contentWidth;
_H = display.contentHeight;
---Count number of correct matches
local matchCount = 0;
--Hide status bar
display.setStatusBar(display.HiddenStatusBar);
--Declare a totalButtons variable to track number of buttons on screen
local totalButtons = 0
--Declare variable to track button select
local secondSelect = 0
local checkForMatch = false
--Declare Data Table
local data = {}
--Load objects into data
data[1] = {}
data[1].title = "Naka"
data[1].subtitle = "a"
data[1].image = "a.png"
data[1].image1 = "ear.png"
data[1].sound = "naka-ear.caf"
data[1].sound1 = "naka-ear.mp3"
data[2] = {}
data[2].title = "Aapuhu"
data[2].subtitle = "aa"
data[2].image = "aa.png"
data[2].image1 = "eyebrow.png"
data[2].sound = "aapuhu-eyebrow.caf"
data[2].sound1 = "aapuhu-eyebrow.mp3"
data[3] = {}
data[3].title = "Ego"
data[3].subtitle = "Ego"
data[3].image = "e.png"
data[3].image1 = "tongue.png"
data[3].sound = "ego-tongue.caf"
data[3].sound1 = "ego-tongue.mp3"
data[4] = {}
data[4].title = "Kamoo"
data[4].subtitle = "kamoo"
data[4].image = "ee.png"
data[4].image1 = "chin.png"
data[4].sound = "kamoo-chin.caf"
data[4].sound1 = "kamoo-chin.mp3"
data[5] = {}
data[5].title = "Kowpa"
data[5].subtitle = "ego"
data[5].image = "leg.png"
data[5].image1 = "leg.png"
data[5].sound = "kowpa-leg.caf"
data[5].sound1 = "kowpa-leg.mp3"
data[6] = {}
data[6].title = "Mae"
data[6].subtitle = "kwa"
data[6].image = "hand.png"
data[6].image1 = "hand.png"
data[6].sound = "mae-hand.caf"
data[6].sound1 = "mae-hand.mp3"
data[7] = {}
data[7].title = "Nodo"
data[7].subtitle = "kwe"
data[7].image = "kwe.png"
data[7].image1 = "throat.png"
data[7].sound = "nodo-throat.caf"
data[7].sound1 = "nodo-throat.mp3"
data[8] = {}
data[8].title = "Matogo"
data[8].subtitle = "kwe"
data[8].image = "kwe.png"
data[8].image1 = "thumb.png"
data[8].sound = "matogo-thumb.caf"
data[8].sound1 = "matogo-thumb.mp3"
data[9] = {}
data[9].title = "Matzehe"
data[9].subtitle = "kwe"
data[9].image = "kwe.png"
data[9].image1 = "elbow.png"
data[9].sound = "matzehe-eblow.caf"
data[9].sound1 = "matzehe-elbow.mp3"
data[10] = {}
data[10].title = "Kuku"
data[10].subtitle = "kwe"
data[10].image = "kwe.png"
data[10].image1 = "foot.png"
data[10].sound = "kuku-foot.caf"
data[10].sound1 = "kuku-foot.mp3"
--Declare button, buttonCover, and buttonImages table
local tableCopy = {}
local buttonImages = {}
--Shuffle data table
--local shuffleSet = function()
--Shuffle data table
math.randomseed (os.time())
local function shuffle(a)
local n = #a
local t
local k
while(n > 0) do
t = a[n]
k = math.random(n)
a[n] = a[k]
a[k] = t
n = n - 1
end
return a
end
local tableCopy = shuffle(data);
local button = {}
local buttonCover = {}
--Choose six random objects from data to be used in game.
local firstSix = {}
for i = 1,6 do
firstSix[i] = tableCopy[i];
end
local buttonImages = {firstSix[1],firstSix[1],firstSix[2],firstSix[2],firstSix[3],firstSix[3],firstSix[4],firstSix[4],firstSix[5],firstSix[5],firstSix[6],firstSix[6]}
--end
--Declare and prime a last button selected variable
local lastButton;-- = display.newImage("1.png");
--lastButton.myName = 1;
--
--Set up simple off-white background
--Notify player if match is found or not
local matchText = display.newText(" ", 0, 0, native.systemFont, 65)
matchText:setReferencePoint(display.CenterReferencePoint)
matchText:setTextColor(255, 255, 255)
matchText.x = _W/2
--
--Set starting point for button grid
local x = -20
local matchesFound = 0;
--Set up game function
local function game(object, event)
if(event.phase == "began") then
if(checkForMatch == false and secondSelect == 0) then
--Flip over first button
buttonCover[object.number].isVisible = false;
audio.play(object.sound);
lastButton = object
checkForMatch = true
elseif(checkForMatch == true and object.number ~= lastButton.number) then
if(secondSelect == 0) then
--Flip over second button
buttonCover[object.number].isVisible = false;
secondSelect = 1;
--If buttons do not match, flip buttons over
if(lastButton.myName ~= object.myName) then
audio.play(object.sound);
timer.performWithDelay(1000,function()
matchText.text = "Ki Nawa'neyoo";
audio.play(ki); end,1)
timer.performWithDelay(2500, function()
matchText.text = " ";
checkForMatch = false;
secondSelect = 0;
buttonCover[lastButton.number].isVisible = true;
buttonCover[object.number].isVisible = true;
end, 1)
--If buttons DO match, remove buttons
elseif(lastButton.myName == object.myName) then
matchText.text = "U " .. object.myName .. " Mayuhoo";
audio.play(u)
timer.performWithDelay(750,function()
audio.play(object.sound); end, 1)
timer.performWithDelay(1500,function()
audio.play(mayuhoo); end, 1)
timer.performWithDelay(2400, function()
matchText.text = " ";
checkForMatch = false;
secondSelect = 0;
lastButton:removeSelf();
object:removeSelf();
buttonCover[lastButton.number]:removeSelf();
buttonCover[object.number]:removeSelf();
matchesFound = matchesFound + 1;
timer.performWithDelay(250, function()
if (matchesFound == 1) then
matchText.text = " Play Again? ";
againBtn.isVisible = true;
-- all display objects must be inserted into group
--group:insert( playBtn )
end
end, 1)
end, 1)
end
end
end
end
end
--]]
-- Touch event listener for background image
--[[
local function onSceneTouch( self, event )
if event.phase == "began" then
storyboard.gotoScene( "scene2", "slideLeft", 800 )
return true
end
end
--]]
-- Called when the scene's view does not exist:
function scene:createScene( event )
local screenGroup = self.view
local image = display.newImageRect( "bg.png", display.contentWidth, display.contentHeight )
image:setReferencePoint( display.TopLeftReferencePoint )
image.x, image.y = 0, 0
screenGroup:insert( image )
local function boardSet()
for count = 1,3 do
x = x + 100 * 2
y = 20 *2
for insideCount = 1,4 do
y = y + 90 * 2
--Assign each image a random location on grid
local temp = math.random(1,#buttonImages)
button[count] = display.newImageRect(buttonImages[temp].image1, 150, 150);
--Position the button
button[count].x = x;
button[count].y = y;
--Give each a button a name
button[count].myName = buttonImages[temp].title
-- Preload the sound file (needed for Android)
--Give each button a sounds
soundID = audio.loadSound(buttonImages[temp].sound1)
button[count].sound = soundID
button[count].sound1 = soundID
button[count].number = totalButtons
--Remove button from buttonImages table
table.remove(buttonImages, temp)
--Set a cover to hide the button image
buttonCover[totalButtons] = display.newImageRect("button.png", 150, 150);
buttonCover[totalButtons].x = x; buttonCover[totalButtons].y = y;
--screenGroup:insert(button[count].)
totalButtons = totalButtons + 1
--Attach listener event to each button
button[count].touch = game
button[count]:addEventListener( "touch", button[count] )
end
end
end
boardSet();
end
-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
againBtn = widget.newButton{
label="Play Again?",
fontSize = 25,
labelColor = { default={255}, over={128} },
default="button1.png",
over="button-over.png",
width=250, height=100,
onRelease = onPlayBtnRelease -- event listener function
}
againBtn:setReferencePoint( display.CenterReferencePoint )
againBtn.x = display.contentWidth * 0.5
againBtn.y = display.contentHeight - 125
againBtn.isVisible = false
print( "1: enterScene event" )
-- remove previous scene's view
end
-- Called when scene is about to move offscreen:
function scene:exitScene( event )
print( "1: exitScene event" )
if againBtn then
matchText.text = " "
againBtn:removeSelf() -- widgets must be manually removed
button = nil
buttonCover = nil
firstSix = nil
data = nil
tableCopy = nil
buttonImages = nil
againBtn = nil
end
end
-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
local screenGroup = self.view
storyboard.removeScene();
--storyboard.purgeScene( "level1" )
print( "((destroying scene 1's view))" )
end
---------------------------------------------------------------------------------
-- END OF YOUR IMPLEMENTATION
---------------------------------------------------------------------------------
-- "createScene" event is dispatched if scene's view does not exist
scene:addEventListener( "createScene", scene )
-- "enterScene" event is dispatched whenever scene transition has finished
scene:addEventListener( "enterScene", scene )
-- "exitScene" event is dispatched before next scene's transition begins
scene:addEventListener( "exitScene", scene )
-- "destroyScene" event is dispatched before view is unloaded, which can be
-- automatically unloaded in low memory situations, or explicitly via a call to
-- storyboard.purgeScene() or storyboard.removeScene().
scene:addEventListener( "destroyScene", scene )
---------------------------------------------------------------------------------
return scene
Yeah, this is simple.
here is an example(assuming that you have implemented storyboard)
function scene:createScene(event)
screenGroup = self.view
local image = display.newImage("image.png")
screenGroup:insert(image)
end
Now everything will go fine :)
Add all the display objects to a group.local myGroup = display.newGroup();
local img = display.newImage("yourimage.png");
myGroup:insert(img);
For example
If you follow this method, all display objects will not be flushed out of memory when you change the screen.
When using corona storyboard you need to add display objects to the group. For example you would need to add all of your display objects into screenGroup in order for them to be removed when you change scenes.

Resources