📄 snakeserver.java
字号:
package logic;
import java.net.*;
import java.util.*;
import java.io.*;
import ui.*;
public class SnakeServer implements Runnable {
private ServerSocket ss;
private Socket s;
private DataOutputStream dos;
private Vector playerList = new Vector(); //该向量用来保存每个玩家的DataOutputStream对象
private static final int port = 5000;
private int count = 0;
private Hashtable players = new Hashtable(); //这个Hash表保存每个玩家的游戏检测者(线程对象)
private Food food; // 表示食物
private WorldMap worldMap; // 表示地图
private String mapName = "The Heart of God.map"; // 默认地图——上帝之心
private CommandSender commandSender = new CommandSender(this); //同时运行一个命令发送者(线程)
private StartUI startUI; //the starting inteface
private boolean hasStarted = false; //judge whether host has pressed start button
public SnakeServer(String mapName) {
try {
//initialize UI
startUI = new StartUI();
ss = new ServerSocket(port);
// 新的地图
if (mapName!=null && !mapName.equals("")) this.mapName = mapName;
// 初始化地图
worldMap = new WorldMap(this.mapName);
// 根据地图中的食物坐标初始化食物
food = new Food(worldMap.getXFood(), worldMap.getYFood(), worldMap.getMapWidth(), worldMap.getMapHeight());
new Thread(this).start();
// new Snake("127.0.0.1", 5000);
new Thread(new ServerSnake()).start();
while (hasStarted != true) { //wait until the host pressed
hasStarted = startUI.isHasStarted();
Thread.sleep(10);
}
//game start!
if (hasStarted == true) {
sendToAll("true");
startUI.dispose();
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.interrupted()) {
try {
s = ss.accept();
System.out.println(s.toString() + "Connected!");
//whenever a player connected, update startUI
//then notify all other waiting players
startUI.setName(s.getLocalAddress().toString().substring(1));
dos = new DataOutputStream(s.getOutputStream());
// 对玩家编号
dos.write(count);
// 发送地图名
dos.writeUTF(mapName);
// 将玩家的DataOutputStream对象添加
playerList.add(dos);
// 运行接收玩家按键消息的线程
new Thread(new ServerThread(this, s, count));
// 生成玩家游戏检测者,并放入Hash表
players.put(new Integer(count),new Player(count, commandSender, food, worldMap));
count++;
//send player information to all other players
sendToAll(startUI.getAllName());
}catch (IOException ie){
ie.printStackTrace();
}
}
}
// 处理按键消息
public void handleKeyPressed(int id, int d) {
// 得到对应编号的玩家检测者
Player player = (Player)players.get(new Integer(id));
// 如果不是与蛇当前方向相反的按键,则是合法按键,则修改蛇的方向
if (player.getDirection()+d!=5) player.setDirection(d);
}
// 将命令发送给每个玩家
public void sendToAll(String command) throws IOException{
int i;
for (i=0;i<count;i++) {
dos = (DataOutputStream)playerList.elementAt(i);
dos.writeUTF(command);
}
}
public static void main(String[] args) {
new SnakeServer("The Heart of God.map");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -