ネットワーク燃料争奪ゲーム
while (true) {// 無限ループ try { Socket cs = serverSocket.accept(); addConnection(cs);// コネクションを登録します // クライアント処理スレッドを作成します Thread ct = new Thread(new clientProc(cs)); ct.start(); }catch (IOException e){ System.err.println("client socket or accept error."); } }
public static void loginUser(String name){ if (userTable == null){// 登録用テーブルがなければ作成します userTable = new Hashtable(); } if (random == null){// 乱数の準備をします random = new Random(); } // 船の初期位置を乱数で決定します int ix = Math.abs(random.nextInt()) % 256; int iy = Math.abs(random.nextInt()) % 256; // クライアントの名前や船の位置をハッシュ表userTablweに登録します userTable.put(name, new Ship(ix, iy)); // サーバ側の画面にもクライアントの名前を表示します System.out.println("login:" + name); System.out.flush(); }
public void run(){ try { //LOGOUTコマンド受信まで繰り返します while (true) { // クライアントからの入力を読み取ります String line = in.readLine(); // nameが空の場合にはLOGINコマンドのみを受け付けます if (name == null){ StringTokenizer st = new StringTokenizer(line); String cmd = st.nextToken(); if ("login".equalsIgnoreCase(cmd)){ name = st.nextToken(); UmiServer.loginUser(name); }else{ // LOGINコマンド以外は,すべて無視します } }else{ // nameが空でない場合はログイン済みですから,コマンドを受け付けます StringTokenizer st = new StringTokenizer(line); String cmd = st.nextToken();// コマンドの取り出し // コマンドを調べ,対応する処理を行います if ("STAT".equalsIgnoreCase(cmd)){ UmiServer.statInfo(out); } else if ("UP".equalsIgnoreCase(cmd)){ UmiServer.up(name); .... } else if ("LOGOUT".equalsIgnoreCase(cmd)){ UmiServer.logoutUser(name); break; } } } // 登録情報を削除し,接続を切断します. UmiServer.deleteConnection(s); s.close(); }catch (IOException e){ try { s.close(); }catch (IOException e2){} } } }
public void repaint(){ // サーバにstatコマンドを送付し,盤面の様子などの情報を得ます if( !dlg.OKflag) return; out.println("stat"); out.flush(); //System.out.println("repaint"); try { String line = in.readLine();// サーバからの入力の読み込み Graphics g = getGraphics();// Canvas cに海の様子を描きます // 海の描画(単なる青い四角形です) g.setColor(Color.blue); g.fillRect(0, 0, 256, 256); //ship_infoから始まる船の情報の先頭行を探します while (!"ship_info".equalsIgnoreCase(line)) line = in.readLine(); // 船の情報ship_infoの表示 // ship_infoはピリオドのみの行で終了です line = in.readLine(); while (!".".equals(line)){ StringTokenizer st = new StringTokenizer(line); // 名前を読み取ります String obj_name = st.nextToken().trim(); // 自分の船は赤(red)で表示し,他人の船は緑(green)で表示します if (obj_name.equals(name))//自分の船 g.setColor(Color.red); else // 他人の船 g.setColor(Color.green); // 船の位置座標を読み取ります int x = Integer.parseInt(st.nextToken()) ; int y = Integer.parseInt(st.nextToken()) ; // 船を表示します g.fillOval(x - 10, 256 - y - 10, 20, 20); // 得点を船の右下に表示します g.drawString(st.nextToken(),x+10,256-y+10) ; // 名前を船の右上に表示します g.drawString(obj_name,x+10,256-y-10) ; // 次の一行を読み取ります line = in.readLine(); } // energy_infoから始まる,燃料タンクの情報を待ち受けます .... }catch (Exception e){ e.printStackTrace(); System.exit(1); }