App inventor 2 en español
Cómo programar los teléfonos móviles con Android.
Curso de App inventor 2 en español - Juan Antonio Villalpando
-- Tutorial de iniciación de App Inventor 2 en español --
Volver al índice del tutorial
_________________________________________________
109.- Java Bridge - 4. Mole Mash.
- Ejemplo Mole Mash.
- En el tutorial oficial de Java Bridge viene este ejemplo Mole Mash, lo vemos con aclaraciones en español.
- La aplicación Mole Mash la podemos consultar en App inventor: MoleMash.aia
- Para ver este MoleMash.aia, es conveniente poner App inventor en inglés, ya que las variables y la explicación están en inglés.
- Una vez visto MoleMash con App inventor, bajamos el archivo en JAVA (recuerdo que no hay ningún conversor de App inventor a Java, simplemente alguien ha creado y escrito el código en texto de Mole Mash basándose en el de App inventor, pero no se ha traducido automáticament por ningún sofware).
- Bajamos Mole Mash en Java: molemash.java
- La forma más sencilla de continuar es simplemente copiando y pegando el siguiente código del molemash.java en nuestra Screen1 y cambiando la palabra example, por el que tienes en tu package.
- Otra manera sería Pegando este archivo en app / src / main / java / juan / com / botonrojo /
y luego modificando el archivo
BotonRojo / app / src / main / AndroidManifest.xml
<activity
android:name=".molemash"
Código molemash.java |
// A simple MoleMash game with a timer
package com.example.molemash;
// you need the following imports in all Java Bridge apps
import com.google.appinventor.components.runtime.HandlesEventDispatching;
import com.google.appinventor.components.runtime.EventDispatcher;
import com.google.appinventor.components.runtime.Form;
import com.google.appinventor.components.runtime.Component;
// the components for the MoleMash game
import com.google.appinventor.components.runtime.Button;
import com.google.appinventor.components.runtime.Canvas;
import com.google.appinventor.components.runtime.Clock;
import com.google.appinventor.components.runtime.Label;
import com.google.appinventor.components.runtime.ImageSprite;
import com.google.appinventor.components.runtime.HorizontalArrangement;
// import Java's Random module
import java.util.Random;
// the usual header for a Java Bridge app
public class Screen1 extends Form implements HandlesEventDispatching
{
// declare all your components as variables
private Canvas canvas1;
private Label headerLabel;
private Clock moleClock;
private Clock gameClock;
private HorizontalArrangement horizArrangement;
private Label timeLeftLabel;
private Label timeLeftValueLabel;
private Label spaceLabel;
private Label scoreLabel;
private Label scoreValueLabel;
private ImageSprite moleSprite;
protected void $define()
{
// create your components and set their initial properties
headerLabel = new Label (this);
headerLabel.Text("MOLEMASH-- touch the mole to earn points!");
canvas1 = new Canvas(this);
canvas1.BackgroundColor(COLOR_GRAY);
canvas1.Width(LENGTH_FILL_PARENT);
canvas1.Height(300);
moleSprite = new ImageSprite(canvas1);
// be sure and place a file mole.png in the assets folder of your project!
moleSprite.Picture("mole.png");
moleClock = new Clock(this);
gameClock = new Clock(this);
horizArrangement = new HorizontalArrangement(this);
timeLeftLabel= new Label(horizArrangement);
timeLeftLabel.Text("Time Left:");
timeLeftValueLabel= new Label(horizArrangement);
timeLeftValueLabel.Text("60");
spaceLabel = new Label(horizArrangement);
spaceLabel.Text(" ");
scoreLabel= new Label(horizArrangement);
scoreLabel.Text("Score:");
scoreValueLabel= new Label(horizArrangement);
scoreValueLabel.Text("0");
EventDispatcher.registerEventForDelegation( this, "Canvas/Sprite", "Touched" );
EventDispatcher.registerEventForDelegation( this, "ClockMoleTimer", "Timer" );
}
public boolean dispatchEvent(Component component, String componentName, String eventName, Object[] params )
{
// when mole is touched, add a point. Need to covert text to int and back
if( component.equals(moleSprite) && eventName.equals("Touched") )
{
int score = Integer.parseInt(scoreValueLabel.Text());
score = score+1;
scoreValueLabel.Text(String.valueOf(score));
return true;
}
// count down the clock on the clock timer
if( component.equals(gameClock) && eventName.equals("Timer") )
{
int count = Integer.parseInt(timeLeftValueLabel.Text());
count = count - 1;
timeLeftValueLabel.Text(String.valueOf(count));
if (count==0) {
//game is over
gameClock.TimerEnabled(false);
moleClock.TimerEnabled(false);
timeLeftValueLabel.Text("Game Over");
}
return true;
}
// on mole timer, move the mole randomly
if( component.equals(moleClock) && eventName.equals("Timer") )
{
Random random = new Random();
int x= random.nextInt(canvas1.Width()-moleSprite.Width());
int y= random.nextInt(canvas1.Height()-moleSprite.Height());
moleSprite.MoveTo(x, y);
return true;
}
return false;
}
} |
____________________________
- Comentarios.
- Se observa que se crea un Canvas (Lienzo) para poder poner los dibujos Sprite.
- El dibujo moleSprite.Picture("mole.png") debe estar en la carpeta "assets", la manera de crear esta carpeta lo vimos en el tutorial anterior.
- Otros componentes usa como contenedor un HorizontalArrangement (DisposiciónHorizontal).
- Recuerda que this, significa que el componente está sobre la pantalla, es decir this es la pantalla.
moleClock = new Clock(this);
timeLeftValueLabel= new Label(horizArrangement);
______________
- Eventos.
Vamos a ver tres eventos...
1.- When the Mole is Touched. Cuando se Toca el dibujo Sprite Mole...
When the Mole is Touched. |
public boolean dispatchEvent(Component component, String componentName, String eventName, Object[] params )
{
// when mole is touched, add a point. Need to covert text to int and back
if( component.equals(moleSprite) && eventName.equals("Touched") )
{
int score = Integer.parseInt(scoreValueLabel.Text());
score = score + 1;
scoreValueLabel.Text(String.valueOf(score));
return true;
} |
- En App inventor se puede pasar directamente de caracteres numéricos a variables numéricas. En Java no. Debemos convertir de caracteres numéricos a números y viceversa según lo necesite el código.
scoreValueLabel.Text es un caracter numérico, para pasarlo a número entero utilizamos Integer.parseInt
"7" -------------------------------------------------------------------------------------------> 7
Al revés:
scoreValueLabel.Text(String.valueOf(score));
Pasa el número 7 a "7" para poder ser presentado en el Label1.Text
2.- When the MoleClock.Timer Triggers. Cuando pasa un Intervalo en el Reloj...
When the MoleClock.Timer Triggers. |
// on mole timer, move the mole randomly
if( component.equals(moleClock) && eventName.equals("Timer") )
{
Random random = new Random();
int x= random.nextInt(canvas1.Width()-moleSprite.Width());
int y= random.nextInt(canvas1.Height()-moleSprite.Height());
moleSprite.MoveTo(x, y);
return true;
} |
- Para generar números aleatorios se utilizar random.nextInt
- En este caso cada vez que pasa un Intervalo en el Reloj Timer, se generan dos números aleatorios.
- Los números entre paréntesis indica el límite del número aleatorio generado y está relacionado con el tamaño del Lienzo y el Sprite.
3.- When the GameClock.Timer Triggers. Cuando pasa un Intervalo en el Reloj...
When the GameClock.Timer Triggers. |
// count down the clock on the clock timer
if( component.equals(gameClock) && eventName.equals("Timer") )
{
int count = Integer.parseInt(timeLeftValueLabel.Text());
count = count - 1;
timeLeftValueLabel.Text(String.valueOf(count));
if (count==0) {
//game is over
gameClock.TimerEnabled(false);
moleClock.TimerEnabled(false);
timeLeftValueLabel.Text("Game Over");
}
return true;
} |
- Se observa que también hay conversión de carácter numérico a valor numérico y viceversa.
int count = Integer.parseInt(timeLeftValueLabel.Text());
timeLeftValueLabel.Text(String.valueOf(count));
__________________________________
|