⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 combatcanvas.java

📁 欢迎使用蓝牙联网坦克大战
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
package newpackagetank;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Random;

import javax.bluetooth.L2CAPConnection;
import javax.microedition.io.Connection;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Canvas;


import org.apache.log4j.Category;

import newpackage.BlueConfig;
import newpackage.Utility;

public class CombatCanvas extends Canvas implements CommandListener, Runnable {

    /** Game constants */
    private static final int MILLIS_PER_TICK = 10;
    /** Constants for interconnection protocol between client and server */
    private static final int SIGNAL_RESTART = 0;
    private static final int SIGNAL_SCREEN_SIZE_REQ = 1;
    private static final int SIGNAL_SCREEN_SIZE_ACK = 2;
    private static final int SIGNAL_SCREEN_SIZE_CONFIRM = 3;
    private static final int SIGNAL_SCREEN_SIZE_CONFIRM_ACK = 4;
    private static final int SIGNAL_RANDOM_GUI_DATA = 5;
    private static final int SIGNAL_SHOOT = 6;
    private static final int SIGNAL_ENEMY_TANK = 7;
    private static final int SIGNAL_START_ENEMY = 8;
    private static final int SIGNAL_ENEMY_BULLET = 9;
    private static final int SIGNAL_DEATH = 11;
    private static final int SIGNAL_MAP = 12;
    
    
    static Category log = Category.getInstance("panci.combat.CombatCanvas");
    private final TankMidlet combatMIDlet;
    private MainCanvas m_MainCanvas;
    private Command exitCommand;
    private Command restartCommand;
    private Command logCommand;
    private static Random random = new Random();
    private int screenWidth; // Screen width (agreed with client and server)
    private int screenHeight; // Screen height (agreed with client and server)
    private volatile Thread animationThread = null;
    private boolean initDone = false;
    private String initPaintMessage = "Waiting for the other device...";
    /** Number of milliseconds to wait before a connection.receive() */
    protected int waitBeforeReceiveData = 0;
    /** Connection protocol to use (SPP o L2CAP) */
    protected int connectionProtocol;
    private Connection conn = null;
    private DataOutputStream out = null;
    private DataInputStream in = null;
    private Reader reader = null;

    public CombatCanvas(TankMidlet combatMIDlet) {
        super();
        log.debug("Constructor!");
        this.combatMIDlet = combatMIDlet;
        //chooseParametersCommand = new Command("Choose Parameters", Command.SCREEN, 1);
        restartCommand = new Command("Restart", Command.SCREEN, 2);
        exitCommand = new Command("Exit", Command.EXIT, 1);
        if (combatMIDlet.isLogAvailable()) {
            logCommand = new Command("Log", Command.SCREEN, 3);
            addCommand(logCommand);
        }
        addCommand(exitCommand);
        setCommandListener(this);
    //turn = 1;
    }

    /**
     * Restart game.
     * This method is called either by server and by client (and in stand alone mode) 
     * When it's called, it informs the client which in turn will call this method to restart.
     *
     */
    public void restart() {

        if (combatMIDlet.getGameMode() == TankMidlet.SERVER_MODE) {
            if (connectionProtocol == BlueConfig.PROTOCOL_L2CAP) {
                sendInt(SIGNAL_RESTART);
            } else {
                try {
                    out.writeInt(SIGNAL_RESTART);
                    out.flush();
                } catch (IOException e) {
                    log.error("Error in restart: " + e.getMessage());
                    e.printStackTrace();
                }
            }
        // logSignal(SIGNAL_RESTART);
        }

    }

    private void initDone() {
        initDone = true;
        repaintAll();
    }

    private void setInitPaintMessage(String msg) {
        if (log.isDebugEnabled()) {
            initPaintMessage = msg;
            repaintAll();
        }
    }

    public void paint(Graphics g) {

    }

    public void resetPosition(int x) {

        m_MainCanvas.setTankNewPosition(x);

    }

    public void setEnemyTank(int dir, int num) {
        m_MainCanvas.setEnemyTankNewPosition(dir, num);

    }

    public void startServerEnemy(int start) {
        m_MainCanvas.startServerEnemy(start);

    }

    public void startEnemyBullet(int sh, int num) {
        m_MainCanvas.startEnemyBullet(sh, num);
    }
    
    public void resetMap(int col, int row){
        m_MainCanvas.resetMap(col, row);
    }

    public void setDeath(int num) {
        m_MainCanvas.setDeath(num);
    }

    static int random(int scale) {
        int randomInt = random.nextInt();
        // extend to long, but remove sign-extend
        long randomIntAsLong = (long) randomInt & 0xFFFFFFFFL;
        int result = (int) ((randomIntAsLong * (long) scale) >> 32);
        return result;
    }

    public void commandAction(Command c, Displayable d) {
        log.debug("commandAction: " + c.getLabel() + ", " + d.getTitle());

        if (c == restartCommand) {
            combatMIDlet.restart();

        } else if (c == exitCommand) {
            combatMIDlet.quit();
        } else if (c == logCommand) {
            combatMIDlet.showLog(this);
        }
    }

    private synchronized void stopThread() {

        animationThread = null;

    }

    private void repaintAll() {
        repaint(0, 0, screenWidth, screenHeight);
        serviceRepaints();
    }

    public void run() {
        Thread currentThread = Thread.currentThread();

        try {
            // This ends when animationThread is set to null, or when
            // it is subsequently set to a new thread; either way, the
            // current thread should terminate
            while (currentThread == animationThread) {
                long startTime = System.currentTimeMillis();

                repaintAll();
                long timeTaken = System.currentTimeMillis() - startTime;
                if (timeTaken < MILLIS_PER_TICK) {
                    synchronized (this) {
                        wait(MILLIS_PER_TICK - timeTaken);
                    }
                } else {
                    Thread.yield();
                }
            }
        } catch (InterruptedException e) {
        // ignore
        }
    }

    /**
     * To start the game, you need to create an instance of this class and
     * call startGame(). The midlet should have set correctly the properties
     * gameMode and connection.
     */
    public void startGame() {
        if (combatMIDlet.getGameMode() == TankMidlet.STAND_ALONE_MODE) {
            System.out.println("开始单机模式");
            startStandAloneGame();
        }
        if (combatMIDlet.getGameMode() == TankMidlet.SERVER_MODE) {
            startServerGame(combatMIDlet.getConnection());
        }
        if (combatMIDlet.getGameMode() == TankMidlet.CLIENT_MODE) {
            startClientGame(combatMIDlet.getConnection());
        }
    }

    private void startStandAloneGame() {
        log.debug("startStandAloneGame");

        if (m_MainCanvas == null) {
            m_MainCanvas = new MainCanvas(combatMIDlet, this, TankMidlet.STAND_ALONE_MODE);
        }
        Display.getDisplay(combatMIDlet).setCurrent(m_MainCanvas);


    }

    private void startServerGame(Connection connection) {
        // set the user commands
        log.debug("startServerGame");
        addCommand(restartCommand);


        // save the connection and open the streams
        initDone = false;
        connectionProtocol = combatMIDlet.getConnectionProtocol();
        log.debug("connectionProtocol = " + connectionProtocol);
        waitBeforeReceiveData = combatMIDlet.getWaitBeforeReceiveData();
        log.debug("waitBeforeReceiveData = " + waitBeforeReceiveData);

        conn = connection;
        if (connectionProtocol == BlueConfig.PROTOCOL_SPP) {
            if (out == null) {
                try {
                    out = ((StreamConnection) conn).openDataOutputStream();
                    in = ((StreamConnection) conn).openDataInputStream();
                } catch (IOException e) {
                    log.error("Can't read from server: " + e.getMessage());
                    e.printStackTrace();
                }
            }
            log.debug("Aperti out e in!");
        }

        // start the thread which listens to the other device's messages
        if (reader == null) {
            reader = new Reader();
            new Thread(reader).start();
        }

        // Let's wait a while, to be sure that the reader has started
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
        }

        // start the protocol to exchange the configuration parameters

        askForScreenSizeToClient();

        if (m_MainCanvas == null) {
            m_MainCanvas = new MainCanvas(combatMIDlet, this, TankMidlet.SERVER_MODE);
        }
        Display.getDisplay(combatMIDlet).setCurrent(m_MainCanvas);

    }

    /**
     * startClientGame does:
     *  - set the user commands
     *  - save the connection and open the streams
     *  - start the thread which listens to the other device's messages
     * 
     * @param connection
     */
    private void startClientGame(Connection connection) {
        // set the user commands
        log.debug("startClientGame");


        // save the connection and open the streams
        initDone = false;
        connectionProtocol = combatMIDlet.getConnectionProtocol();
        log.debug("connectionProtocol = " + connectionProtocol);
        waitBeforeReceiveData = combatMIDlet.getWaitBeforeReceiveData();
        log.debug("waitBeforeReceiveData = " + waitBeforeReceiveData);

        conn = connection;
        if (connectionProtocol == BlueConfig.PROTOCOL_SPP) {
            if (out == null) {
                try {
                    out = ((StreamConnection) conn).openDataOutputStream();
                    in = ((StreamConnection) conn).openDataInputStream();
                } catch (IOException e) {
                    log.error("Can't read from client: " + e.getMessage());
                    e.printStackTrace();
                }
            }
        }

        // start the thread which listens to the other device's messages
        if (reader == null) {
            reader = new Reader();
            new Thread(reader).start();
        }
        while (!initDone) {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
            }
        }
        if (m_MainCanvas == null) {
            m_MainCanvas = new MainCanvas(combatMIDlet, this, TankMidlet.CLIENT_MODE);
        }
        Display.getDisplay(combatMIDlet).setCurrent(m_MainCanvas);
    }

    /**
     * Ask to client the screen sizes, in order to use for both devices
     * the smallest sizes.
     */
    private void askForScreenSizeToClient() {
        if (connectionProtocol == BlueConfig.PROTOCOL_L2CAP) {

            String str = String.valueOf(SIGNAL_SCREEN_SIZE_REQ);

            str += "*";

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -