Jme - sdk - application mobile - attrape les ipod qui tombent

Description

Petit appli mobile avec le SDK 3.0. (Tomcat 6)
Il faut déplacer un petit panier afin de rattraper les IPod qui tombent du ciel :)

Ce code montre donc l'utilisation du ramdom, timer, graphics, vector, etc.
Utilisation également des sons.

Source / Exemple :


GamerMIDlet.java

package com.supinfo.sun.ipodgrabber.midlets;
import com.supinfo.sun.ipodgrabber.beans.GameCanvas;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.*;

public class GamerMIDlet extends MIDlet implements CommandListener {

    private Form gamerForm;
    private ChoiceGroup difficultyList;
    private TextField gamerNameTextField;
    private Command startCommand;
    private Command exitCommand;
    private Display display;
    private GameCanvas canvas;
    private static GamerMIDlet currentInstance;

    public GamerMIDlet() {
        this.gamerForm= new Form("Game info");
        String[] s=new String[] {"Easy","Medium","Hard"};
        this.gamerNameTextField= new TextField("Name","",20,TextField.ANY);
        this.gamerForm.append(gamerNameTextField);
        
        this.difficultyList= new ChoiceGroup("Difficulty level", ChoiceGroup.EXCLUSIVE,s,null);
        this.gamerForm.append(difficultyList);

        this.startCommand= new Command("Menu",Command.OK,10);
        this.gamerForm.addCommand(startCommand);

        this.exitCommand= new Command("Exit",Command.EXIT,20);
        this.gamerForm.addCommand(exitCommand);

        this.display= Display.getDisplay(this);

        this.gamerForm.setCommandListener(this);
        GamerMIDlet.currentInstance = this;
    }

    public static GamerMIDlet getCurrentInstance() {
        return currentInstance;
    }
    
    public void startApp() {
        this.display.setCurrent(this.gamerForm);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }
    
    public void commandAction(Command c, Displayable d) {
        if (c.equals(startCommand)) {
            this.canvas= new GameCanvas(this.gamerNameTextField.getString(), this.difficultyList.getSelectedIndex()+1);
            System.out.println("***new Game name: "+this.gamerNameTextField.getString());
            this.display.setCurrent(this.canvas);
            this.canvas.repaint();
        }else {
            notifyDestroyed();
        }
    }
    
}
----------------------------------------------------------------------------------------
IPodGenerator.java

package com.supinfo.com.ipodgrabber.tasks;

import com.supinfo.sun.ipodgrabber.beans.GameCanvas;
import java.util.TimerTask;

public class IPodGenerator extends TimerTask{
    private GameCanvas canvas;

    public IPodGenerator(GameCanvas canvas) {
        this.canvas = canvas;
    }

    public void run() {
        canvas.generateIpod();
    }

----------------------------------------------------------------------------------------
IPodMover.java

package com.supinfo.com.ipodgrabber.tasks;

import com.supinfo.sun.ipodgrabber.beans.GameCanvas;
import java.util.TimerTask;

public class IPodMover extends TimerTask {
    private GameCanvas canvas;

    public IPodMover(GameCanvas canvas) {
        this.canvas = canvas;
    }
    
    public void run() {
        canvas.moveIpods();
    }

}
----------------------------------------------------------------------------------------
GameCanvas.java

package com.supinfo.sun.ipodgrabber.beans;

import com.supinfo.com.ipodgrabber.tasks.IPodGenerator;
import com.supinfo.com.ipodgrabber.tasks.IPodMover;
import com.supinfo.sun.ipodgrabber.midlets.GamerMIDlet;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import java.util.Timer;
import java.util.Vector;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Graphics;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.rms.RecordStore;

public class GameCanvas extends Canvas implements CommandListener{
    private String name;
    private Random random;
    private Vector ipods;
    private Basket basket;
    private int score;
    private int life;
    private int level;
    
    private Timer timer;
    private IPodGenerator generator;
    private IPodMover mover;

    private Command viewScoreCommand;
    private Command replayCommand;

    public GameCanvas(String name, int level) {
        this.name = name;
        this.level = level;
        this.random= new Random();
        this.ipods= new Vector();
        this.basket= new Basket();
        this.score=0;
        this.life= 4;

        basket.setX(0);
        basket.setY(this.getHeight()-19-this.basket.getHeight());

        this.timer= new Timer();
        this.generator= new IPodGenerator(this);
        this.mover= new IPodMover(this);
        this.timer.schedule(generator, 0, 5000/this.level);
        this.timer.schedule(mover, 100, 500/this.level);

        this.viewScoreCommand=new Command("Scores", Command.OK, 30);
        this.replayCommand=new Command("Replay", Command.OK, 40);
    }

    public void generateIpod() {
        IPod ipod= new IPod(this.random.nextInt(7)+1);
        ipod.setX(this.random.nextInt(this.getWidth()-ipod.getWidth()));
        this.ipods.addElement(ipod);
        repaint();
    }

    public void moveIpods() {
        for (int i = 0; i < ipods.size(); i++) {
            IPod iPod = (IPod) this.ipods.elementAt(i);
            iPod.setY(iPod.getY()+10);
            if (iPod.getY() > this.getHeight()) {
                this.ipods.removeElementAt(i);
                playExplosion();
                this.life--;
                iPod = (IPod) this.ipods.elementAt(i);
                iPod.setY(iPod.getY()+10);
                if (this.life==0) {
                    this.gameOver();
                }
            }else{
                if (hasHurtBasket(iPod)){
                    this.ipods.removeElement(iPod);
                    playBip();
                    this.score+=10;
                    iPod = (IPod) this.ipods.elementAt(i);
                    iPod.setY(iPod.getY()+10);
                }
            }
        }
        repaint();
    }

    protected void keyPressed(int keyCode) {
        if ((getGameAction(keyCode) == RIGHT) && (this.basket.getX()<this.getWidth()-this.basket.getWidth())) {
            this.basket.setX(this.basket.getX()+10);
        } else if((getGameAction(keyCode) == LEFT) && (this.basket.getX()>0)) {
            this.basket.setX(this.basket.getX()-10);
        }
    }
    
    public void paint(Graphics g) {
        g.setColor(0, 175, 242);
        g.fillRect(UP, UP, this.getWidth(), this.getHeight());
        for (int i = 0; i < ipods.size(); i++) {
            IPod iPod = (IPod) ipods.elementAt(i);
            g.drawImage(iPod.getImage(), iPod.getX(), iPod.getY(), Graphics.TOP | Graphics.LEFT);
        }
        g.drawImage(basket.getImage(), basket.getX(), basket.getY(), 0);
        g.setColor(0, 0, 0);
        g.drawString("Score: "+this.score+"_Life: "+this.life, UP, UP, Graphics.TOP | Graphics.LEFT);

        if (this.life<1) {
            g.setColor(0, 255, 0);
            g.fillRect(UP, UP, this.getWidth(), this.getHeight());
            g.setColor(255, 0, 0);
            g.drawString("Game over", this.getWidth()/2, this.getHeight()/2, Graphics.TOP | Graphics.HCENTER);
        }
    }

    private boolean hasHurtBasket(IPod i) {
        if ((this.basket.getX() <= i.getX()) && (i.getX()+i.getWidth() <= this.basket.getX()+this.basket.getWidth())) {
            if ((this.basket.getY() <= i.getY()+i.getHeight()) && ((this.basket.getY()+this.basket.getHeight()/2) >= i.getY()+i.getHeight()) )
            return true;
        }
        return false;
    }

    private void gameOver() {
        playGameOver();
        this.generator.cancel();
        this.mover.cancel();
        this.timer.cancel();
        this.ipods.removeAllElements();
        this.saveScore();
        this.addCommand(viewScoreCommand);
        this.setCommandListener(this);
    }

    private void saveScore() {
        byte[] score1=null,score2=null,score3=null;
        PlayerScore pScore1 = new PlayerScore(),pScore2 = new PlayerScore(),pScore3 = new PlayerScore();
        RecordStore store=null;
        try {
            store=RecordStore.openRecordStore("Scores", true);
        }catch (Exception e){
            //e.printStackTrace();
        }
        try{
            score1 = store.getRecord(1);
        }catch (Exception e){
            //e.printStackTrace();
        }
        try{
            score2 = store.getRecord(2);
        }catch (Exception e){
            //e.printStackTrace();
        }
        try{
            score3 = store.getRecord(3);
        }catch (Exception e){
            //e.printStackTrace();
        }
        //System.out.println("***store and scores***");
            if (score1==null) {
                try{
                    pScore1=new PlayerScore(this.name, this.level, this.score);
                    //System.out.println("***1"+this.name+" "+this.level+" "+this.score+"***");
                    score1=pScore1.toByteArray('-');
                }catch (Exception e){
                    //e.printStackTrace();
                }
                try{
                    store.addRecord(score1, 0, score1.length);
                }catch (Exception e){
                    //System.out.println("addRecord score1 error");
                    //e.printStackTrace();
                }
            }else {
                if (score2==null) {
                    pScore1.parseByteArray(score1, '-');
                    pScore2=new PlayerScore(this.name, this.level, this.score);
                    System.out.println("***2"+this.name+" "+this.level+" "+this.score+"***");
                    score2=pScore2.toByteArray('-');
                    if (pScore1.getScore()>pScore2.getScore()) {
                        try{
                            store.addRecord(score2, 0, score2.length);
                        }catch (Exception e){
                            //System.out.println("***addRecord score2 error");
                            //e.printStackTrace();
                        }
                    }else{
                        try{
                            store.addRecord(score1, 0, score1.length);
                            store.setRecord(1, score2, 0, score2.length);
                        }catch (Exception e){
                            //System.out.println("***addRecord score1/setRecord score2 error");
                            //e.printStackTrace();
                        }
                    }
                }else {
                    if (score3==null) {
                        pScore1.parseByteArray(score1, '-');
                        pScore2.parseByteArray(score2, '-');
                        pScore3=new PlayerScore(this.name, this.level, this.score);
                        System.out.println("***3"+this.name+" "+this.level+" "+this.score+"***");
                        score3=pScore3.toByteArray('-');
                        if (pScore3.getScore()>pScore1.getScore()) {
                            try{
                                store.setRecord(1, score3, 0, score3.length);
                                store.setRecord(2, score1, 0, score1.length);
                                store.addRecord(score2, 0, score2.length);
                            }catch (Exception e){
                                //e.printStackTrace();
                            }
                        }else{
                            if (pScore3.getScore()<pScore2.getScore()) {
                                try{
                                    store.addRecord(score3, 0, score3.length);
                                }catch (Exception e){
                                    //e.printStackTrace();
                                }
                            }else{
                                try{
                                    store.setRecord(2, score3, 0, score3.length);
                                    store.setRecord(3, score2, 0, score2.length);
                                }catch (Exception e){
                                    //e.printStackTrace();
                                }
                            }
                        }
                    }else{
                        pScore1.parseByteArray(score1, '-');
                        pScore2.parseByteArray(score2, '-');
                        pScore3.parseByteArray(score3, '-');
                        if (this.score>pScore3.getScore()){
                            pScore3=new PlayerScore(this.name, this.level, this.score);
                            score3=pScore3.toByteArray('-');
                            if (pScore3.getScore()>pScore1.getScore()) {
                                try{
                                store.setRecord(1, score3, 0, score3.length);
                                store.setRecord(2, score1, 0, score1.length);
                                store.setRecord(3,score2, 0, score2.length);
                                }catch (Exception e){
                                    //e.printStackTrace();
                                }
                            }else{
                                if (pScore3.getScore()<pScore2.getScore()) {
                                    try{
                                        store.setRecord(3,score3, 0, score3.length);
                                    }catch (Exception e){
                                        //e.printStackTrace();
                                    }
                                }else{
                                    try{
                                        store.setRecord(2, score3, 0, score3.length);
                                        store.setRecord(3, score2, 0, score2.length);
                                    }catch (Exception e){
                                        //e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                }
            }
    }

    public void commandAction(Command c, Displayable d) {
        PlayerScore pScore1 = new PlayerScore(),pScore2 = new PlayerScore(),pScore3 = new PlayerScore();
        byte[] score1=null,score2=null,score3=null;
        RecordStore store=null;
        if (c.equals(this.replayCommand)) {
            GamerMIDlet.getCurrentInstance().startApp();
        }else{
            if (c.equals(this.viewScoreCommand)) {
                try {
                    store=RecordStore.openRecordStore("Scores", true);
                }catch (Exception e){
                    //System.out.println("openRecordStore error");
                }
                try{
                    score1 = store.getRecord(1);
                }catch (Exception e){
                    //System.out.println("getRecord1 error");
                }
                try{
                    score2 = store.getRecord(2);
                }catch (Exception e){
                    //System.out.println("getRecord2 error");
                }
                try{
                    score3 = store.getRecord(3);
                }catch (Exception e){
                    //System.out.println("getRecord3 error");
                }
                try{
                    pScore1.parseByteArray(score1, '-');
                    pScore2.parseByteArray(score2, '-');
                    pScore3.parseByteArray(score3, '-');
                    Form form=new Form("Scores");
                    form.append("1- "+pScore1.getPlayerName()+": "+pScore1.getScore()+"\n");
                    if (pScore2.getPlayerName() != null){
                        form.append("2- "+pScore2.getPlayerName()+": "+pScore2.getScore()+"\n");
                        if (pScore3.getPlayerName() != null){
                            form.append("3- "+pScore3.getPlayerName()+": "+pScore3.getScore());
                        }
                    }
                    form.addCommand(this.replayCommand);
                    form.setCommandListener(this);
                    Display.getDisplay(GamerMIDlet.getCurrentInstance()).setCurrent(form);
                }catch (Exception e){
                    //System.out.println("exception a la fin");
                    //e.printStackTrace();
                }
                
            }
        }
    }

    private void playBip() {
        InputStream is=getClass().getResourceAsStream("/com/supinfo/sun/ipodgrabber/resources/sounds/bip.wav");
        try {
            Player player = Manager.createPlayer(is, "audio/x-wav");
            player.realize();
            player.prefetch();
            player.start();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (MediaException ex) {
            ex.printStackTrace();
        }
    }

    private void playExplosion() {
        InputStream is=getClass().getResourceAsStream("/com/supinfo/sun/ipodgrabber/resources/sounds/explosion.wav");
        try {
            Player player = Manager.createPlayer(is, "audio/x-wav");
            player.realize();
            player.prefetch();
            player.start();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (MediaException ex) {
            ex.printStackTrace();
        }
    }

    private void playGameOver() {
        InputStream is=getClass().getResourceAsStream("/com/supinfo/sun/ipodgrabber/resources/sounds/gameOver.wav");
        try {
            Player player = Manager.createPlayer(is, "audio/x-wav");
            player.realize();
            player.prefetch();
            player.start();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (MediaException ex) {
            ex.printStackTrace();
        }
    }
}
---------------------------------------------------------------------------------
Basket.java

package com.supinfo.sun.ipodgrabber.beans;

import javax.microedition.lcdui.Image;

public class Basket {
    private int x;
    private int y;
    private int width;
    private int height;
    private Image image;

    public Basket() {
        try {
            this.image = Image.createImage(getClass().getResourceAsStream("/com/supinfo/sun/ipodgrabber/resources/images/basket.png"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.width = this.image.getWidth();
        this.height = this.image.getHeight();
    }

     public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getHeight() {
        return height;
    }

    public Image getImage() {
        return image;
    }

    public int getWidth() {
        return width;
    }
}

------------------------------------------------------------------------
IPod.java

package com.supinfo.sun.ipodgrabber.beans;

import javax.microedition.lcdui.Image;

public class IPod {
    private int x;
    private int y;
    private int width;
    private int height;
    private Image image;

    public IPod(int imgNumber) {
        try {
            if ((imgNumber<=1) || (imgNumber>7)) {
                this.image = Image.createImage(getClass().getResourceAsStream("/com/supinfo/sun/ipodgrabber/resources/images/ipod_1.png"));
            }else{
                this.image = Image.createImage(getClass().getResourceAsStream("/com/supinfo/sun/ipodgrabber/resources/images/ipod_"+imgNumber+".png"));
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        this.width = this.image.getWidth();
        this.height = this.image.getHeight();
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getHeight() {
        return height;
    }

    public Image getImage() {
        return image;
    }

    public int getWidth() {
        return width;
    }

}

------------------------------------------------------------------------------
PlayerScore.java

package com.supinfo.sun.ipodgrabber.beans;

public class PlayerScore {
    private String playerName;
    private int level, score;

    public PlayerScore() {
    }

    public PlayerScore(String playerName, int level, int score) {
        this.playerName = playerName;
        this.level = level;
        this.score = score;
    }

    public int getLevel() {
        return level;
    }

    public void setLevel(int level) {
        this.level = level;
    }

    public String getPlayerName() {
        return playerName;
    }

    public void setPlayerName(String playerName) {
        this.playerName = playerName;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public void parseByteArray(byte[] record, char separator) {
        if(record != null) {
            String values = new String(record);
            int index = values.indexOf(separator);
            int lastIndex = values.lastIndexOf(separator);
            this.playerName = values.substring(0, index);
            this.level = Integer.parseInt(values.substring(index+1, lastIndex));
            this.score = Integer.parseInt(values.substring(lastIndex+1));
        }
    }

    public byte[] toByteArray(char separator) {
        return (this.playerName + separator + this.level + separator +
                this.score).getBytes();
    }
    
}

-------------------------------------------------------------------------
FIN :)

Codes Sources

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.