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

📄 garageclient.java

📁 一个非常好的赛车游戏代码
💻 JAVA
字号:
import java.util.*;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;

public class GarageClient implements CommandListener
{
  public  Form loginform;
  public  Form mainform;
  public  Form detailform;
  public  Form sellform;
  public  Form sellform2;
  public  Form itemsoldform;
  
  // commands 
  static final Command LOGIN = new Command("Log In",Command.SCREEN, 1);
  static final Command EXIT = new Command("Exit",Command.EXIT, 2);
  
  static final Command BUY = new Command("Buy",Command.SCREEN, 1);
  static final Command SELL = new Command("Sell",Command.SCREEN, 1);
  static final Command LOGOUT = new Command("Log Out",Command.SCREEN, 2);
  static final Command REFRESH = new Command("Refresh",Command.SCREEN, 2);
  
  static final Command BUYIT = new Command("Buy It",Command.SCREEN, 1);
  static final Command SELLIT = new Command("Sell It",Command.SCREEN, 1);
  static final Command BACK = new Command("Back",Command.BACK, 2);
  
  private  TextField usernamefield;
  private  TextField pricefield;
  private  ChoiceGroup itemgroup;
  private  String username;
  private  Vector itemvector;
  private  Vector solditemvector;
  private  int price;
  private  String usershere;
  
  Timer timer;
  
  String url = "http://localhost/garage";
  
  private Game game;

  
  GarageClient(Game g)
  {
  	  game = g;	
     loginform = new Form("The Garage");
     loginform.append("Log In Now");
     usernamefield = new TextField("Username:", "", 10, TextField.ANY);
     loginform.append(usernamefield);
     loginform.addCommand(LOGIN);
     loginform.addCommand(EXIT);
     loginform.setCommandListener(this);
  }

  public void Login() 
  {
    game.getDisplay().setCurrent(loginform);
  }

  public void commandAction(Command c, Displayable s) 
  {
    if (s instanceof Form) 
    {
        Form obj = (Form) s;
        if (obj == loginform) 
        {
            if (c == EXIT) 
            {
            	 // Nothing is up for sale anymore
            	 for (int i=0; i < game.cs.getWeapons().length; i++)
            	 	game.cs.getWeapons()[i].setUpForSale(false);
    	         game.getDisplay().setCurrent(game.form);
            }
            else if (c == LOGIN) 
            {
                username = usernamefield.getString();
                Login l = new Login();
            }
        }
        else if (obj == mainform) 
        {
            if (c == BUY) 
	        buydetail(itemgroup.getSelectedIndex());
            else if (c == SELL) 
                sell();
            else if (c == LOGOUT) 
            {
                Logout lo = new Logout();
            }
            else if (c == REFRESH)
            {
		Login l = new Login();
            }
        }
        else if (obj == sellform || obj == detailform || obj == itemsoldform) 
        {
            if (c == BACK)
                game.getDisplay().setCurrent(mainform);
            else if (c == BUYIT)
            {
                BuyIt bi = new BuyIt(itemgroup.getSelectedIndex());
            }
            else if (c == SELLIT)
		pickprice();
        }
        else if (obj == sellform2)
        {
            if (c == BACK)
                game.getDisplay().setCurrent(sellform);
            else if (c == SELLIT)
            {
                String price = pricefield.getString();
                int i = itemgroup.getSelectedIndex();

		        // Be sure item wasn't already put up for sale
                if (game.cs.getWeapons()[i].getUpForSale())
					return;

                // Marshal data for item in a String
                String theitem = game.cs.getWeapons()[i].getName()+"!"+game.cs.getWeapons()[i].getDescription()+"!"+price;
 
                // Remove the item from the local list of my items
                game.cs.getWeapons()[i].setUpForSale(true);

                SellIt si = new SellIt(theitem);
            }
        }
    }
  }

  void CreateMainform()
  {
    mainform = new Form("Items For Sale");
    mainform.addCommand(BUY);
    mainform.addCommand(SELL);
    mainform.addCommand(LOGOUT);
    mainform.addCommand(REFRESH);
    mainform.setCommandListener(this);    

    mainform.append("Also Here: "+usershere+"\n");
    mainform.append("My Balance: $"+game.cs.getCash()+"\n");

    if (itemvector.size() == 0)
    {
	  mainform.append("No Items For Sale");
	  mainform.append("Come Back Later");

          // Remove the buy button 
          mainform.removeCommand(BUY);
    }
    else
    {
        String items[] = new String[itemvector.size()];        
        // Now parse out the item name
        for (int i=0; i < itemvector.size(); i++)
            items[i] = ItemName((String)itemvector.elementAt(i));

        itemgroup = new ChoiceGroup("Exclusive",ChoiceGroup.EXCLUSIVE,items,null);
    
        mainform.append(itemgroup);
    }
  }

