iprogrammingnotes.doc

advertisement
Who is here. You have to use the lab computers
Show tablets and other devices
show syllabus--uncertain about how to test for the course.
We will use COrona SDK--cite advantages--easy development cycle, rapid cycle, cross
platform, etc.
Go home and see if you still understand it.
Some thoughts about programming
We use the programming language called LUA which is integrated into the CORONA
development kit. LUA is described as a scripting language, similar to JAVAscript if you
are familiar with that. It is a procedural language, although it retains many of the
outward appearances of OOP’s especially the “dot” operator (more below) and the
association of methods with objects.
Idea of Objects
a variable is like a cell in a spreadsheet
a data structure is like a cell with formatting
functionally like a rolodex containing
name variable (field)
address variable (field)
zip variable (field)
an object is a data structure, one of whose elements is s program
program may have variable degrees of complexity
add a number to a number
find the average of a ist of numbers
conditional statement on a computer
demonstrate these points using a spreadsheet to change raw score on a test to
percentages, and then to S/U. Emphasize that we will not be using sreadsheets as a
programming environment and that these are only analogies for what we will do drawn
from a (hopefully) more familiar world.
C6 = cell.newNumber(6)
C6:setTextColor(255,255,0)
C6.setColumnWidth(60)
and
C7=8*C6
a multiply by 8 function. Now it looks different in LUA, and to illustrate this we are going
to write an “Hello World” program and then put it on my Android phone--actually I’ve
already put a fairly complicated one on the phone--show and tell “hellowoild”.
Let’s start out by looking at the Corona development environment:
((Define two terms==API is the Application programming interface
SDK==software development kit))
Three parts to the Corona envronment:
Text Editor
Terminal Window
Simulator
The text editor is where you write your code. We use TextWrangler which is free and
color codes stuff
The terminal window is the “window on our mac’s soul and can reveal the innards of
what’s going on. It is a standard UNIX window but we are not going to learn UNIX here-maybe a couple of tidbits--in general, we can send messages to ourselves, telling us
where our program is hung up, or where functioning properly through the terminal
window.
The simulator emulates the device we are currently writing for, be it a kindle, nook, ipad
or android or whatever.
So the first thing we do is write our code. We place each program in its own folder. The
name of the program is the name of the folder. The main file for that program is called
main.lua. So we have a jillion different folders each with a different name but each
containing (at least) a file named main.lua.
Show on TV Text Wrangler and drag main.lua over it. Use folder “printroutine” located in
Documents->coronastuff->classstuff. Drag the “main.lua file contained therein over
textwrangler. Very simple. Show the code and imagine we made the file, typed in the
code and now we are ready to go--what do we do next?
Make sure we save the changes we want to keep and then go to the corona folder in
applications. Double-click on the “Corona Terminal” icon. Show them what happens.
You get a terminal window and a splash screen. Best at first to just go to the simulator
by clicking on its button. Let’s simulate a Droid and navigate to folder “printroutine” and
open main.lua. It would help if you had the terminal window visible in the background
before you open main.lua.
When you open main.lua, the simulator comes to the front and “Hello World” appears in
the terminal window. The print command prints stuff in the terminal window, and so
nothing appears in the simulated droid window. So we have to change that
Go to simulator and select file-->open. This time navigate to the documents>coronastuff->classstuff-> sendtosimulator folder and open the file named main.lua.
Watch the simulator window as you do this and you should see “Hello World!” appear in
large yellow lettering on a black background on the droid cell phone simulated window.
What happened--to see what we did, we need to examine main.lua from the folder
“sendtosimulator” in the word processor. So we drag it to the textwrangler icon in the
dock and it opens up.
Do this on the demo TV
Here’s what you get:
textObject = display.newText( "Hello World!", 20, 50, nil, 24 )
textObject:setTextColor( 255,255,0)
textObject is the name of your variable. The first line is like assigning a number or
function to a variable in algebra. It’s like saying x = 6, or maybe x = (sinθ)e-5t. The only
difference is that we do not yet know what display.newText means. We can look this up
at the Corona site--a very important page
http://docs.coronalabs.com/api/
Anything you put on the screen is a display object and it is put on the screen by a
constructor. display.newText is the constructor of a text object.
If we look up display.newText, we see the basic syntax as follows:
display.newText( [parentGroup,] string, left, top, [width,
height,] font, size )
Let’s translate:
Display a new fragment of text on the screen from some parent group--this is optional
and usually ommitted--the actual fragment is denoted in the place listed as “string”. The
left top, in pixels is next, and, if you want to specify the width and height of your text box
you can, but this is not required. Then give the name of the font you want to use and its
size. Though it is not stated, the default color of the font is white.
In our code, then, we said “create a new text object whose name is textObject
(remember these names are case sensitive), and whose contents consist of the text
string ‘Hello World’. Place the top left corner of the box that bounds that text 20 pixels
from the left edge of the screen and 50 pixels down from the top edge. We don’t specify
a width and a height, just as we did not specify a parent group. We say use the nil font-this means use the default system font. Finally we specify the font size as 24 points.
By default, this font will display in white. If we don’t want this to happen, then we have to
set this property of the text object using:
textObject:setTextColor( 255,255,0)
setTextColor is a method that text objects carry along with them. Input the approproiate
numbers and the color you want comes out
At this point go through how colors are represented in a 24 bit system.
Demo how to change colors and how to change font size.
Impress on them the ease of use as you go through each cycle and the simulator
relaunches itself with the new code.
Also--if they had not noticed by this point--there is no special end of line separator--such
as the semicolon.
Finally, object properties use a dot separator, whereas methods use a semicolon. How
can you know? Look it up and it will grow on you.
Talk about how there are many paths to the mountaintop as well as the experience of
drinking water from a fire hose.
We will learn the basics of LUA--if we have a vocab of 100 commands and keywords by
end of semester, we will be happy.
LUA cares about capitalization and so many more variable names are
possible...however, the following is a list of reserved words that LUA keeps for itself:
and
break do
else
elseif
end
false for
function if
in
local nil
not
or
repeat return then
true until
while
Names (also called identifiers) in Lua can be any string of letters, digits, and
underscores, not beginning with a digit. Once agai, however, underscored word are
customarily “owned” by the Corona SDK. Don’t use them in your program.
Comments begin anywhere with a double hyphen (--) except inside a string. They run
until the end of the line.
A numerical constant can be written with an optional decimal part and an optional
decimal exponent. Lua also accepts integer hexadecimal constants, by prefixing them
with 0x. Examples of valid numerical constants are
3 3.0 3.1416 314.16e-2 0.31416E1 0xff 0x56
Graphics
Everyone loves graphics and we expect to utilize graphics. If you want to put graphics
on the screen, you need to put up a display object. Your object may be a vector object-chances are the SDK will draw that on the screen, or it may be a bitmap object, one that
you bring in from a camera or a scanner or some image processing program such as
photoshop.
There are numerous display object constructors in corona. We will use a couple
to draw a star. look at main.lua in /documents/coronastuff/classstuff/star/
Show how append just appends vertices and how we make it meet the beginning
of our star.
Also show the color scheme and ask them to write a short program that will draw
a rectangle.
However corona does not open or import external vector graphics unless you
install a module. So no postscript support...no pict or
On to bit map--explain the difference once more between bitmap and vector.
Explain compression and filetypes before explaining that Corona uses either jpg
or png as its graphics formats.
JPEG = joint photographic experts group
png=portable network graphics
Because png is scalable Corona likes png because of varying screen sizes
So while Corona
Interaction
People have to get data in and get data out and so we want to learn to do this-one baby step at a time, and we will do that now starting with buttons. But first we have
to make a button and we need to know how to draw one. For our purposes we are going
to learn to use Adobe Fireworks, part of the adobe creative suite
So we now have the fireworks tutorial and just show how to draw simple shapes in
different layers and color them to give a simple icon for a button
Next is to make a button on the screen.
First make a folder using textwrangler and name it interactivity and store your empty
main.lua program in it. This program will ultimately demonstrate some event driven code
which listens for and uses button events.
Now make your first button and name it first.png. You’ll have to go to fireworks to do
this. I used 77x37 as my canvas size. You can set this under the modify menu. You
might also want to set the color of your background...perhaps to transparent?
Save the button in your project folder and then make another called second.png. Then
type or paste the following text into your main.lua document in your interactivity folder.
local button1 = display.newImage( "first.png" )
button1.x = display.contentWidth /3
button1.y = display.contentHeight - 50
local button2 = display.newImage( "butt2.png" )
button2.x = 2*display.contentWidth / 3
button2.y = display.contentHeight - 50
display.setDefault("background",0,140,140)
Note that you are setting a couple of button properties: “x” and “y”, using display
properties “contentWidth” and contentHeight. You are in essence telling your device to
display these buttons 1/3 and 2/3 of the way across the screen,and 50 pixels from the
bottom.
That last little bonus line sets the default screen color and we are going to need it in a
moment or two in the next elaboration of our program.
As usual, experiment with your code, and look up the full description of the properties
you have used in the Corona API docs. When you finish, save your main lua file and
say yes to reload the page in your simulator.
Sounds
Let’s add a sound for feedback to let you know that you have pressed a button. For
sound we are going to use the (relatively) newly initiated openAL system which is
replacing the older Corona Event Sound system. The older system will be deprecated at
some point (i.e. eliminated and de-supported), and so we will write programs that use
the newer sound system.
The following code includes two additions which result in a beep (of sorts) every time
the first button is pressed. It also includes additions which allow your device or the
simulator to respond to button presses. We will explain those shortly--for now let’s just
concentrate on sound production.
The new code is shown in italics, and the part of that code that involves sound
production is also bold-faced.
local button1 = display.newImage( "first.png" )
button1.x = display.contentWidth /3
button1.y = display.contentHeight - 50
local button2 = display.newImage( "second.png" )
button2.x = 2*display.contentWidth / 3
button2.y = display.contentHeight - 50
display.setDefault("background",0,140,140)
beepSound = audio.loadSound("beep.mp3")
function button1:tap( event )
beepChannel = audio.play( beepSound )
end
button1:addEventListener( "tap", button1 )
button2:addEventListener( "tap", button2 )
The audio.loadSound method loads a sound file, in this case beep.mp3, and then
assigns a handle to it that you specify (beepChannel), and a sound channel (that it
specifies and that you can ask it to tell you). Corona can have a maximum of 32
simultaneous sound channels in use.
Whenever you want to refer to your beep sound, you cite the name of its handle
(beepChannel, in this case). This handle, for example, is the argument to the method
audio.play.
OK--let’s answer some questions that you may be asking. One would be “what’s a
handle?”. Easy--a handle is a pointer. “Then, what’s a pointer?” A pointer is a variable
that points to another variable, whereas an ordinary variable just points to some value
you’d like to know.
What’s the office number of the physics teacher. Go to the school phone book and look
up physics teacher. It’s Dr. Dehaven. Go look up Dr. DeHaven’s phone number. It’s
7844. 7844 is the value of the variable, Dr. Dehaven’s phone number. Physics teacher
phone number is a pointer. It’s value is not the actual phone number, but the location of
where to find it.
Do I have to use .mp3’s. If you want your sound files played on any device (including,
maybe, someday, Windows devices), then use .mp3 or .wav files. Only problem: .wav
are much bigger than mp3’s and the memory space on a cell phone can get real small
real fast. Consequently we will try to use .mp3’s for sound files wherever possible.
Events
Now let’s talk about the real meat of the issue, events. Events are occurrences
through which the external world attempts to make contact with your cell phone or your
tablet. If you shake the tablet, for example, and the tablet contains an accelerometer,
that will generate an event. An event can occur, however, without direct human
intervention: if you want to set an alarm on your phone, you will need the internal clock
to generate an event at, say, 6:30 AM. Events can even come from within programs. A
game author, for example, might want an event generated every time two moving
objects on the screen collided. One of the most important type of event is the tap: when
you tap the screen the software must detect both the tap and where it occurred
Corona SDK is event driven, and it has to be because the iOS and Android
environments are themselves both event driven. The Corona SDK and your device
provide you with a queue of each type of event, and you set up your program to look for
these events and to respond to them intelligently.
In the table below is a listing of the various types of devices and processes which
can generate events.
accelerometer
key
productList (In-app purchase)
audio
location (GPS)
sprite
collision
mapAddress
storeTransaction (In-app
purchase)
completion
memoryWarning (iOS only)
system
creditsRequest
networkRequest
tap
enterFrame
networkStatus
timer
fbconnect
notification
touch
gameNetwork
orientation
urlRequest
gyroscope
postCollision
heading (compass)
preCollision
With each device or process there are likely to be associated several different
properties pertaining to these events. As an example, the properties associated with the
accelerometer contained in most phones and tablets, are tabulated below:
event.isShake
event.zGravity
event.xInstant
event.deltaTime
event.name
event.zInstant
event.yGravity
The complete documentation for the events supported by Corona SDK can be accessed
at the following link:
http://docs.coronalabs.com/api/event/index.html
OK, so what exactly do we do with events. First of all we have to listen for them. The
following code instructs our graphic objects to listen for events of type “tap”:
button1:addEventListener( "tap", button1 )
button2:addEventListener( "tap", button2 )
Without this event listener, our button is just a hunk of colored pixels, looking pretty on
the screen. With it, however, it sends a message to the program, which checks to see if
there is an event handler waiting for a message from button1. It turns out there is:
function button1:tap( event )
beepChannel = audio.play( beepSound )
end
Whenever a tap event from button1 is detected, it is sent to the function named button1.
The function performs its task (it makes the phone or tablet beep) and the control
passes back to the program’s event listener loop--in this case the two
“addEventListener” statements, which wait patiently for the next tap.
The tap event is associated here with a particular object (one or the other buttons). It is
therefore referred to as a local event, as opposed to an event such as an orientation
event, in which the orientation of the entire pad or phone was changed, and the
existence which event would be important information for any running application.
A basic, but thorough introductory explanation of events and event listeners can be
found at the following link, and I urge you to visit and master the content of this section:
http://developer.coronalabs.com/content/application-programming-guide-tutorialintroduction#Basic_Interactivity.
Let’s try to do a couple of new things with our buttons. First, let’s play a song when we
press button 2. Then let’s alter the screen colors when we press button 1.
Here is the code that could accomplish this:
local button1 = display.newImage( "first.png" )
button1.x = display.contentWidth /3
button1.y = display.contentHeight - 50
local button2 = display.newImage( "second.png" )
button2.x = 2*display.contentWidth / 3
button2.y = display.contentHeight - 50
display.setDefault("background",0,140,140)
beepSound = audio.loadSound("beep.mp3")
bachgloria=audio.loadSound("osannaBminor.mp3")
function button1:tap( event )
local r = math.random( 0, 255 )
local g = math.random( 0, 255 )
local b = math.random( 0, 255 )
beepChannel = audio.play( beepSound )
display.setDefault("background",r,g,b)
end
function button2:tap( event )
beepChannel = audio.play( bachgloria )
end
button1:addEventListener( "tap", button1 )
button2:addEventListener( "tap", button2 )
What have we done? We have added a new function, a button2 function to listen for tap
events from button2. When that happens, it plays a sound file named “bachgloria”. Note
that we already loaded this as part of the startup to the program. Note how we structure
our functions: there is a function statement and then a block of code (one or more lines)
that tell us what to do when the function is called, and, finally, and “end” statement: this
is the end of the function.
If we put this function into our program--and don’t forget to include the “loadSound
statement a few lines above--then the program will look for osannaBninor.mp3 and play
it. Of course you can play your favorite song as well. Remember--your .mp3 file must
go into the same folder as “main.lua”.
Try the code and see what happens when you hit button 2 twice, or 3 times. What a
mess: the song plays over itself and there is no way to stop it. So what do we do?Before
we answer that question, we must make a brief side journey into conditional statements.
We want to somehow make what the song does depend on what we do--this is after we
start the song. Right now it just plays on and on and can’t be stopped. What I want is
this: I want it to play if i click the 2nd button while the song is silent, and I want the song
to stop playing if I click the button while it is playing.
I’ll write a “pretend program” to show you what I mean:
If you click on button 2 then do the following:
Check to see if the song is playing
If the song is playing then stop it from playing and exit this routine
Otherwise, if the song is not playing, then play the song, and exit this routine
The End of this program block.
The above lines are often called pseudo-code. They are a rough draft of what you are
going to type into the computer, and pseudo-code is often a great help, a kind of bridge
from your native language to the language of computers.
Let’s try to implement the above pseudo code in LUA:
http://lua-users.org/wiki/ControlStructureTutorial
Problems
If you hadn’t noticed, there is a slight problem
Building a File for Android
First sign your app. Go to File->Build->Android...
Use your folder name as your app name. Put in an integral version code. Give a
decimal version name.
Package name
1--reverse your domain
2--unique company name (mnsdehaven)
3--program name--finalresult
edu.dyc.mnsdehaven.finalresult
Go to campus.dyc.edu
Name=android
ID=lualua505
http://developer.coronalabs.com/reference/bitmap-masks-tableviews-and-scrollviews
Properties
Many Corona API’s return objects. You are free to manipulate the documented
properties of these objects just like you would on a table. You can even add your
own properties provided you do not prefix any of your custom properties with an
underscore (“_”). Ansca reserves the right to use any property name that begins
with an underscore.
Like most languages, all properties can be accessed via the dot (“.”) operator. It's
really just a convenient way to index into a table. In other words, we can access
property foo of a table t using the dot operator (t.foo) or index into it using a string
(t["foo"]); the result is the same.
Object Methods
Objects in Lua are represented by tables. Display objects (rectangles, images,
etc.) and the global Runtime object are all examples of objects. Like the math
library, these objects similarly store object methods (a.k.a. instance methods) as
properties. One key difference, however, is syntax. You need to tell Lua that you
intend this function to be called as an object method, not just a plain function. To
do so, you need to use the colon (“:”) operator instead of the dot (“.”) operator.
This may be slightly different than what you are used to in other languages.
Compare the syntax of Javascript and Lua:
JavaScript
Lua
object.translate
( 10, 10 );
object:translate( 10, 10 )
Download