Corona interstitial tap count - lua

i have a question with corona (LUA), at the moment im showing interstitial ad when tap button occurs. I have this and its working (sometimes takes like 5-10-15 seconds to load and ad, i dont know why:
local ads = require("ads")
local interstitialAppID = "ca-app-pub-xxxxxxxxxx/xxxxxxxx21"
local testMode = true
local adProvider = "admob"
local function adListener( event )
if ( event.isError ) then
print ( "Error en el anuncio!", msg )
elseif ( event.phase == "loaded") then
print ( "Anuncio cargado!", msg )
elseif ( event.phase == "shown") then
print ( "Cargando nuevo anuncio!", msg )
ads.load ("interstitial", { appId = interstitialAppID, testMode = isTestMode } )
end
end
ads.init("admob", interstitialAppID, adListener )
ads.load ("interstitial", { appId = interstitialAppID, testMode = isTestMode } )
-- INTERSTITIAL AD
local function Adinterstatial( self, event )
ads.show( "interstitial", { appId = interstitialAppID, testMode = isTestMode
} )
end
local test = display.newImageRect( "Lore/0.png", 50, 50 )
test.x = 150
test.y = 150
test.tap = Adinterstatial
test:addEventListener( "tap" )
I want to do this for example: every 20 taps (on all the app) shows an interistitial ad.
Is this possible?
How i can do it?
Thanks.

You can add a Runtime tap event. This will get all taps on the screen, it does not matter where or what object was tapped. For example:
local numTaps = 0
local function countTaps()
numTaps = numTaps + 1
if numTaps % 20 == 0 then
-- Show the add here.
end
end
Runtime:addEventListener("tap", countTaps)
The % gets the remaindeer of the division between numTaps and 20. This means that it will be 0 every 20 taps.

Related

Refresh menu scene after data change (Corona SDK)

I have just implemented adbuddiz reward video in my app and it works as expected but I have a slight challenge.
After watching the video, it triggers the "didComplete" event for adbuddiz where it adds the needed value into a json file.
The challenge now is the value does not automatically reflect on the screen except I go out of the scene and go back before the new value shows.
Is there a way to refresh the screen so the new value appears immediately?
Note: This all happens on a button click
local savecount = Lib.getSaveValue("savecount")
-- Events (rewarded video)
local function listenerRewardedVideo( event )
if event.value == "didFetch" then
print( "didFetch" )
end
if event.value == "didComplete" then
print( "didComplete" )
-- Reward user here
print ("savecount")
savecount = savecount + 1
Lib.setSaveValue("savecount", savecount, true);
local alert = native.showAlert("Successful","Count saved successfully!", {"OK"})
end
if event.value == "didNotComplete" then
print( "didNotComplete" )
end
if event.value == "didFail" then
print( "didFail - " .. event.detail )
end
end
Runtime:addEventListener( "AdBuddizRewardedVideoEvent", listenerRewardedVideo )
This displays the value on the menu scene
label_saveme = display.newText({parent=uiGroup, text=savecount, x=0, y=0, font=native.systemFont, fontSize=24})
label_saveme.xScale = 0.92
label_saveme.x = button_buysaveme.x + 22
label_saveme.y = button_buysaveme.y + 6
label_saveme:setFillColor(255/255, 255/255, 255/255)
label_saveme.alpha = 0.4
uiGroup:insert(label_saveme)
Thanks
So you want to put savecount value on label_saveme?
if your local label_save me on the same file as your button click code, change the "didComplete"
if event.value == "didComplete" then
print( "didComplete" )
-- Reward user here
print ("savecount")
savecount = savecount + 1
label_saveme.text = savecount
Lib.setSaveValue("savecount", savecount, true);
local alert = native.showAlert("Successful","Count saved successfully!", {"OK"})
end

How to destroy a ADMOB ad

when i use the underneath code in my main.lua file it displays the ad as i want it to be.
but when i add "ads.hide()" (the ad stay on every scene) in the "exitScene" scene section i get this error in the terminal " attempt to index global 'ads' (a nil value)" which i understand as the ads don't display in the simulator but when i open the app op my phone (galaxy s4) non of the buttons respond, and it just stay on the main.lua file/scene
local provider = "admob"
local appID = "**********"
local ads = require "ads"
local screenGroup = self.view
local statusText = display.newText( "", 0, 0, native.systemFontBold, 22 )
statusText:setTextColor( 255 )
statusText:setReferencePoint( display.CenterReferencePoint )
statusText.x, statusText.y = display.contentWidth * 0.5, 160
local showAd
local function adListener( event )
local msg = event.response
print("Message received from the ads library: ", msg)
if event.isError then
statusText:setTextColor( 255, 0, 0 )
statusText.text = "Error Loading Ad"
statusText.x = display.contentWidth * 0.5
local screenGroup = self.view
showAd( "banner" )
else
end
end
if appID then
ads.init( provider, appID, adListener )
end
local sysModel = system.getInfo("model")
local sysEnv = system.getInfo("environment")
showAd = function( adType )
local screenGroup = self.view
local adX, adY = display.screenOriginX, 400
statusText.text = ""
ads.show( adType, { x=adX, y=adY } )
end
if sysEnv == "simulator" then
else
local screenGroup = self.view
showAd( "banner" )
end
Hi how can i close or destroy a "admob" ad on screen change ?
You need to require ads in every scene you create
Add this line to every Lua file that are using the ads plugin
local ads = require("ads")
ads.hide( )
ads:removeSelf()
ads=nil
you can insert above into any event listener or something else.
You need to call this function in every screen.
if ads then
ads.hide()
end
Note: When you are generating dynamic ads then there are time duration between the ads.
So if the ads is on the screen it will hide otherwise not.
But when you not check the if condition and move to next scene the ads will load again.

Images doesn´t appear in storyboard Corona SDK

I am doing a game in corona SDK, but I have this little problem.
I have a menu with a button. If I press it, it sends me to the first level of my game.
When I pass the final level, the game return me to the menu. Bur, if I start playing the first again, my images doesn´t appear.
The images are balls, and to pass the level, you have to eliminate all the balls. To do this, I use:
ball:removeSlef()
ball = nil
But, I don´t think that this is the problem, because I eliminate this lines, and it doesn´t work.
The images are create in scene:createScene function, and insert in the Group.
I short the code of the first level to be understood.
local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
local physics = require "physics"
physics.start(); physics.pause()
physics.setGravity( 0, 0 )
local cont = 0
local bur = {}
function eliminar1( event )
if (cont == 0) and (event.phase == "began") then
event.target:removeSelf()
bur[1] = nil
cont = cont + 1
end
end
function eliminar2( event )
if (cont == 1) and (event.phase == "began") then
bur[2]:removeSelf()
bur[2] = nil
cont = cont + 1
end
end
function eliminar3( event )
if (cont == 2) and (event.phase == "began") then
bur[3]:removeSelf()
bur[3] = nil
storyboard.gotoScene( "levels.1.level2" )
end
end
function scene:createScene ( event )
local screenGroup = self.view
for i = 1,3 do
bur[i] = display.newImage("irudiak/"..i..".png")
bur[i]:translate(math.random(0,280), math.random(0,400) )
physics.addBody( bur[i], {bounce = 0.3 } )
bur[i]:setLinearVelocity(math.random(-50,50), math.random(-50,50) )
screenGroup:insert(bur[i])
end
bur[1]:addEventListener("touch", eliminar1)
bur[2]:addEventListener("touch", eliminar2)
bur[3]:addEventListener("touch", eliminar3)
end
function scene:enterScene( event )
local screenGroup = self.view
physics.start()
end
function scene:exitScene( event )
local screenGroup = self.view
physics.stop()
end
function scene:destroyScene( event )
local screenGroup = self.view
package.loaded[physics] = nil
physics = nil
end
return scene
createScene is ran only first time when you gotoScene. Every next time only willEnterScene and enterScene are played. To play createScene again you have to remove it (storyboard.removeScene() I guess). Or you can move some stuff you need to willEnterScene. For more detailed info you can watch this: http://www.coronalabs.com/blog/2013/08/20/tutorial-reloading-storyboard-scenes/

corona sdk - scene keep old items

I'm using director , to move from one scene to another. I have a problem that the buttons and text fields from intor still in the top of screen when moving to any scene.
How to remove items (text fields, btns from intro.lua screen) before move to next scene?
enter code here
-- into.lua
module(..., package.seeall)
function new()
--
-- Project: NativeKeyboard2
--
local widget = require( "widget" )
require("hijacks")
local tHeight -- forward reference
-------------------------------------------
-- General event handler for fields
-------------------------------------------
-- You could also assign different handlers for each textfield
local function fieldHandler( textField )
return function( event )
if ( "began" == event.phase ) then
-- This is the "keyboard has appeared" event
-- In some cases you may want to adjust the interface when the keyboard appears.
elseif ( "ended" == event.phase ) then
-- This event is called when the user stops editing a field: for example, when they touch a different field
elseif ( "editing" == event.phase ) then
elseif ( "submitted" == event.phase ) then
-- This event occurs when the user presses the "return" key (if available) on the onscreen keyboard
print( textField().text )
-- Hide keyboard
native.setKeyboardFocus( nil )
end
end
end
-- Predefine local objects for use later
local nameField, phoneField
local fields = display.newGroup()
-------------------------------------------
-- *** Create native input textfields ***
-------------------------------------------
-- Note: currently this feature works in device builds or Xcode simulator builds only (also works on Corona Mac Simulator)
local isAndroid = "Android" == system.getInfo("platformName")
local inputFontSize = 18
local inputFontHeight = 30
tHeight = 30
if isAndroid then
-- Android text fields have more chrome. It's either make them bigger, or make the font smaller.
-- We'll do both
inputFontSize = 14
inputFontHeight = 42
tHeight = 40
end
nameField = native.newTextField( 40, 120, 200, tHeight )
nameField.font = native.newFont( native.systemFontBold, inputFontSize )
nameField:addEventListener( "userInput", fieldHandler( function() return nameField end ) )
phoneField = native.newTextField( 40, 160, 200, tHeight )
phoneField.font = native.newFont( native.systemFontBold, inputFontSize )
phoneField.inputType = "phone"
phoneField:addEventListener( "userInput", fieldHandler( function() return phoneField end ) )
-- Add fields to our new group
fields:insert(nameField)
fields:insert(phoneField)
-------------------------------------------
-- *** Add field labels ***
-------------------------------------------
local defaultLabel = display.newText( "الاسم", 250, 120, native.systemFont, 18 )
defaultLabel:setTextColor( 255, 0, 0 )
local defaultLabel = display.newText( "رقم الجوال", 250, 160, native.systemFont, 18 )
defaultLabel:setTextColor( 255, 0, 0 )
-- -------------------------------------------
-- -- Create a Background touch event
-- -------------------------------------------
local listener = function( event )
-- Hide keyboard
print("tap pressed")
native.setKeyboardFocus( nil )
return true
end
-- Determine if running on Corona Simulator
--
local isSimulator = "simulator" == system.getInfo("environment")
if system.getInfo( "platformName" ) == "Mac OS X" then isSimulator = false; end
-- Native Text Fields not supported on Simulator
--
if isSimulator then
msg = display.newText( "الرجاء ادخال اسمك ورقم جوالك", 0, 280, native.systemFontBold, 12 )
msg.x = display.contentWidth/2 -- center title
msg:setTextColor( 255,0,0 )
end
-- -- Add listener to background for user "tap"
-- bkgd:addEventListener( "tap", listener )
-- display.remove( obj )
-- obj = nil
local introGroup = display.newGroup();
local background = display.newImage("graphics/intro_background.png")
local begin = display.newImage("graphics/begin_button.png")
begin.x = 160;
begin.y = 400;
begin.scene = "menu";
introGroup:insert(background);
introGroup:insert(begin);
begin:addEventListener("touch", changeScene)
return introGroup;
end
Corona provides a very good feature that is "Storyboard".I am giving you a brief explanation, Try this -
Storyboard - It is a scene (e.g. "screens" or "views") management library that provides developers an easy way to create and transition between scene modules in a Corona SDK app.
Syntax -
local storyboard = require "storyboard"
Example -
local scene1 = storyboard.newScene( "name of the Scene" )
Here are the different events used in the Storyboard -
1- Create Scene -
-- Called when the scene's view does not exist:
function scene:createScene( event )
local group = self.view
end
2- Enter Scene -
-- Called immediately after scene has moved onscreen:
function scene:enterScene( event )
local group = self.view
end
3- Exit Scene -
-- Called when scene is about to move offscreen:
function scene:exitScene( event )
local group = self.view
end
4 - Destroy Scene -
-- Called prior to the removal of scene's "view" (display group)
function scene:destroyScene( event )
local group = self.view
end
It will help you.

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