How can I have a randomly generated image be used as a tool that a player could use to determine which "character" to press? - lua

In this particular code, I have 3 boxes that currently show up on the screen. The boxes in the center of the screen are the ones I want to have treated as the characters. The box on the top of the screen randomly generates an image of one of the characters, in this case the red box or the blue box. For example, if at the top the red box was selected as the randomly generated image, I would want the player to tap the red box that would be treated as a character. If the person tapped the correct box as a result of the box on the top, I would want the box at the top to change again, therefore creating a cycle between the characters and the box at the top. If the player taps the wrong box, I would want the game to end. What am I doing wrong, and more importantly how can I fix it? Here is my code:
local imageFiles = {"bluebox.png", "redbox.png"}
local imageFile = imageFiles[math.random(2)]
local randomImage = display.newImage(imageFile, 40, 40)
local button1 = display.newImage("redbox.png")
button1.x = centerX
button1.y = centerY
group:insert(button1)
local button2 = display.newImage("bluebox.png")
button2.x = centerX
button2.y = centerY - 100
group:insert(button2)
local function randomize(event)
if button2 == randomImage then
(insert code here)
end
end
local function generate(event)
if button2 ~= imageFile then
storyboard.gotoScene ("restartEasy")
elseif button2 == imageFile then
(insert code here)
end
end
button1:addEventListener("tap", randomize)
button2:addEventListener("tap", generate)