  void CreateItemsoldform()
  {
    itemsoldform = new Form("Item Sold!");
    itemsoldform.addCommand(BACK);
    itemsoldform.setCommandListener(this);    
  }

  
  class Login implements ServerCallback
  {
  
  Login() 
  {
      ConnectServer("login",null,this);
  }

  public void serverResponse(String response)
  { 
    if (CheckForError(response)) return;

    // Parse out the user list and items for sale
    
    int uindex = response.indexOf("users"); 
    int findex = response.indexOf("forsale"); 
    if (uindex == -1 || findex == -1)
    {
        ShowError("Bad User List or For Sale List Returned");
        return;
    }
    usershere = response.substring(6,findex-1);
    String forsale = response.substring(findex+8);

    // Now parse through the for sale list
    itemvector = new Vector();
    CreateItemVector(forsale,itemvector);
    boolean canbuy = true;

    CreateMainform();

    game.getDisplay().setCurrent(mainform);
  }
  }
  
  private void buydetail(int at)
  {
    detailform = new Form("Ready To Buy");
    detailform.addCommand(BUYIT);
    detailform.addCommand(BACK);
    detailform.setCommandListener(this);

    detailform.append(ItemName((String)itemvector.elementAt(at))+"\n");
    
    // Show the description
    detailform.append(ItemDescription((String)itemvector.elementAt(at))+"\n");
    
    // Show the price
    String iprice = ItemPrice((String)itemvector.elementAt(at));
    detailform.append("For $"+iprice+"\n");
    try {
    price = Integer.parseInt(iprice);
    }
    catch (NumberFormatException nfe) 
    { 
        price = 0;    
    }

    // Do we have enough money?
    if (price > game.cs.getCash())
    {
 	detailform.append("You Can't Afford This!");
	detailform.removeCommand(BUYIT);
    }
    game.getDisplay().setCurrent(detailform);
  }

  class BuyIt implements ServerCallback  
  {
  int index;

  BuyIt(int itemindex)
  {
    index = itemindex;
    ConnectServer("buy",itemgroup.getString(itemindex),this);
  }

  public void serverResponse(String response)
  {
    if (CheckForError(response)) return;
    if (response.equals(""))
    {
	// Charge your account
        game.cs.setCash(game.cs.getCash()-price);

        // TODO: Add item to your personal database
 
        // Remove item from local list
	itemvector.removeElementAt(index);

	CreateMainform();
        game.getDisplay().setCurrent(mainform);
    }
    else
        ShowError(response);
  }
  }
  
  private void sell()
  {
    sellform = new Form("Your Items");
    sellform.addCommand(SELLIT);
    sellform.addCommand(BACK);
    sellform.setCommandListener(this);
    
    String myitemname[] = new String[game.cs.getWeapons().length];
    for (int i=0; i < game.cs.getWeapons().length; i++)
    	myitemname[i] = game.cs.getWeapons()[i].getName();

    itemgroup = new ChoiceGroup("Exclusive",ChoiceGroup.EXCLUSIVE,myitemname,null);
    sellform.append(itemgroup);
    game.getDisplay().setCurrent(sellform);
  }

  private void pickprice()
  {
    sellform2 = new Form("Choose Sale Price");
    sellform2.addCommand(SELLIT);
    sellform2.addCommand(BACK);
    sellform2.setCommandListener(this);

    sellform2.append(itemgroup.getString(itemgroup.getSelectedIndex())+"\n");

    pricefield = new TextField("Price:", "", 3, TextField.NUMERIC);
    sellform2.append(pricefield);

    game.getDisplay().setCurrent(sellform2);
  }

  class SellIt implements ServerCallback  
  {

  SellIt(String item)
  {
    ConnectServer("sell", item, this);
  }

  public void serverResponse(String response)  
  {
    if (CheckForError(response)) return;

    // Begin polling the server for any updates
    if (timer == null)
    {
        timer = new Timer();
	CheckInTimer ci = new CheckInTimer();
	timer.schedule(ci,(long)10000,10000);
    }
    game.getDisplay().setCurrent(mainform);
  }
  }

  class Logout implements ServerCallback  
  {

  Logout() 
  {
    if (timer != null)
	timer.cancel();
    ConnectServer("logout",null,this);
  }

  public void serverResponse(String response)  
  {
    if (CheckForError(response)) return;
    game.getDisplay().setCurrent(loginform);
  }
  }
  
  class CheckIn implements ServerCallback  
  {

  CheckIn() 
  {
    ConnectServer("checkin",null,this);
  }

  public void serverResponse(String response)  
  {
    if (CheckForError(response)) return;
    int rindex = response.indexOf("sold"); 
    if (rindex != -1)
    {
        String items = response.substring(rindex+5);
        if (!items.equals(""))
        {
	   CreateItemsoldform();
 	   solditemvector = new Vector();
           CreateItemVector(items,solditemvector);

           // Now parse out the item name
           for (int i=0; i < solditemvector.size(); i++)
           {
              String itemname = ItemName((String)solditemvector.elementAt(i));
              String itemprice = ItemPrice((String)solditemvector.elementAt(i));
              int price = 0;
              try {
                price = Integer.parseInt(itemprice);
              }
              catch (NumberFormatException nfe) { }

              // TODO: Remove the item from the database
	      itemsoldform.append(itemname+" sold for $"+itemprice);

              // Add money to your balance
              game.cs.setCash(game.cs.getCash()+price);
	      CreateMainform();
	      game.getDisplay().setCurrent(itemsoldform);
           }
        }
    }
  }
  }

  void CreateItemVector(String items,Vector iv)
  {
      // Parse through the list of items
      int start = 0;
      int end = 0;
      String item = "";
      end = items.indexOf(',');
    
      while (end != -1)
      {
	   item = items.substring(start,end);
	   iv.addElement(item);
	   start = end+1;
	   end = items.indexOf(',',start);
      }
      item = items.substring(start);
      if (!item.equals(""))
	iv.addElement(item);
  }
  
  private boolean CheckForError(String response)
  {
     System.out.println("RESP:"+response);
     int ecode = response.indexOf("error");
     if (ecode != -1)
     {
	String therror = response.substring(ecode+6);
	ShowError(therror);
	return true;
     }
     return false;
  }
  
  private void ShowError(String err)
  {
    Alert errorAlert = new Alert("Alert",err,null, AlertType.ERROR);
    errorAlert.setTimeout(Alert.FOREVER);
    game.getDisplay().setCurrent(errorAlert);
  }
  
  private String ItemName(String item)
  {
    int end = item.indexOf('!');
    if (end == -1)
    {
        ShowError("Bad Item Format");
        return "";
    }
    return item.substring(0,end);
    // Horse!mean!669
  }
  
  private String ItemDescription(String item)
  {
    int start = item.indexOf('!');
    int end = item.indexOf('!',start+1);
    if (end == -1 || start == -1)
    {
        ShowError("Bad Item Format");
        return "";
    }
    return item.substring(start+1,end);
  }
  
  private String ItemPrice(String item)
  {
    int start = item.indexOf('!');
    int end = item.indexOf('!',start+1);
    if (end == -1 || start == -1)
    {
        ShowError("Bad Item Format");
        return "";
    }
    return item.substring(end+1);
  }

  void ConnectServer(String action,String item,ServerCallback callback)
  {
      ConnectNow cn = new ConnectNow(action,item,callback);	
      cn.start();
  }

  public interface ServerCallback 
  {
      public void serverResponse( String response);
  }

  class ConnectNow implements Runnable
  {
    String action;
    String item;
    ServerCallback callback;

    ConnectNow( String a,String i,ServerCallback c)
    {
      action = a;
      item = i;
      callback = c;
    }

    public void run()
    {
      HttpConnection c = null;
      InputStream is = null;
      DataOutputStream os = null;
      StringBuffer b = new StringBuffer();

      if (item == null)
          item = "";

      try 
      {
        c = (HttpConnection)Connector.open(url);
        c.setRequestMethod(HttpConnection.POST);
        c.setRequestProperty("User-Agent","Profile/MIDP-1.0 Configuration/CLDC-1.0");
        c.setRequestProperty("Content-Language", "en-US");

        os = new DataOutputStream(c.openOutputStream());
        os.writeUTF(username);
        os.writeUTF(action);
        os.writeUTF(item);
	System.out.println(username+","+action+","+item);

        int rc = c.getResponseCode();
        if( rc == HttpConnection.HTTP_OK )
        {      
          is = c.openDataInputStream();
          int ch;
          while ((ch = is.read()) != -1) 
              b.append((char) ch);
        }
        else
        {
  	   System.out.println("Response Code: "+rc);
           ShowError("Bad Server Response!");
        }
      } 
      catch (Exception e)
      {
          ShowError("Problem Connecting to Network");
      }
      finally 
      {
        try {
        if (is != null) 
          is.close();
        if (c != null) 
          c.close();
        if (os != null)
          os.close();
        }
        catch (Exception e) 
        { 
          ShowError("Problem Closing Network Connection");
        }
      }
      if (b != null)
          callback.serverResponse(b.toString());
      else
          callback.serverResponse(null);
    } 

    void start()
    {
       Thread t = new Thread( this );
       try 
       {
          t.start();
       }
       catch( Exception e )
       {
           ShowError(e.toString());
       }
    }
  }
  
  class CheckInTimer extends TimerTask 
  {
    CheckInTimer() { }
    
    public void run() 
    {
	  try {
  	    CheckIn ci = new CheckIn();
	  } 
	  catch (Exception ex) { }
    }
  }
}

⌨️ 快捷键说明

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