我目前正在研究服务器插槽,并从事游戏项目。我的游戏是基于回合的2玩家游戏,它将产生5个随机数字和一个答案。玩家需要找到与答案匹配的5位数字的数学运算符(+,-,*,/)。将随机选择第一个玩家,当两个玩家都完成了回合后,我们将比较剩余时间。下一场比赛剩下更多时间的玩家将成为第一位玩家,并且游戏将永远这样循环。因此,我编写了3个用于处理游戏的类
对不起,代码错误,我是代码的新手,我不知道该在哪里剪掉代码部分来问这个问题。
对于客户端,我基本上是通过发送按钮发送回数据的。
这是Server类,其中包括对多个客户端的客户端处理
public class serverSocket implements Runnable{
final static int port = 22222;
ServerSocket server;
Socket socket;
boolean play = true;
static int connected = 0;
final static int maxConnected =2;
static int nowplaying;
int firstplayer = (int) (Math.random()*maxConnected);
static List<ClientHandler> connects;
static ArrayList<playerData> players;
static int time1, time2;
public static void main(String[]args) throws IOException {
new serverSocket(port).run();
}
//start the server.
public serverSocket(int port) {
GUI();
try {
server = new ServerSocket(port);
System.out.println("New server initialized!");
connects = Collections.synchronizedList(new ArrayList<ClientHandler>());
players = new ArrayList<playerData>();
} catch (IOException e) {
e.printStackTrace();
}
//start thread for each client.
while(connected < maxConnected){
try {
socket = server.accept();
System.out.println("Client " + connected + " is connected.");
ClientHandler connect = new ClientHandler(socket);
new Thread(connect).start();
connects.add(connect);
connected++;
} catch (IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// first playerData created
for(int i = 0; i< maxConnected;i++) {
try {
players.add((playerData) connects.get(i).clientInput.readObject());
labelClient.setText(labelClient.getText() + players.get(i).getName() + ", ");
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//write back first data to all user.
writeToALl(players);
flushALl();
players.get(firstplayer).setPastWin(true);
}
public void run(){
for(int i = 0;i< maxConnected;i++) {
if(players.get(i).getPastWin() == true) {
try {
connects.get(i).serverOutput.writeObject(play);
flushALl();
nowplaying = i;
break;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
playerData a = null;
try {
a = (playerData) connects.get(nowplaying).clientInput.readObject();
} catch (ClassNotFoundException | IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(a.getCorrect() == true) {
time1 = a.getTime();
}
try {
connects.get((nowplaying+1)%maxConnected).serverOutput.writeObject(play);
flushALl();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
playerData b = null;
try {
b = (playerData) connects.get((nowplaying+1)%maxConnected).clientInput.readObject();
} catch (ClassNotFoundException | IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(b.getCorrect() == true) {
time2 = b.getTime();
}
if(a.getCorrect() == false || time2 > time1) {
players.get((nowplaying+1)%maxConnected).score++;
players.get((nowplaying+1)%maxConnected).setPastWin(true);
players.get((nowplaying+1)%maxConnected).setCorrect(false);
}
else if(b.getCorrect() == false || time1>time2) {
players.get(nowplaying).score++;
players.get(nowplaying).setPastWin(true);
players.get(nowplaying).setCorrect(false);
}
writeToALl(players);
}
class ClientHandler implements Runnable{
Socket socket;
public ClientHandler(Socket socket) {
this.socket = socket;
}
ObjectInputStream clientInput;
ObjectOutputStream serverOutput;
public void run() {
try {
clientInput = new ObjectInputStream(socket.getInputStream());
serverOutput = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void writeToALl(Object output) {
for(int i = 0; i < maxConnected; i++) {
try {
connects.get(i).serverOutput.writeObject(output);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void flushALl() {
for(int i = 0; i < maxConnected; i++) {
try {
connects.get(i).serverOutput.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这是客户端
public class clientSocket implements Runnable{
static final int port = 22222;
static Socket socket;
static ObjectInputStream serverInput;
static ObjectOutputStream clientOutput;
static ArrayList<playerData> players;
static playerData playerData;
static boolean nowplay;
static int inputAnswer;
static Timer timer;
static String name;
static int time = 60;
static int score = 0;
static boolean pastplay = false;
static boolean correct = false;
static Random myRandom = new Random();
static int num1,num2,num3,num4,num5,givenAnswer;
static String operator1,operator2,operator3,operator4,result;
public static void main(String[]args){
new clientSocket("localhost", port).run();
}
@SuppressWarnings("unchecked")
public void run(){
try {
nowplay = (boolean) serverInput.readObject();
if(nowplay == true) {
JOptionPane.showMessageDialog(frame,name + "'s turn");
timer.start();
}
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
players = (ArrayList<playerData>) serverInput.readObject();
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
labelScorePlayer1.setText(players.get(0).name + " " + players.get(0).score);
labelScorePlayer2.setText(players.get(1).name + " " + players.get(1).score);
}
//establish connection with server.
@SuppressWarnings("unchecked")
public clientSocket(String hostname, int port) {
try {
GUI();
socket = new Socket(hostname, port);
clientOutput = new ObjectOutputStream(socket.getOutputStream());
serverInput = new ObjectInputStream(socket.getInputStream());
players = new ArrayList<playerData>();
nowplay = false;
askName();
playerData = new playerData(name,score,time, correct, pastplay);
clientOutput.writeObject(playerData);
clientOutput.flush();
} catch (IOException | ScriptException e) {
e.printStackTrace();
}
try {
players = (ArrayList<playerData>) serverInput.readObject();
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(players.size() > 1) {
labelScorePlayer1.setText(players.get(0).name + " " + players.get(0).score);
labelScorePlayer2.setText(players.get(1).name + " " + players.get(1).score);
}
}
static JFrame frame;
static JPanel panelNorth;
static JPanel panelCenter;
static JPanel panel;
static JPanel panel1;
static JPanel panel2;
static JPanel panelSouth;
static JLabel labelName;
static JLabel labelTimer;
static JLabel labelScorePlayer1;
static JLabel labelScorePlayer2;
static JLabel labelEqual;
static JLabel labelGivenAnswer;
static JLabel labelAnswer;
static JLabel labelInputAnswer;
static JButton buttonNum1;
static JButton buttonNum2;
static JButton buttonNum3;
static JButton buttonNum4;
static JButton buttonNum5;
static JButton buttonSend;
static JButton buttonPlus;
static JButton buttonMinus;
static JButton buttonMultiply;
static JButton buttonDivide;
public static void GUI() throws ScriptException {
//random integer 0-9.
num1 = (int) (Math.random()*9+1);
num2 = (int) (Math.random()*9+1);
num3 = (int) (Math.random()*9+1);
num4 = (int) (Math.random()*9+1);
num5 = (int) (Math.random()*9+1);
//random math operator + - * /.
operator1 = pickRandom();
operator2 = pickRandom();
operator3 = pickRandom();
operator4 = pickRandom();
//Given answer.
result = num1 + operator1 + num2 + operator2 + num3 + operator3 + num4 + operator4 + num5;
givenAnswer = operation(result);
//GUI
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//panelNorth
panelNorth = new JPanel();
panelNorth.setLayout(new BorderLayout(0, 0));
//game name label
labelName = new JLabel("IQ180");
labelName.setFont(new Font("Lucida Grande", Font.PLAIN, 20));
labelName.setHorizontalAlignment(SwingConstants.CENTER);
//timer
labelTimer = new JLabel("60");
timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
playerData.time--;
time--;
labelTimer.setText(Integer.toString(time));
if (time == 0) {
final Timer timer = (Timer) e.getSource();
timer.stop();
time = 60;
}
}
});
labelTimer.setHorizontalAlignment(SwingConstants.CENTER);
//adding label to panel
panelNorth.add(labelName, BorderLayout.CENTER);
panelNorth.add(labelTimer, BorderLayout.SOUTH);
//adding panel to frame
frame.getContentPane().add(BorderLayout.NORTH, panelNorth);
//panelCenter
panelCenter = new JPanel();
//Score player 1
labelScorePlayer1 = new JLabel("");
labelScorePlayer1.setBounds(0, 0, 40, 49);
labelScorePlayer1.setHorizontalAlignment(SwingConstants.CENTER);
//Score player2
labelScorePlayer2 = new JLabel("");
labelScorePlayer2.setBounds(387, 0, 63, 49);
labelScorePlayer2.setHorizontalAlignment(SwingConstants.CENTER);
//adding label to panel
panelCenter.setLayout(null);
panelCenter.add(labelScorePlayer1);
panelCenter.add(labelScorePlayer2);
//adding panel to frame
frame.getContentPane().add(BorderLayout.CENTER, panelCenter);
//center part of panelCenter
panel = new JPanel();
panel.setBounds(40, 0, 347, 198);
panelCenter.add(panel);
panel.setLayout(null);
//panel1 inside panel
panel1 = new JPanel();
panel1.setBounds(0, 0, 347, 105);
panel.add(panel1);
panel1.setLayout(null);
//button num1
buttonNum1 = new JButton(Integer.toString(num1));
buttonNum1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
labelInputAnswer.setText(labelInputAnswer.getText()+Integer.toString(num1));
buttonNum1.setEnabled(false);
}
});
buttonNum1.setBounds(6, 38, 40, 40);
panel1.add(buttonNum1);
//button num2
buttonNum2 = new JButton(Integer.toString(num2));
buttonNum2.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
labelInputAnswer.setText(labelInputAnswer.getText()+Integer.toString(num2));
buttonNum2.setEnabled(false);
}
});
buttonNum2.setBounds(65, 38, 40, 40);
panel1.add(buttonNum2);
//button num3
buttonNum3 = new JButton(Integer.toString(num3));
buttonNum3.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
labelInputAnswer.setText(labelInputAnswer.getText()+Integer.toString(num3));
buttonNum3.setEnabled(false);
}
});
buttonNum3.setBounds(117, 38, 40, 40);
panel1.add(buttonNum3);
//button num4
buttonNum4 = new JButton(Integer.toString(num4));
buttonNum4.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
labelInputAnswer.setText(labelInputAnswer.getText()+Integer.toString(num4));
buttonNum4.setEnabled(false);
}
});
buttonNum4.setBounds(169, 38, 40, 40);
panel1.add(buttonNum4);
//button num5
buttonNum5 = new JButton(Integer.toString(num5));
buttonNum5.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
labelInputAnswer.setText(labelInputAnswer.getText()+Integer.toString(num5));
buttonNum5.setEnabled(false);
}
});
buttonNum5.setBounds(221, 38, 40, 40);
panel1.add(buttonNum5);
//equal sign
labelEqual = new JLabel("=");
labelEqual.setBounds(273, 37, 10, 40);
panel1.add(labelEqual);
//givenAnswerLabel
labelGivenAnswer = new JLabel(Integer.toString(givenAnswer));
labelGivenAnswer.setBounds(301, 37, 40, 40);
panel1.add(labelGivenAnswer);
//panel2 inside panel
panel2 = new JPanel();
panel2.setBounds(0, 105, 347, 93);
panel.add(panel2);
panel2.setLayout(null);
//plus button
buttonPlus = new JButton("+");
buttonPlus.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
labelInputAnswer.setText(labelInputAnswer.getText()+"+");
}
});
buttonPlus.setBounds(44, 27, 40, 40);
panel2.add(buttonPlus);
//minus button
buttonMinus = new JButton("-");
buttonMinus.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
labelInputAnswer.setText(labelInputAnswer.getText()+"-");
}
});
buttonMinus.setBounds(120, 27, 40, 40);
panel2.add(buttonMinus);
//multiply button
buttonMultiply = new JButton("*");
buttonMultiply.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
labelInputAnswer.setText(labelInputAnswer.getText()+"*");
}
});
buttonMultiply.setBounds(198, 27, 40, 40);
panel2.add(buttonMultiply);
//divide button
buttonDivide = new JButton("/");
buttonDivide.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
labelInputAnswer.setText(labelInputAnswer.getText()+"/");
}
});
buttonDivide.setBounds(272, 27, 40, 40);
panel2.add(buttonDivide);
//panelSouth
panelSouth = new JPanel(); // the panel is not visible in output
labelAnswer = new JLabel("Answer");
labelInputAnswer = new JLabel("");
//send button
buttonSend = new JButton("Send");
buttonSend.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
String inputAnswer = labelInputAnswer.getText();
int inputIntAnswer = 0;
try {
inputIntAnswer = operation(inputAnswer);
} catch (ScriptException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(Math.abs(inputIntAnswer-givenAnswer) == 0 && playerData.time > 0) {
JOptionPane.showMessageDialog(frame,"Correct!");
labelInputAnswer.setText("");
playerData.setCorrect(true);
}else {
JOptionPane.showMessageDialog(frame,"Wrong!");
labelInputAnswer.setText("");
}
timer.stop();
playerData.setPastWin(false);
nowplay = false;
try {
clientOutput.writeObject(playerData);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
playerData.time = 60;
labelTimer.setText(Integer.toString(playerData.time));
buttonNum1.setEnabled(true);
buttonNum2.setEnabled(true);
buttonNum3.setEnabled(true);
buttonNum4.setEnabled(true);
buttonNum5.setEnabled(true);
}
});
panelSouth.add(labelAnswer);
panelSouth.add(labelInputAnswer);
panelSouth.add(buttonSend);
frame.getContentPane().add(BorderLayout.SOUTH, panelSouth);
frame.setVisible(true);
}
//ask name
public static void askName() {
name = JOptionPane.showInputDialog(frame,"What is your name?");
JOptionPane.showMessageDialog(frame,"Welcome, " + name);
}
//Get random operator.
public static String getRandom(String[] arr) {
int rdm = myRandom.nextInt(arr.length);
return arr[rdm];
}
public static String pickRandom() {
String[] operator = {"+"/*, "-", "*", "/"*/};
String r = getRandom(operator);
return r;
}
public static int operation(String input) throws ScriptException {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
return new BigDecimal(engine.eval(input).toString()).intValue();
}
}
我正在来回发送playerData类以进行套接字通信。
public class playerData implements java.io.Serializable{
private static final long serialVersionUID = 1L;
String name;
int score;
int time;
boolean pastwin;
boolean correct;
public playerData() {
name = null;
score = 0;
time = 60;
pastwin = false;
correct = false;
}
public playerData(String name, int score, int time, boolean correct, boolean pastwin) {
this.name = name;
this.score = score;
this.time = time;
this.pastwin = pastwin;
this.correct = correct;
}
public String toString() {
return "Name : " + name + ", score : " + score + ", time : " + time;
}
public int getTime(){
return time;
}
public int getScore() {
return score;
}
public String getName() {
return name;
}
public boolean getCorrect() {
return correct;
}
public boolean getPastWin() {
return pastwin;
}
public void setTime(int time) {
this.time = time;
}
public void setScore(int score) {
this.score = score;
}
public void setName(String name) {
this.name = name;
}
public void setPastWin(boolean pastwin) {
this.pastwin = pastwin;
}
public void setCorrect(boolean correct) {
this.correct = correct;
}
问题是我的运行循环在第一轮之后没有继续,我也不知道为什么会这样。
答案 0 :(得分:0)
尝试在run
方法中添加while
。如果您有任何条件破坏while
,则可以将其添加到while
括号中,或在break
范围内(或同时使用)使用while
。
public void run(){
while(true)
{
try {
nowplay = (boolean) serverInput.readObject();
if(nowplay == true) {
JOptionPane.showMessageDialog(frame,name + "'s turn");
timer.start();
}
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
players = (ArrayList<playerData>) serverInput.readObject();
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
labelScorePlayer1.setText(players.get(0).name + " " + players.get(0).score);
labelScorePlayer2.setText(players.get(1).name + " " + players.get(1).score);
}
}