if button2 ~= imageFile then
elseif button2 == imageFile then
You're comparing images with strings. This will never work. But let's ignore that for now.
While I'm not familiar with Corona, I believe randomImage will never equal either button1 or button2 because it's a separate image (with independent coordinates and/or dimensions).
I'd replace your random selection code (the first three lines) with the following lines right after the second call to group:insert():
local one_or_two = math.random(2)
local endGameButton, shuffleButton
if one_or_two == 1 the
endGameButton, shuffleButton = button1, button2
else
endGameButton, shuffleButton = button2, button1
end
At the end I'd replace your two addEventListener lines with:
shuffleButton:addEventListener("tap", randomize)
endGameButton:addEventListener("tap", generate)
And then I'd remove all the conditions (if buttonX == whatever) from your functions because they are no longer needed.
In other words: instead of testing which button is the random one every time something is clicked (as you're doing now), we assign each button a meaning.

Ok so in order to have the top button correspond with the characters, I needed to use the png files of the images as opposed to using a variable defined by those png images. in this case instead of using
if button2 = randomimage
use
if imageFile = "nameofimagefile.png"

Related

(Adobe Animate ActionScript) how can iRemove specific Symballl's from the stage using name, arry, and lib()?

I'm super frustrated with this.
first for you to understand my code - My goal here is for the user to get randomly selected word appear to them in a way that every letter sits inside of a box.
Then if the user clicks on a button called "Pick a word", another word will be selected and the correct number of boxes will appear.
I have an array of words like this:
var word_group_1 = ["abolsh", "absorbent", "betrayal", "frutish", "commensurate", "eonfident", "zite"]
I'm using this function to select a random word from that array then splice it.. works perfectly:
function random_word_genereator() {
random = randomNumber(0, word_group_1.length);
//putting the chosen word from array in the chosen word variable
chosen_word = word_group_1[random]
//after we used the chosen word were removing it from the away
word_group_1.splice(random, 1)
//splitting the chosen word into an array
chosen_word_letters_arry = chosen_word.split("")
}
in a button click of "pick a word"- I'm creating 5 instances of a Movieclip I have in my library (just a blue box to put text in it) with text in at like this:
function create_boxes(e)
{
//to know which word has been displayed to the user//
old_word=chosen_word
random_word_genereator()
for (i=0;i<chosen_word.length;i++){
cell_boxes = new lib.cell_box();
stage.addChild(cell_boxes)
cell_boxes.name="cell_box"+i;
cell_boxes.x=(xlocation * i) + 50
cell_boxes.y = 80;
output = new createjs.Text();
cell_boxes.addChild(output)
output.text=chosen_word_letters_arry[i]
}
everything works fine on the first click As You Can View Here.
The word being selected and displayed on the stage
my problem is when I'm clicking Again on the button "pick a word"
its not deleting the correct number of boxes.
I'm putting visible false to the boxes which holds the "Old word" (the one I need to delete)
but As you can se here After I click again its getting messed up.
sometimes its's working, switches from 12 letter word, to a 4 one.
but it should be luck. I'm dying to get this to WORK! its for my school project.
Please help me!
Easy answer that will plug and play into your code:
js
...
//to know wichh word has been displayed to the user//
old_word=chosen_word
random_word_genereator()
for (i = 0; i < stage.numChildren; i++) // Loop through all children of the stage
if (stage.getChildAt(i) is lib.cell_box) // Checks if the child is a lib.cell_box
stage.removeChildAt(i--); // Removes child from stage and decrements i
for (i=0;i<chosen_word.length;i++){
...
Original answer (cleaner code, some restructuring):
It's best to break this kind of logic down into steps.
var boxes:MovieClip = new MovieClip();
boxes.y = 80;
addChild(boxes);
...
function createBoxes(word:String):void {
// Remove boxes first
while (boxes.numChildren > 0)
boxes.removeChildAt(0);
// Add boxes
for each(var c:String in word.split("")) {
var box:Box = new Box(c);
box.x = boxes.width + 50;
boxes.addChild(box);
}
}
Then set the text inside a Box class.

How can I make an image fall down randomly as if meteors in Corona SDK?

What I want is that the images fall from the top side of the screen and start falling down accelerating, they would only be falling straight down, alternating positions around the width of the screen, meaning one on the right, then another one in the middle, and then another one on the left side and so on in the different positions, until they disappear at the bottom of the screen.
I tried this
function moveMeteors()
for i = 1, math.random(1, 2) do
meteors = display.newImage("meteor.png")
screenGroup:insert(meteors)
meteors.x = (math.random(display.contentWidth))
meteors.y = centerY - 340
transition.to(meteors, {time = math.random(3500 - speedMeteor, 4500 - speedMeteor),
y = 1000 + speedMeteor, onComplete = clear })
speedMeteor = speedMeteor + 10
end
end
But, sometimes the images appear one over the other and I do not want that, I mean, each image appear and go from the top to the bottom of the screen in his own line. I hope that I've explained this well.
You should look into utilizing the built in physics of Coronasdk. CoronaDocs:Physics.
As an example this code should easily simulate the effect you a trying to get, you will have to add functions to take care of removing objects as they leave the screen etc.
local physics = require("physics")
physics.start()
function SpawnMeteor()
local meteor = display.newImage( "meteor.png", math.random(display.contentWidth), centerY - 340)
physics.addBody( meteor)
end
timer.performWithDelay( 2000, SpawnMeteor)

Corona SDK display.remove() in lua

this code (lua) gives you a random value from the table "local a" by pressing the text "new". Unfortunately the new random value just appears above the old one. I've tried to remove the old value e.g. with display.remove(mmDis), but it doesn't work.
The second problem is that sometimes I also get back the value "nil" and not only the four entries from the table.
Both things must be easy to solve, but as newbie to lua and working on these small things for almost 4 hours now I just don't get what to change to make it work.
-- references
local mmDis
-- functions
function randomText(event)
display.remove(mmDis)
local a = {"Banana!","Apple!","Potato","Pie"}
com = (a[math.random(0.5,#a)])
local mmDis = display.newText(tostring(com),
display.contentWidth*0.57, display.contentHeight*0.7,
display.contentWidth*0.9, display.contentHeight*0.8, "Calibri", 60)
end
-- menu button
local textnew = display.newText("New", 0, 0, "Calibri", 40)
textnew.x = display.contentWidth*0.2
textnew.y = display.contentHeight*0.9
textnew:addEventListener ("tap", randomText )
It's hard to understand what you are trying to do because when you create textnew you have it in one position and size, while in randomeText() you seem to want to replace that text object with a new one, but you put it at a different pos and size. It appears you want to change the object's text every time you press on tap; in this case, you don't need to replace the text object, you just replace its text.
Also:
you have two "local mmDis", the second one will hide the first, not sure what you're after there
read carefully the docs for math.random
com is already a string so you don't need tostring
Try this code and let me know if this is not what you are after:
local menuTextOptions = {
text = "New",
x = display.contentWidth*0.2,
y = display.contentHeight*0.9,
align = 'left',
font = "Calibri",
fontSize = 40,
}
local textnew = display.newText(menuTextOptions)
-- functions
function randomText(event)
local a = {"Banana!","Apple!","Potato","Pie"}
local com = a[math.random(1,#a)]
textnew.text = com
-- if you want to change position too:
-- textnew.x = display.contentWidth*0.2
-- textnew.y = display.contentHeight*0.9
-- if you want to change size too, but only used for multiline text:
-- textnew.width = display.contentWidth*0.9
-- textnew.height = display.contentHeight*0.8
end
textnew:addEventListener ("tap", randomText )
Sometimes it looks like the button doesn't do anything when you tap but that's because the random number happens to be same as previous, you could put a loop to guard against that. Ig you actually want to change the pos and/or width, then the above code makes it clear where you should do that.
So, that's the basic code (without any extras at the moment :)) how it should be. Big thanks to Scholli!:
local menuTextOptions = {
text = "New",
x = display.contentWidth*0.2,
y = display.contentHeight*0.9,
align = 'left',
font = "Calibri",
fontSize = 40,
}
local textnew = display.newText(menuTextOptions)
local replacement = display.newText(menuTextOptions)
replacement.y = display.contentHeight*0.5
-- functions
function randomText(event)
local a = {"Banana!","Apple!","Potato","Pie"}
local com = a[math.random(1,#a)]
replacement.text = com
end
textnew:addEventListener ("tap", randomText )

Attempt to index global 'player' (a nil value)

I'm getting a (a nil value) error when i try to do this :
player = display.newSprite( imageSheet, "sequenceDataPlayer"..math.random(1, 7) )
Looking at a test print :
print ("sequenceDataPlayer"..math.random(1, 7) )
It prints the data oky 'sequenceDataPlayer1'
What Im i doing wrong here ?
Your print statement is just printing the string "sequenceDataPlayer" concatenated with a random number between 1 and 7.
It took me a little while to figure out how to use sprites in Corona, but here's how I do it. I'll use Player for the variables since that's what you're using.
First I create an options variable to get the frames from my Player.lua file:
optionsPlayer =
{
frames = require("player").frames,
}
Then I create a variable for the image sheet:
playerSheet = graphics.newImageSheet( "player.png", optionsPlayer )
After that, I create a variable to set up the name, the sequence of frames, the time it takes to play, and set how many times it will loop:
spriteOptionsPlayer = { name="Player", start=1, count=10, time=500, loopCount = 1}
Finally, I create the new sprite:
spriteInstancePlayer = display.newSprite( playerSheet, spriteOptionsPlayer )
Once I've done all this, I usually set up the x and y positions, xScale and yScale, and other properties along with adding it to a display group.
Last of all, then I play the sprite somewhere:
spriteInstancePlayer:play()
From what it looks like, you want to have 7 different sprites to choose from. Personally, I would just create seven different sprites using all of the steps above and then put them in a table.
sprites = { spriteInstancePlayer, spriteInstancePlayer2, spriteInstancePlayer3, etc.. }
Then when I wanted to play them, I would set the position and visibility and just do:
r = math,random(1, 7)
sprites[r].x = x position
sprites[r].y = y position
sprites[r].isVisible = true
sprites[r]:play()
Of course, then I would want to set listeners to either completely remove the sprite or set the visibility to false when it's done playing, there's a collision(you'd have to add a physics body and set that all up), or whatever else might happen...
There are probably simpler ways to do it, but that's what I do.
Hope this helps.

Changing to display object position in corona

I am new to programming this question might sound very simple.
I have created a object as a module called box
box = {}
m={}
m.random = math.random
function box:new(x,y)
box.on=false
local box = display.newRect(0,0,100,100)
box:setFillColor(m.random(120,200),m.random(120,200),m.random(120,200))
box.x = x
box.y = y
box.type = "box"
return box
end
return box
in my main.lua I want to create as many boxes and ,like an adventure game how can I switch two of the boxes position,example I click on one of them,then it is selected,and simply I click on the other one and they change position with each other.
Thanks in advance
I don't know Corona, but the general logic for what you're doing is this:
Add an event handler which allows you to detect when a box is clicked.
Add some way of tracking the selected box.
When a box is clicked:
if no box is yet selected, select the current box
if another box was previously selected, swap with the current box
if the already-selected box was clicked, ignore (or toggle off selected)
General idea (not sure if this is valid Corona event handling, but should get you close):
box = {}
m={}
m.random = math.random
-- track the currently selected box
local selected = nil
function box:new(x,y)
box.on=false
local box = display.newRect(0,0,100,100)
box:setFillColor(m.random(120,200),m.random(120,200),m.random(120,200))
box.x = x
box.y = y
box.type = "box"
function box:touch(event)
if not selected then
-- nothing is selected yet; select this box
selected = self
-- TODO: change this box in some way to visually indicate that it's selected
elseif selected == self then
-- we were clicked on a second time; we should probably clear the selection
selected = nil
-- TODO: remove visual indication of selection
else
-- swap positions with the previous selected box, then clear the selection
self.x, self.y, selected.x, selected.y
= selected.x, selected.y, self.x, self.y
selected = nil
end
end
return box
end

Resources