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

📄 mazenetwork.java

📁 在eclipse的环境下开发的迷宫对战游戏
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
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.Item;
import javax.microedition.lcdui.ItemCommandListener;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

public class MazeNetwork extends MIDlet 
		implements CommandListener, ItemCommandListener  {
	Display display = null;

	/**
	 * 在实际开发中,这里应该替换为服务器的真实地址
	 */
	private static final String SERVER_URL = "socket://localhost:9999";
    
	Command cmdOK = null;
	Command cmdExit = null;
	
	// ====================登录对话框==========================
	Form frmLogin = null;
	TextField tfUserName = null;
	TextField tfPass = null;

	//=====================游戏大厅============================
	Form frmHall = null;
	Command cmdLogin = null;
    Command cmdPlay = null;
	
    
	/** 游戏画布 */
	MazeGameCanvas canMaze = null;
	
	String curUserName = "";
    
    /** 
     * 当但送命令时设置为true,发送完成设置为fasel。
     * 在为true时,不在独立线程中接收其他的命令
     */
    boolean isSendingCmd = false; 
    
    /**
     * 客户端运行标志
     */
	boolean isRunning = false;
    
    SocketConnection sc = null;
	DataInputStream dis = null;
	DataOutputStream dos = null;

	public MazeNetwork() {
		super();

		cmdOK = new Command("确定", Command.SCREEN, 1);
		cmdExit = new Command("退出", Command.EXIT, 0);
		
		//初始化登录对话框
		frmLogin = new Form("登录系统");
		tfUserName = new TextField("用户名: ", "", 20, TextField.ANY);
		tfPass = new TextField("密码: ", "", 20, TextField.PASSWORD);
		frmLogin.append(tfUserName);
		frmLogin.append(tfPass);
		frmLogin.addCommand(cmdOK);
		frmLogin.addCommand(cmdExit);
		frmLogin.setCommandListener(this);
		
		//初始化游戏大厅
		frmHall = new Form("游戏大厅");
		cmdLogin = new Command("重新登录", Command.SCREEN, 1);
        cmdPlay = new Command("开始游戏", Command.SCREEN, 1);
		frmHall.addCommand(cmdLogin);
        frmHall.addCommand(cmdPlay);
		frmHall.addCommand(cmdExit);
		frmHall.setCommandListener(this);	
	}

	protected void startApp() throws MIDletStateChangeException {
		display = Display.getDisplay(this);
		displayLoginForm(null);
	}

	protected void pauseApp() {
		close();
	}

	protected void destroyApp(boolean arg0)
		throws MIDletStateChangeException {

		close();
	}

	//------------------------------------------------用户界面处理-开始
	
	/**
	 * 显示登录对话框
	 */
	private void displayLoginForm(Alert alert) {
		tfUserName.setString("");
		tfPass.setString("");
		if (alert == null) {
			display.setCurrent(frmLogin);
		} else {
			display.setCurrent(alert, frmLogin);
		}
	}
	
	/**
	 * 显示游戏大厅
	 *
	 */
	private void displayGameHall() {
		frmHall.deleteAll();
		
		for(int i=1;i<=50;i++) {
			TableItem si = new TableItem("", "#" + 
					String.valueOf(i) + ": \n", Item.BUTTON);
			si.number = i-1;
            si.setDefaultCommand(cmdOK);
			si.setItemCommandListener(this);
			frmHall.append(si);
		}
		display.setCurrent(frmHall);
		
	}
	
	/**
	 * 显示错误信息,之后重新进行登录
	 *
	 */
	private void displayErrorAlert() {
        isRunning = false;
        
		//显示登录错误提示对话框他
        Alert alert = new Alert(
        		"登录错误",
        		"错误原因:\n" +
        		"1. 用户名/密码错误\n" +
        		"2. 服务器不可用\n" +
        		"3. 网络故障\n" +
        		"请重试",
                null, AlertType.ALARM);
        alert.setTimeout(2000);
        displayLoginForm(alert);
	}
	
	//------------------------------------------------用户界面处理-结束
	
	
	
	//-------------------------------------打开和关闭与服务器的连接-开始	
	/**
	 * 关闭Socket的连接
	 */
	private void close() {
        isRunning = false;
        
		if (dis != null) {
			try {
				dis.close();
				dis = null;
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}

		if (dos != null) {
			try {
				dos.close();
				dos = null;
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}

		if (sc != null) {
			try {
				sc.close();
				sc = null;
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
	}

	/**
	 * 打开Socket连接
	 */
	private void open(){
		close();
		try {
			sc = (SocketConnection) Connector.open(SERVER_URL);
			sc.setSocketOption(SocketConnection.KEEPALIVE, 1);
			sc.setSocketOption(SocketConnection.LINGER, 5);
			dis = sc.openDataInputStream();
			dos = sc.openDataOutputStream();
		} catch (Exception e) {
			e.printStackTrace();
            return;
		}
        receivingThread();
	}
    //-------------------------------------打开和关闭与服务器的连接-结束
    
    //----------------------------------------接收和处理服务器命令-开始
    /**
     * 用于接收从服务器发送来的命令,
     * 例如CMD_SIT,CMD_MOVE等。
     * 只在isSendingCmd为false时工作。
     *
     */
    private void receivingThread() {
        isRunning = true;
        
        new Thread() {
            public void run() {
                while(isRunning) {
                    try {
                        Thread.sleep(800);
                    } catch (Exception e) {}
                                        
                    if (isSendingCmd) {
                        continue;
                    }
                    
                    try {
                        if (dis.available()>0) {
                            handleCmd();
                        }
                    } catch (Exception e) {
                        displayErrorAlert();
                        break;
                    }
                } 
            }
        }.start();        
    }
    
    /**
     * 处理服务器命令
     */
    private void handleCmd() throws IOException{
        if ((sc == null) || (dis == null) || (dos == null)) {
            return;
        }
        
        byte cmd = dis.readByte();
        System.out.println("处理来自服务器的命令:"+cmd);
        switch(cmd) {
            case 0:
                break;
            case MazeProtocol.CMD_SIT:
                if (display.getCurrent() == frmHall) {
                    handleSitDown();
                }
                break;
            case MazeProtocol.CMD_STAND:
                if (display.getCurrent() == frmHall) {
                    handleStandUp();
                }
                break;
            case MazeProtocol.CMD_EXIT:
                handleExit();
                break;
            case MazeProtocol.CMD_STARTGAME:
                if (display.getCurrent() == frmHall) {
                    handleStartGame();
                }
                break;
            case MazeProtocol.CMD_MOVE:
            	if (display.getCurrent() == canMaze) {
            		handleMove();
            	}
            	break;
            case MazeProtocol.CMD_WIN:
            	if (display.getCurrent() == canMaze) {
            		Alert alert = new Alert("对不起,对方走出了迷宫");
            		alert.setString("游戏失败!!!");
            		alert.setType(AlertType.INFO);
            		alert.setTimeout(Alert.FOREVER);
            		canMaze.isRunning = false;
            		display.setCurrent(frmHall);
            	}
            	break;
        }
    }
    
    /**
     * 处理服务器发送过来的坐下命令,
     * 一般为有用户坐下后,通知其他客户端更新界面
     *
     */
    private void handleSitDown() {
        if ((sc == null) || (dis == null) || (dos == null)) {
            return;
        }
        
        int number = -1;
        byte pos = 0;
        int size = 0;
        byte[] data = null;
        String username=null;
        
        //读取协议命令
        try {
            number = dis.readInt();
            pos = dis.readByte();
            size = dis.readInt();
            data = new byte[size];
            dis.read(data);
            username = new String(data, "UTF-8");
        } catch (IOException e) {
            return;
        }         
        
        //显示添加的用户
        if(number > -1 && number < frmHall.size()) {
            TableItem ti = (TableItem)frmHall.get(number);
            if (ti.getUser(pos)==null) {
                ti.setUser(pos, username);
            }
        }
    }
    
    private void handleStandUp() {
        if ((sc == null) || (dis == null) || (dos == null)) {
            return;
        }
        
        int number = -1;
        byte pos = 0;
        int size = 0;
        byte[] data = null;
        String username=null;
        
        //读取协议命令
        try {
            number = dis.readInt();
            pos = dis.readByte();
            size = dis.readInt();
            data = new byte[size];
            dis.read(data);
            username = new String(data, "UTF-8");
        } catch (IOException e) {
            return;
        }   
        
        //删除用户
        if(number > -1 && number < frmHall.size()) {
            TableItem ti = (TableItem)frmHall.get(number);
            String un = ti.getUser(pos); 
            if (un!=null && un.equals(username)) {
                ti.setUser(pos, null);
            }
        }
    }
    
    
    private void handleExit() {
        if ((sc == null) || (dis == null) || (dos == null)) {
            return;
        }
        
        int number = -1;
        int size = 0;
        byte[] data = null;
        String username=null;       
        //读取协议命令
        try {
            number = dis.readInt();
            size = dis.readInt();
            data = new byte[size];
            dis.read(data);
            username = new String(data, "UTF-8");
        } catch (IOException e) {
            return;
        } 
        
        //删除用户
        if(number > -1 && number < frmHall.size()) {
            TableItem ti = (TableItem)frmHall.get(number);
            String un1 = ti.getUser(0);
            String un2 = ti.getUser(1);
            Displayable disp = display.getCurrent();
            
            if (un1!=null && un1.equals(username)) {
                //是否在游戏状态   
                if (disp == frmHall) {
                    ti.setUser(0, null);
                } else {
                    if (un2!=null && un2.equals(curUserName)){
                        canMaze.isRunning = false;
                        display.setCurrent(frmHall);
                    }   
                }
            }
            
            if (un2!=null && un2.equals(username)) {

⌨️ 快捷键说明

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