?? gobangroom.java
字號:
package com.j2medev.chapter5;
import java.util.ArrayList;
import java.util.List;
public class GoBangRoom implements Room {
private List players = new ArrayList();
public GoBangRoom() {
}
//最多容納兩個用戶
public int maxPlayer() {
return 2;
}
public boolean canJoin() {
return players.size()<2;
}
//添加一個用戶,如果達到兩個用戶則開始游戲
public synchronized void addPlayer(Session s) {
players.add(s);
s.setSessionId(players.size());
s.setRoom(this);
s.start();
if(players.size()== maxPlayer()){
//開始游戲,最先加入的用戶先走
startGame(1);
}
}
private void clean(){
for(int i = 0;i<players.size();i++){
try{
((Session)players.get(i)).join();
}catch(InterruptedException ex){
ex.printStackTrace();
}
}
for(int i = 0;i<players.size();i++){
((Session)players.get(i)).closeSession();
}
//等session結束后,清除房間
players.clear();
System.out.println("the room is clear");
}
public void startGame(int id){
//休眠1s
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
//讓客戶端起動
for(int i = 0;i<players.size();i++){
((Session)players.get(i)).startGame(id);
}
}
//代理客戶端發送過來的數據
public synchronized void delegate(int data) {
int type = (data&0xFF000000)>>24;
int id = (data&0x00FF0000)>>16;
for(int i=0;i<players.size();i++){
Session s = (Session)players.get(i);
if(type == Protocol.QUIT || type == Protocol.WIN){
try {
//發送給所有用戶
Thread.sleep(500);
s.send(data);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}else if(type == Protocol.STEP){
if(s.getSessionId() != id){
//對手走了一步,發給另一個用戶
s.send(data);
}
}
}
//準備清理房間了
if(type == Protocol.QUIT || type == Protocol.WIN){
new Thread(){
public void run(){
clean();
}
}.start();
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -