The Names spawn randomsly

Hi there,

I need a help to realyze this function.

In my game I have a spinning wheel and i would like that when the wheel stops a random name of a player will spawn on the screen but when the wheel restart spinning (with a touch event) the name should disappear, can anyone help me please!

Thanks

Hi.

This could be a couple questions. One is just the display part of it, but that’s fairly basic usage of display.newText() and text:removeSelf(), so I’m going to assume it’s not where you’re having trouble.

If coming up with the string is the problem, you’ll need to store a list somewhere, say in a Lua array. Populating it will take a while, but is inevitable. There are probably lists already out there, but if not, you could use a tool like this: List of Random Names (first relevant thing I found when I searched, and seems decent). Just export as text and stuff into an array, then add quotes and commas. Do this a bunch of times to build a big list, removing duplicates if you care. Later if you add user-provided names you can read from a file.

Then just have stuff like:

local Names = { "Adam", -- could be tables to add metadata like male / female, nationality, is a nickname, etc. "Alice", "Amy", -- and so on } -- other code local CurrentName local function PutUpRandomName (group) local name = Names[math.random(#Names)] display.remove(CurrentName) -- in case some name is still showing CurrentName = display.newText(group, name, display.contentCenterX, display.contentCenterY, native.systemFontBold, 50) -- set color, apply transitions, etc. end local function RemoveName () if CurrentName then -- fade the old name out transition.to(CurrentName, { alpha = 0, time = 1000, onComplete = display.remove }) end CurrentName = nil end

and call them where appropriate.

Hi StarCrunch,

Thanks for your help.

And if i wuold like to write the player’s names in the main menu, using a text box, how I can do that? Is ti possible?

For example:

Player1 = --type the name of the player here

Player2 = --type the name of the player here

and so on…

Sure, just use one of these:

native.newTextBox()

native.newTextField()

Make sure to read the “Gotchas”, just in case those would affect you.

Hi StarCrunch,

I’m still in trouble with my project, I’m trying to use the native.newTextField() method but.

  1. I don’t know how to join my players.lua (where i should writhe the names) and my game.lua (where it should spawn       the names).

  2. With the putUpRandomNames function whe i stop the wheel nothing happends or it’s not displayed and no errors

This is my players.lua nativeNewText code:

[lua] local createPlayer = display.newEmbossedText( sceneGroup, “Players”, centerX, 40, “youmurderer”, 60 )

createPlayer:setFillColor( 0.8,0.2,0.2  )

local color = 

{

   highlight = { r=1, g=1, b=1 },

   shadow = { r=0.8, g=0.2, b=0.2 }

}

createPlayer:setEmbossColor( color )

local function onUserPlayerInput( event )

local phase = event.phase

if “editing” == phase then

game.name = event.text

elseif “submitted” == phase or “ended” == phase then

native.setKeyboardFocus( nil )

end

end

– The Player’s name field

local PlayerField = native.newTextField( 20, 50, 280, 30 )

PlayerField.x = display.contentCenterX

PlayerField.y = createPlayer.y + createPlayer.contentHeight + 15

PlayerField.placeholder = “Player Name”

PlayerField:addEventListener( “userInput”, onUserPlayerInput )

PlayerField:setReturnKey( “done” )

PlayerField.inputType = “name”

self.PlayerField = PlayerField

[/lua]

When i try to write a player’s name it gave me an error. If you need more code or you need to check my files just ask.

Please help

P.S.

I’m sorry for my bad english

In case you still need it, Rob actually just put up a list of the text tutorials last night:

Tutorial Treasury: Native text input fields/boxes

The clean way to share code will be to make modules. It sounds like you’ve been doing so, since you have separate files.

You should put game.name somewhere (per player) and then add a function or two to players.lua to get those names. Basically, update your current structure to something like:

-- updated players.lua local M = {} -- module table -- Add most / all of your current code here -- Add some utility functions -- Get a player's name -- This is just an example. Write this in whatever way is nicest for you. -- You could even just make one function per player. function M.GetName (which) if which == "player1" then return Player1Name elseif which == "player2" then return Player2Name -- etc. end end return M -- export your module

Then in game.lua , do a require(“players”) and call your functions somewhere appropriate:

local players = require("players") -- Your code... local Name = players.GetName("player1") -- or add it to an array, if following the earlier approach -- in that case, you should also remove it, post-level -- do stuff with name

Thanks for the quick answer!

I’ll modify my project and i’ll continue to crash my head on the screen :wink: and keep the post updated.

P.S. 

In the post of my code, at line 15, you can find what you was talking about ( game.name )

Hello there,

after many attempts these are my issues:

  1. In the editing phase i got an error: attempt to index global ‘src’ (a nil value), ‘src’ is the folder where I got players.lua and game.lua

     

code:

[lua] local function onUserPlayerInput( event )

local phase = event.phase

if “editing” == phase then

src.game.name = event.text

elseif “submitted” == phase or “ended” == phase then

native.setKeyboardFocus( nil )

end

end  [/lua]

  1. When I try to enter in the game scene i got an error: attempt to call field ‘GetName’ (a nil value)

code:

[lua] local Name = players.GetName(“player1”) [/lua]

And here is part of my players.lua code:

[lua] 

– Create a module table

local M = {"…"}

– Create a label showing which scene this is

local label = display.newEmbossedText( sceneGroup, “Players”, centerX, 40, “youmurderer”, 60 )

label:setFillColor( 0.8,0.2,0.2  )

local color =

{

highlight = { r=1, g=1, b=1 },

shadow = { r=0.8, g=0.2, b=0.2 }

}

label:setEmbossColor( color )

    – Create a label for the text field

local function onUserPlayerInput( event )

local phase = event.phase

if “editing” == phase then

src.game.name = event.text

elseif “submitted” == phase or “ended” == phase then

native.setKeyboardFocus( nil )

end

end

– The Player’s name field

local Player1Field = native.newTextField( 20, 50, 280, 30 )

      Player1Field.x = display.contentCenterX

 Player1Field.y = label.y + label.contentHeight + 15

 Player1Field.placeholder = “Player1 Name”

 Player1Field:addEventListener( “userInput”, onUserPlayerInput )

 Player1Field:setReturnKey( “done” )

 Player1Field.inputType = “name”

 self.Player1Field = Player1Field

local Player2Field = native.newTextField( 20, 50, 280, 30 )

   Player2Field.x = display.contentCenterX

 Player2Field.y = label.y + label.contentHeight + 55

 Player2Field.placeholder = “Player2 Name”

 Player2Field:addEventListener( “userInput”, onUserPlayerInput )

 Player2Field:setReturnKey( “done” )

 Player2Field.inputType = “name”

 self.Player2Field = Player2Field

local Player3Field = native.newTextField( 20, 50, 280, 30 )

 Player3Field.x = display.contentCenterX

 Player3Field.y = label.y + label.contentHeight + 95

 Player3Field.placeholder = “Player3 Name”

 Player3Field:addEventListener( “userInput”, onUserPlayerInput )

 Player3Field:setReturnKey( “done” )

 Player3Field.inputType = “name”

 self.Player3Field = Player3Field

local Player4Field = native.newTextField( 20, 50, 280, 30 )

   Player4Field.x = display.contentCenterX

 Player4Field.y = label.y + label.contentHeight + 135

 Player4Field.placeholder = “Player4 Name”

 Player4Field:addEventListener( “userInput”, onUserPlayerInput )

 Player4Field:setReturnKey( “done” )

 Player4Field.inputType = “name”

 self.Player4Field = Player4Field

local Player5Field = native.newTextField( 20, 50, 280, 30 )

      Player5Field.x = display.contentCenterX

 Player5Field.y = label.y + label.contentHeight + 175

 Player5Field.placeholder = “Player5 Name”

 Player5Field:addEventListener( “userInput”, onUserPlayerInput )

 Player5Field:setReturnKey( “done” )

 Player5Field.inputType = “name”

 self.Player5Field = Player5Field

local Player6Field = native.newTextField( 20, 50, 280, 30 )

 Player6Field.x = display.contentCenterX

 Player6Field.y = label.y + label.contentHeight + 215

 Player6Field.placeholder = “Player6 Name”

 Player6Field:addEventListener( “userInput”, onUserPlayerInput )

 Player6Field:setReturnKey( “done” )

 Player6Field.inputType = “name”

 self.Player6Field = Player6Field

local Player7Field = native.newTextField( 20, 50, 280, 30 )

 Player7Field.x = display.contentCenterX

 Player7Field.y = label.y + label.contentHeight + 255

 Player7Field.placeholder = “Player7 Name”

 Player7Field:addEventListener( “userInput”, onUserPlayerInput )

 Player7Field:setReturnKey( “done” )

 Player7Field.inputType = “name”

 self.Player7Field = Player7Field

local Player8Field = native.newTextField( 20, 50, 280, 30 )

 Player8Field.x = display.contentCenterX

 Player8Field.y = label.y + label.contentHeight + 295

 Player8Field.placeholder = “Player8 Name”

 Player8Field:addEventListener( “userInput”, onUserPlayerInput )

 Player8Field:setReturnKey( “done” )

 Player8Field.inputType = “name”

 self.Player8Field = Player8Field

     – Get a player’s name

function M.GetName(which)

if which == “player1” then

return Player1Field

elseif which == “player2” then

return Player2Field

elseif which == “player3” then

return Player3Field

elseif which == “player4” then

return Player4Field

elseif which == “player5” then

return Player5Field

elseif which == “player6” then

return Player6Field

elseif which == “player7” then

return Player7Field

elseif which == “player8” then

return Player8Field

end

end

[/lua]

Hi.

A few things.

You should return your module table at the end:

return M

Otherwise you’ll just get (at most) true when you do require(“x”).

If your modules are in a directory, you should do this instead:

local game = require("src.game") local players = require("src.players")

In the code, you would still just use your variable’s name, game or players in this case.

Right now, it looks like you’re assigning the name directly to the same variable ( src.game.name , above) from any text field. But maybe instead it would be cleaner to just ask for it on demand, as for example

local name = players.GetName("player1").text -- use name

Ok StarCrunch thanks for your help.

Now after the last updates my project gave back an error when i try to open the game.lua or players.lua:

loop or previous error loading module ‘src.players’

loop or previous error loading module ‘src.game’

Okay, this happens when module A requires module B, but module B also requires module A. Also, if you dropped in my example verbatim, the module might be trying to require() itself! Thus the “loop”.

I haven’t seen all of your code, of course, but I suspect if you follow my suggestion in the previous post (get the name on demand, instead of assigning it directly in the textbox), you could structure it as:

main.lua - require src.game ; if necessary, also src.players

src/game.lua - require src.players

src/players.lua - no requiring

(If you do have legitimate loops, there are ways around them. But this doesn’t look like one of those cases.)

Ok now i can load the modules,

but when load the game.lua scene I’v got an error: attempt to call field ‘GetName’ (a nil value)

Hmm, this sounds like some little problem happened somewhere.

Make sure you have

local players = require("src.players")

and later,

local name = players.GetName("player1") -- or something like this, anyway

in game.lua.

That’s one guess, either that you accidentally require()'d into the wrong variable or, instead, tried calling from the wrong one.

You didn’t accidentally make GetName() local, did you? Or forget to put it in M? Or maybe you were moving things around and put it somewhere else ( game.lua?) by mistake?

[lua]

require “src.players”

local players       = require(“src.players”)

local composer = require( “composer” )

local scene     = composer.newScene()

local physics = require(“physics”)

      physics.start()

      physics.setGravity(0,0)

      physics.setDrawMode(“normal”)


– LOCALS –


– Variables

local w = display.contentWidth

local h = display.contentHeight

local centerX = display.contentCenterX

local centerY = display.contentCenterY

– Forward Declarations

local onBack

– Useful Localizations

local mAbs              = math.abs

local mRand             = math.random

local mDeg              = math.deg

local mRad              = math.rad

local mCos              = math.cos

local mSin              = math.sin

local mAcos             = math.acos

local mAsin             = math.asin

local mSqrt             = math.sqrt

local mCeil             = math.ceil

local mFloor            = math.floor

local mAtan2            = math.atan2

local mPi               = math.pi

local getInfo           = system.getInfo

local getTimer          = system.getTimer

local strMatch          = string.match

local strFormat         = string.format

local pairs             = pairs


– Scene Methods




function scene:create( event )

    local sceneGroup = self.view

local background = display.newImage(sceneGroup, “background.png”)

      background.x = display.contentCenterX

      background.y = display.contentCenterY

local arms = display.newImage(sceneGroup, “arms1.png”, true)

      arms.x = display.contentWidth - 134

      arms.y = display.contentHeight - 290

local nail = display.newCircle(sceneGroup, 124.91, 212, 4)

      physics.addBody(nail, “static”,{bounce=0, friction=0.2, radius=4})

local wheel = display.newImage(sceneGroup, “wheel1.png”, true)

      wheel.x = display.contentWidth - 195

      wheel.y = display.contentHeight - 268

      physics.addBody(wheel, “dynamic”,{bounce=0, friction=0.2, radius=1})

      wheel.angularDamping = 0.4

local skull = display.newImage(sceneGroup, “skull1.png”, true)

      skull.x = display.contentWidth - 190

      skull.y = display.contentHeight - 379

local Name = players.GetName(“player1”).text

local label = display.newEmbossedText( sceneGroup, “Presents…”, centerX, 280, “youmurderer”, 40 )

      label:setFillColor( 0.8,0.2,0.2 )

local color =

    {

        highlight = { r=1, g=1, b=1 },

        shadow = { r=0.8, g=0.2, b=0.2 }

    }

    label:setEmbossColor( color )

    display.remove(label)

local joint = physics.newJoint(“pivot”, wheel, nail, 124.91, 212)

    local push1 = PushButton( sceneGroup, centerX, 370, “Back”, onBack,

        { labelColor = {0.8,0.2,0.2}, labelSize = 28 } )

local spinObject = function(event)

     local wheel = event.target

     local phase = event.phase

     local stage = display.getCurrentStage()

     if “began” == phase then

         stage:setFocus(wheel, event.id)

           wheel.isFocus = true

           wheel.tempJoint = physics.newJoint(“touch”, wheel, event.x, event.y)

     elseif wheel.isFocus then

         if “moved” == phase then

             wheel.tempJoint:setTarget(event.x, event.y)

         elseif “ended” == phase or “cancelled” == phase then

             local CurrentName

             local function PutUpRandomName (group)

                 local name = Name[math.random(#Name)]

                 display.remove(CurrentName) – in case some name is still showing

                 CurrentName = display.newText(group, name, display.contentCenterX, display.contentCenterY, native.systemFontBold, 50)

                 – set color, apply transitions, etc.

             end

             stage:setFocus(wheel, nil)

             wheel.isFocus = false

             wheel.tempJoint:removeSelf()

         end

     end

     return true

end

wheel:addEventListener(“touch”, spinObject)

end

    ----------------------------------------------------------------------

    ----------------------------------------------------------------------

function scene:willEnter( event )

    local sceneGroup = self.view

end



function scene:didEnter( event )

    local sceneGroup = self.view

end



function scene:willExit( event )

    local sceneGroup = self.view

end



function scene:didExit( event )

    local sceneGroup = self.view

end



function scene:destroy( event )

    local sceneGroup = self.view

end

    ----------------------------------------------------------------------

    – FUNCTION/CALLBACK DEFINITIONS –

    ----------------------------------------------------------------------

onBack = function ( self, event )

    local options =

    {

        effect = “fromTop”, – See list here: http://docs.coronalabs.com/daily/api/library/composer/gotoScene.html

        time = 500,

        params =

        {

            arg1 = “value”,

            arg2 = 0

        }

    }

    composer.gotoScene( “src.mainMenu”, options  )

    return true

end

    ---------------------------------------------------------------------------------

    – Scene Dispatch Events, Etc. - Generally Do Not Touch Below This Line

    ---------------------------------------------------------------------------------

    function scene:show( event )

        local sceneGroup = self.view

        local willDid = event.phase

        if( willDid == “will” ) then

            self:willEnter( event )

        elseif( willDid == “did” ) then

            physics.start()

            self:didEnter( event )

        end

    end

    function scene:hide( event )

        local sceneGroup = self.view

        local willDid = event.phase

        if( willDid == “will” ) then

            physics.pause()

            self:willExit( event )

        elseif( willDid == “did” ) then

            self:didExit( event )

        end

    end

    function scene:destroy( event )

        local sceneGroup = self.view

        physics.stop()

    end

    scene:addEventListener( “create”, scene )

    scene:addEventListener( “show”, scene )

    scene:addEventListener( “hide”, scene )

    scene:addEventListener( “destroy”, scene )

    ---------------------------------------------------------------------------------

    return scene

[/lua]

This is my game.lua

Ah, I didn’t quite realize players.lua was a scene. (I did see self, so I should have guessed…)

What I would recommend is to add another file, player_names.lua , that is not a scene. Something like:

local M = {} local TextFields = {} --- Get the current list of names as an array of strings. function M.GetNameList () local list = {} for \_, text\_field in ipairs(TextFields) do list[#list + 1] = text\_field.text -- Add the current text to the list end return list end --- Register another text field so we can use it to build our list later. function M.RegisterTextField (text\_field) TextFields[#TextFields + 1] = text\_field end return M

This will replace local M = {} , M.GetName() and return M in players.lua. Instead, just register all your text fields, probably in its scene:create() function:

local player\_names = require("src.player\_names") -- at the top -- other code player\_names.RegisterTextField(Player1Field) player\_names.RegisterTextField(Player2Field) -- etc...

In game.lua , again, require() that same module (and remove both require(“src.players”) calls).

Then, use player_names.GetNameList() to initialize Name. You will probably want to move this into scene:didEnter().

Actually, you might have problems with the  Name and CurrentName variables, if you’re still unfamiliar with things like scope. A better idea for now might be to use self.names and self.current_name (or whatever you want to call them) instead.

Hi.

This could be a couple questions. One is just the display part of it, but that’s fairly basic usage of display.newText() and text:removeSelf(), so I’m going to assume it’s not where you’re having trouble.

If coming up with the string is the problem, you’ll need to store a list somewhere, say in a Lua array. Populating it will take a while, but is inevitable. There are probably lists already out there, but if not, you could use a tool like this: List of Random Names (first relevant thing I found when I searched, and seems decent). Just export as text and stuff into an array, then add quotes and commas. Do this a bunch of times to build a big list, removing duplicates if you care. Later if you add user-provided names you can read from a file.

Then just have stuff like:

local Names = { "Adam", -- could be tables to add metadata like male / female, nationality, is a nickname, etc. "Alice", "Amy", -- and so on } -- other code local CurrentName local function PutUpRandomName (group) local name = Names[math.random(#Names)] display.remove(CurrentName) -- in case some name is still showing CurrentName = display.newText(group, name, display.contentCenterX, display.contentCenterY, native.systemFontBold, 50) -- set color, apply transitions, etc. end local function RemoveName () if CurrentName then -- fade the old name out transition.to(CurrentName, { alpha = 0, time = 1000, onComplete = display.remove }) end CurrentName = nil end

and call them where appropriate.

Hi StarCrunch,

Thanks for your help.

And if i wuold like to write the player’s names in the main menu, using a text box, how I can do that? Is ti possible?

For example:

Player1 = --type the name of the player here

Player2 = --type the name of the player here

and so on…

Sure, just use one of these:

native.newTextBox()

native.newTextField()

Make sure to read the “Gotchas”, just in case those would affect you.

Hi StarCrunch,

I’m still in trouble with my project, I’m trying to use the native.newTextField() method but.

  1. I don’t know how to join my players.lua (where i should writhe the names) and my game.lua (where it should spawn       the names).

  2. With the putUpRandomNames function whe i stop the wheel nothing happends or it’s not displayed and no errors

This is my players.lua nativeNewText code:

[lua] local createPlayer = display.newEmbossedText( sceneGroup, “Players”, centerX, 40, “youmurderer”, 60 )

createPlayer:setFillColor( 0.8,0.2,0.2  )

local color = 

{

   highlight = { r=1, g=1, b=1 },

   shadow = { r=0.8, g=0.2, b=0.2 }

}

createPlayer:setEmbossColor( color )

local function onUserPlayerInput( event )

local phase = event.phase

if “editing” == phase then

game.name = event.text

elseif “submitted” == phase or “ended” == phase then

native.setKeyboardFocus( nil )

end

end

– The Player’s name field

local PlayerField = native.newTextField( 20, 50, 280, 30 )

PlayerField.x = display.contentCenterX

PlayerField.y = createPlayer.y + createPlayer.contentHeight + 15

PlayerField.placeholder = “Player Name”

PlayerField:addEventListener( “userInput”, onUserPlayerInput )

PlayerField:setReturnKey( “done” )

PlayerField.inputType = “name”

self.PlayerField = PlayerField

[/lua]

When i try to write a player’s name it gave me an error. If you need more code or you need to check my files just ask.

Please help

P.S.

I’m sorry for my bad english

In case you still need it, Rob actually just put up a list of the text tutorials last night:

Tutorial Treasury: Native text input fields/boxes

The clean way to share code will be to make modules. It sounds like you’ve been doing so, since you have separate files.

You should put game.name somewhere (per player) and then add a function or two to players.lua to get those names. Basically, update your current structure to something like:

-- updated players.lua local M = {} -- module table -- Add most / all of your current code here -- Add some utility functions -- Get a player's name -- This is just an example. Write this in whatever way is nicest for you. -- You could even just make one function per player. function M.GetName (which) if which == "player1" then return Player1Name elseif which == "player2" then return Player2Name -- etc. end end return M -- export your module

Then in game.lua , do a require(“players”) and call your functions somewhere appropriate:

local players = require("players") -- Your code... local Name = players.GetName("player1") -- or add it to an array, if following the earlier approach -- in that case, you should also remove it, post-level -- do stuff with name