Restart my game with composer

I would like to use composer to restart my game. But the code of my game it’s all in a file. Can I restart it just by creating and adicional restart.lua file?

I already tried my best using the composer with 2 files. Like starts at main.lua -> restart.lua -> main.lua but the main.lua won’t apear after I change my code to composer things. Before trying this the game worked fine but I didn’t know how I would make a restart function.

There is my code. What I need to change to make the restart work or there is another easier way do to it?

display.setStatusBar( display.HiddenStatusBar ) local physics = require "physics" physics.start() physics.setGravity( 0, 0 ) local composerlocal composer = require( "composer" ) local scene = composer.newScene() function scene:create( event ) local sceneGroup = self.view end function scene:show( event ) local sceneGroup = self.view local phase = event.phase if ( phase == "will" ) then elseif ( phase == "did" ) then -- Variables local centerX = display.contentCenterX local centerY = display.contentCenterY local xmin = display.screenOriginX - 50 local xmax = display.contentWidth + 50 local ymin = display.screenOriginY - 50 local ymax = display.contentHeight + 50 local spawnIncreaseTimer local spawnNumber=0 local speedBump = 0 local earthRotation local gametimer local nSeconds = 0 local nMins = 0 local nHours = 0 local numSec = 0 local nSecs = 0 local timervalue = 0 local spawnTimer local firebullet local i = 0 local highscore = 0 local blast = audio.loadSound("media/blast.wav") local gameover = audio.loadSound("media/gameover.wav") local backgroundMusic = audio.loadStream("media/backgroundmusic.wav") local backgroundMusicChannel = audio.play( backgroundMusic, { channel=1, loops=-1, fadein=5000 } ) -- Functions local bg = display.newImage("images/starbg.png") bg.x = centerX bg.y = centerY screenGroup:insert(bg) local logo = display.newImage("images/Logo.png") logo.x = centerX logo.y = centerY screenGroup:insert(logo) local begin = display.newImage("images/start.png") begin.x = centerX + 50 begin.y = centerY + 45 screenGroup:insert(begin) -- Esta função aumenta, de 10 em 10 segundos, o numero de asteroides que aparecem por cada 2 segundos local function spawnIncrease() spawnNumber=spawnNumber+1 spawnIncreaseTimer = timer.performWithDelay( 15000, spawnIncrease) end -- Esta função adiciona o score ao display local function startGame() scoreText = display.newText( "Score", 0, 0, "Helvetica", 22 ) scoreText2 = display.newText("0", 0, 0, "Helvetica", 22) scoreText.x = display.screenOriginX + 50 scoreText.y = display.screenOriginY + 20 scoreText2.x = display.screenOriginX + 50 scoreText2.y = display.screenOriginY + 45 screenGroup:insert(scoreText) screenGroup:insert(scoreText2) end -- Esta função adiciona o timer ao display local function timerGame() timerTxt = display.newText("Time", 0, 0, "Helvetica", 22) timerTxt2 = display.newText("00:00:00", 0, 0, "Helvetica", 22) timerTxt.x = display.contentWidth - 15 timerTxt.y = display.screenOriginY + 20 timerTxt2.x = display.contentWidth - 15 timerTxt2.y = display.screenOriginY + 45 screenGroup:insert(timerTxt) screenGroup:insert(timerTxt2) end -- Esta função dá inicio ao timer local function timeCount() nSeconds = timervalue if nSeconds == 0 then timerTxt2.text = "00:00:00"; else nHours = string.format("%02.f", math.floor(nSeconds/3600)); nMins = string.format("%02.f", math.floor(nSeconds/60 - (nHours\*60))); nSecs = string.format("%02.f", math.floor(nSeconds - nHours\*3600 - nMins \*60)); timerTxt2.text = nHours..":"..nMins..":"..nSecs end timervalue = timervalue + 1 gametimer = timer.performWithDelay( 1000, timeCount) end -- Esta função faz parar o aumento de asteroides que aparecem local function stopSpawnIncrease() timer.cancel( spawnIncreaseTimer ) end -- Esta função dá inicio ao jogo local function go(event) display.remove(logo) display.remove(begin) print(highscore) local planet = display.newImage("images/terra.png") planet.x = centerX planet.y = centerY planet:scale(4, 4) transition.to( planet, { time = 200, xScale = 1, yScale = 1} ) screenGroup:insert(planet) local asteroidgroup = display.newGroup() startGame() timerGame() timeCount() spawnIncrease() local function firebullet(event) local bullet = display.newCircle( planet.x, planet.y, 2 ) bullet.class = "bullet" physics.addBody( bullet,"dynamic", { density=3.0, friction=0.5, bounce=0.05 } ) bullet.isBullet = true bullet.type = "bullet" local deltax = event.x - planet.x local deltay = event.y - planet.y local bulletangle = math.atan2(deltay, deltax) local xforce = (math.cos(bulletangle))\*40 local yforce = (math.sin(bulletangle))\*40 bullet:applyForce( xforce, yforce, bullet.x, bullet.y ) end Runtime:addEventListener ( "tap", firebullet) local lost -- Esta função faz com que os asteroides apareçam local function spawn() for i=1,spawnNumber do local allAsteroids = {"images/enemy1.1.png" , "images/enemy2.1.png"} asteroids = display.newImage(allAsteroids[math.random(#allAsteroids)]) asteroids.x = math.random(xmin, xmax) asteroids.y = math.random(ymin, ymax) asteroidgroup:insert(asteroids) screenGroup:insert(asteroids) local pentagonShape = { 0,-13, 13,-5, 13,13, -13,13, -13,-5 } asteroids.class = "asteroid" physics.addBody(asteroids, "static", {shape = pentagonShape, density=1.0, friction=0.3, bounce=0.2}) asteroids.isSensor = true asteroids.type = "asteroids" if (asteroids.x \> display.screenOriginX and asteroids.x \< display.contentWidth + 1 and asteroids.y \> display.screenOriginY and asteroids.y \< display.contentHeight + 1) then display.remove(asteroids) else transition.to( asteroids, { time=math.random(3000-speedBump , 5000-speedBump), y = centerY, x = centerX , rotation = math.random(50 , 180), onComplete = lost}) speedBump = speedBump + 15 end end spawnTimer = timer.performWithDelay( 2000, spawn) end timer.performWithDelay(5000, spawn) function lost() audio.play(gameover) local path = system.pathForFile( "myfile.txt", system.DocumentsDirectory ) local file, errorString = io.open( path, "r" ) if not file then print( "File error: " .. errorString ) else local highscore = file:read( "\*a" ) io.close( file ) Runtime:removeEventListener ("tap", firebullet) timer.cancel(spawnTimer) display.remove(planet) transition.cancel(asteroids) display.remove(asteroidgroup) asteroidgroup = nil display.remove(scoreText) display.remove(scoreText2) timer.cancel(gametimer) display.remove(timerTxt) display.remove(timerTxt2) losttxt = display.newText( "You Lose", 0, 0, "Helvetica", 30) losttxt.x = centerX losttxt.y = 40 screenGroup:insert(losttxt) finalscore = display.newText( "Final Score", 0, 0, "Helvetica", 22 ) finalscore.x = centerX + 150 finalscore.y = 90 screenGroup:insert(finalscore) finalscore2 = display.newText( "0", 0, 0, "Helvetica", 20) finalscore2.x = centerX + 150 finalscore2.y = 115 screenGroup:insert(finalscore2) finalscore2.text = normalscore highscore2 = display.newText( "High Score", 0, 0, "Helvetica", 22 ) highscore2.x = centerX - 150 highscore2.y = 90 screenGroup:insert(highscore2) timeplayed = display.newText("Time Played", 0, 0, "Helvetica", 22) timeplayed.x = centerX timeplayed.y = 140 screenGroup:insert(timeplayed) timeplayed2 = display.newText(nHours..":"..nMins..":"..nSecs, 0, 0, "Helvetica", 20) timeplayed2.x = centerX timeplayed2.y = 165 screenGroup:insert(timeplayed2) retry = display.newText("Retry", 0, 0, "Helvetica", 30) retry.x = centerX retry.y = display.contentHeight - 50 screenGroup:insert(retry) local highscore4 = display.newText("0", display.screenOriginX - 100, display.screenOriginY - 100, "Helvetica", 22) screenGroup:insert(highscore4) highscore4.text = highscore highscore = tonumber(highscore) if (normalscore \>= highscore) then highscore = normalscore else highscore = highscore end highscore4.text = highscore highscore3 = display.newText( highscore , 0, 0, "Helvetica", 20) highscore3.x = centerX - 150 highscore3.y = 115 print(highscore4.text) local saveData = highscore4.text local path = system.pathForFile( "myfile.txt", system.DocumentsDirectory ) local file, errorString = io.open( path, "w" ) if not file then print( "File error: " .. errorString ) else file:write( saveData ) io.close( file ) end end local function gamerestart() function scene:hide( event ) local sceneGroup = self.view local phase = event.phase if ( phase == "will" ) then elseif ( phase == "did" ) then composer.gotoScene("restart") end end end end retry:addEventListener ( "tap", gamerestart) end begin:addEventListener ( "tap", go) local function onGlobalCollision( event ) if ( event.phase == "began" ) then if (event.object1.type == "bullet" and event.object2.class == "asteroid") or (event.object2.type == "bullet" and event.object1.class == "asteroid") then local myAsteroid if event.object1.type == "bullet" then myAsteroid = event.object2 myBullet = event.object1 transition.cancel(event.object2) else myAsteroid = event.object1 myBullet = event.object2 transition.cancel(event.object1) end audio.play(blast) display.remove(myAsteroid) display.remove(myBullet) normalscore = i + 1 scoreText2.text = i + 1 i = i + 1 end end end Runtime:addEventListener( "collision", onGlobalCollision ) end end function scene:destroy() end scene:addEventListener( "create", scene ) scene:addEventListener( "show", scene ) scene:addEventListener( "hide", scene ) scene:addEventListener( "destroy", scene ) return scene

The issue is trying to reload a scene from the same lua file. Try putting the relevant objects in a function to delete & create them. In this way, you don’t need to call ‘composer.goto’ to reload the whole scene. You just need to destroy the relevant objects and re-create them. That’s what I do for my re-use scenes.

Also try this :

main.lua -> restart.lua -> Wait for 1-second -> main.lua

Ensure the ‘destroy scene’ is called. 

Check out this feature : ‘recycle’ scene. See https://docs.coronalabs.com/api/library/composer/recycleOnSceneChange.html

Generally speaking, main.lua should not be a scene file. It’s best for initializing things. Generally speaking it should go:

main.lua -> game.lua -> restart.lua -> game.lua

In main.lua your basically going to have:

local composer = require(“composer”)

composer.gotoScene(“game”)

and any other one time initialization things. For instance you don’t want to initialize IAP or system events multiple times. If you’re using ads you only want to initialize them once. Turn off your status bar, seed the random number generator, etc. is stuff for main.lua.

Then game.lua and restart.lua need to use the composer template and move your game code to the proper place. That is, local functions that need to be used scene wide and scene wide variables should be in the main chunk of the scene. You create all your objects (perhaps other than things that get spawned during play) in the scene:create() function. You start your timers and transitions and such in scene:show().

Rob

The issue is trying to reload a scene from the same lua file. Try putting the relevant objects in a function to delete & create them. In this way, you don’t need to call ‘composer.goto’ to reload the whole scene. You just need to destroy the relevant objects and re-create them. That’s what I do for my re-use scenes.

Also try this :

main.lua -> restart.lua -> Wait for 1-second -> main.lua

Ensure the ‘destroy scene’ is called. 

Check out this feature : ‘recycle’ scene. See https://docs.coronalabs.com/api/library/composer/recycleOnSceneChange.html

Generally speaking, main.lua should not be a scene file. It’s best for initializing things. Generally speaking it should go:

main.lua -> game.lua -> restart.lua -> game.lua

In main.lua your basically going to have:

local composer = require(“composer”)

composer.gotoScene(“game”)

and any other one time initialization things. For instance you don’t want to initialize IAP or system events multiple times. If you’re using ads you only want to initialize them once. Turn off your status bar, seed the random number generator, etc. is stuff for main.lua.

Then game.lua and restart.lua need to use the composer template and move your game code to the proper place. That is, local functions that need to be used scene wide and scene wide variables should be in the main chunk of the scene. You create all your objects (perhaps other than things that get spawned during play) in the scene:create() function. You start your timers and transitions and such in scene:show().

Rob