После того, как решите мою проблему, добавьте метку в мой jlabel backgroudn в предыдущем вопросе. У меня возникли новые проблемы, когда я разработал клиентский сервер в Hang Man для двух игроков, чтобы играть в игру.
Во-первых, когда пользователь выбирает режим 2 игрока. Клиент отправит сообщение на сервер "twoPMode"
С TCP-сервера сервер получает это сообщение и помещает его в дескриптор метода, вводимый клиентом.
в этом методе у меня есть глобальная переменная playerId, и у него есть 2 метода getter / stter
подробно:
Когда пользователь отправляет сообщение «twoPMode» на сервер, сервер вызовет этот метод, и в этом методе он получит входные данные от клиента и обработчик, если входной сигнал от клиента равен twoPMode, он установит Playerid = "001", и если другой клиент отправит сообщение twoPMode для сервера, он установит playerid = "002", потому что я просто хочу, чтобы 2 клиента могли подключиться к серверу, чтобы играть в игру, если клиент 3 подключится и отправит twoPMode на сервер, я разрушу соединение клиента 3.
Моя проблема в том, что, когда клиент 1 и клиент 2 отправляют сообщение twoPMode на сервер, он также получает идентификатор 001, сбой, потому что я хочу, чтобы тот, кто первым подключился к серверу, получил playerid 001, а второй получил идентификатор игрока 002, но мой код просто отвечает клиенту 001, хотя к серверу подключено 2 клиента
и мой код - я удаляю некоторый генерирующий код из netbean к начальному компоненту
Серверная сторона:
ввод дескриптора класса от клиента
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package srpserver;
import java.util.Random;
/**
*
* @author J2ME NewBiew
*/
public class gameHandle {
private static final int WAITING = 0;
private static final int onePMode = 1;
private static final int getWord = 2;
private static final int PlayonePmode = 3;
private static final int NUMJOKES = 5;
private String keyword = "";
private static final int mode = 4;
private int state = WAITING;
private int countError = 0;
private String playerid = "000";
public String getPlayerid() {
return playerid;
}
//array word list
String[] words = {"laptop", "network", "device", "game", "mobile",
"word", "november", "december", "signal", "internet","localhost","boot", "socket",
"client", "server", "port", "exception", "java", "dotnet","singleton", "ejb","hibernate",
"computer", "microsoft", "lan"};
//this method get random word from array
public String getWord(){
Random r = new Random();
String randomString = words[r.nextInt(words.length)];
return randomString;
}
public String processInput(String theInput) {
String theOutput = null;
if (state == WAITING) {
theOutput = "Hello Hangman Client";
state = mode;
} else if(state == mode){
if(theInput.equalsIgnoreCase("onePMode")){
theOutput = "onePMode" ;
state = onePMode;
}else if(theInput.equalsIgnoreCase("")){
state = WAITING;
}else if(theInput.equalsIgnoreCase("twoPMode")){
if(playerid.equals("000")){
setPlayerid("001");
theOutput = "001";
playerid = "001";
System.out.println("Thu cai coi 01");
}
else if(playerid.equals("001")){
setPlayerid("002");
theOutput = "002";
playerid = "002";
System.out.println("Thu cai coi 02");
}
}
} else if (state == onePMode) {
if (theInput.equalsIgnoreCase("getWord")) {
keyword = getWord();
theOutput = keyword;
state = PlayonePmode;
}
}else if (state == PlayonePmode) {
if(theInput.equalsIgnoreCase("getWord")){
theOutput = " chuyen sang getword";
state = getWord;
}else if (keyword.contains(theInput)) {
theOutput = "containt";
} else {
if(countError <9){
theOutput = "Khong contain";
countError++;
}else if(countError>=9){
theOutput = "Game Over!";
}
}
} if (state == getWord){
keyword = getWord();
theOutput = keyword;
state = PlayonePmode;
}
System.out.println("Player ID: " + playerid);
return theOutput;
}
public void setPlayerid(String playerid) {
this.playerid = playerid;
}
}
Сервер классов открывает поток, отправляет данные клиенту и получает данные от клиента:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package srpserver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/**
*
* @author J2ME NewBiew
*/
public class TCPServerThread extends Thread{
Socket client = null;
BufferedReader in;
String statusBuffer = new String();
String intputLine, outputLine;
public TCPServerThread(Socket socket){
client = socket;
}
public void run(){
try {
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
client.getInputStream()));
String inputLine, outputLine;
gameHandle g = new gameHandle();
outputLine = g.processInput(null);
out.println(outputLine);
while ((inputLine = in.readLine()) != null) {
outputLine = g.processInput(inputLine);
System.out.println(outputLine);
if(inputLine.equals("getWord")){
System.out.println(inputLine);
}
out.println(outputLine);
if (inputLine.equals("Bye"))
break;
}
out.close();
in.close();
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Клиентская сторона: я использую 2 панели, 1 домашнюю страницу игры и 1 - режим двух игроков
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package srpclient.home;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JPanel;
import srpclient.ConnectionTCP;
import srpclient.about.aboutPanel;
import srpclient.player1.onePlayer;
import srpclient.twoplayers.twoPlayers;
/**
*
* @author J2ME NewBiew
*/
public final class Home extends javax.swing.JPanel {
aboutPanel aboutPanel;
onePlayer onePlayerMode;
String serverAddress;
twoPlayers twoPlayerMode;
ConnectionTCP c;
/**
* Creates new form Home
*/
public Home(String ipAddress) {
initComponents();
//conn = new ConnectionTCP(ipAddress);
this.serverAddress = ipAddress;
initialPanel();
// conn.closeConnection();
}
public void initialPanel(){
aboutPanel = new aboutPanel();
}
public void changeImage(JButton bt, String imgPath){
bt.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/"+imgPath+".jpg")));
}
public void setTooltipforButton(JButton bt, String Tooltip){
bt.setToolTipText(Tooltip);
}
private void player1Hover(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
changeImage(btPlayer1, "player1Hover");
setTooltipforButton(btPlayer1, "Play game with 1 player mode");
}
private void player1MouseExit(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
changeImage(btPlayer1, "player1");
}
private void player2MouseHover(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
changeImage(btPlayer2, "player2Hover");
setTooltipforButton(btPlayer2, "Play game with 2 players mode");
}
private void player2MouseExit(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
changeImage(btPlayer2, "player2");
}
private void ruleHover(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
changeImage(btRule, "ruleHover");
setTooltipforButton(btRule, "Play this game with this rule");
}
private void ruleMouseExit(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
changeImage(btRule, "rule");
}
private void AboutMouseHover(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
changeImage(btAbout, "aboutHover");
setTooltipforButton(btAbout, "About Me!!!!");
}
private void AboutMouseExit(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
changeImage(btAbout, "about");
}
private void enterAboutPanel(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
jDesktopRemoveAndRepaint();
CallPanel(aboutPanel);
}
public void jDesktopRemoveAndRepaint(){
jDesktopPane1.removeAll();
jDesktopPane1.repaint();
jDesktopPane1.revalidate();
}
public void CallPanel(JPanel panel){
panel.setBounds(0, 0, 840, 558);
panel.setSize(840,558);
jDesktopPane1.add(panel);
panel.show();
}
private void enterToPlay1PlayerMode(java.awt.event.MouseEvent evt) {
try {
// TODO add your handling code here:
c = new ConnectionTCP(serverAddress);
onePlayerMode = new onePlayer(serverAddress);
jDesktopRemoveAndRepaint();
CallPanel(onePlayerMode);
c.getOut().println("onePMode");
} catch (Exception ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void btPlayer2ActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
c = new ConnectionTCP(serverAddress);
twoPlayerMode = new twoPlayers(serverAddress);
jDesktopRemoveAndRepaint();
String fromServer = c.getIn().readLine();
c.getOut().println("twoPMode");
twoPlayerMode.setPlayerID(fromServer);
CallPanel(twoPlayerMode);
} catch (Exception ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Variables declaration - do not modify
private javax.swing.JButton btAbout;
private javax.swing.JButton btExit;
private javax.swing.JButton btPlayer1;
private javax.swing.JButton btPlayer2;
private javax.swing.JButton btRule;
private javax.swing.JDesktopPane jDesktopPane1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
// End of variables declaration
}
Панель 2 игрока
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package srpclient.twoplayers;
import srpclient.player1.*;
import java.awt.Color;
import java.awt.Graphics;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JLabel;
import srpclient.ConnectionTCP;
/**
*
* @author Kency
*/
public final class twoPlayers extends javax.swing.JPanel {
/**
* Creates new form onePlayer
*/
ConnectionTCP conn;
int countWrongLetter = 0;
String getWord = "getWord";
String serverAddress = "";
JLabel lblKeyword[];
String keyword = "";
JLabel head = new JLabel("");
String sHead = "", sLeft_eye="", sRight_eye="", sBody="",
sMouth="",sLeft_arm="",sRight_arm="",sLeft_leg="",sRight_leg="";
Graphics g;
String playerID = "";
public String getPlayerID() {
return playerID;
}
public void setPlayerID(String playerID) {
this.playerID = playerID;
}
public twoPlayers(String serverAddress) {
try {
initComponents();
jTextArea1.setEditable(false);
conn = new ConnectionTCP(serverAddress);
this.serverAddress = serverAddress;
conn.getOut().println("twoPMode");
if (conn.getIn().readLine() != null) {
setPlayerID(conn.getIn().readLine());
System.out.println(getPlayerID());
}
if(getPlayerID().equals("002")){
jButton1.setEnabled(false);
btPlay.setEnabled(false);
}
} catch (IOException ex) {
Logger.getLogger(twoPlayers.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void getWordLabels(String keyword) {
int length = keyword.length();
lblKeyword = new JLabel[length];
int widhLebelKeyword = 100;
int heightLabelKeyword = 20;
int gapbetweenLetter = 350/length;
for (int i = 0; i < length; i++) {
lblKeyword[i] = new JLabel("_");
jLabel1.revalidate();
jLabel1.repaint();
lblKeyword[i].setForeground(Color.white);
lblKeyword[i].setBounds((gapbetweenLetter * i + 100), 300, widhLebelKeyword, heightLabelKeyword);
jLabel1.add(lblKeyword[i]);
}
}
enum BodyPart {
Head,
Left_Eye,
Right_Eye,
Mouth,
Body,
Left_Arm,
Right_Arm,
Left_Leg,
Right_Leg
}
void DrawBodyPart(BodyPart bp)
{
Graphics g = this.getGraphics();
g.setColor(Color.white);
if(bp == BodyPart.Head)// draw a head
{
g.drawOval(570, 160, 70, 70);
}else if(bp == BodyPart.Left_Eye){
g.drawLine(580, 180, 590, 185);
g.drawLine(590, 180, 580, 185);
}else if(bp == BodyPart.Right_Eye){
g.drawLine(620, 180, 630, 185);
g.drawLine(630, 180, 620, 185);
}else if(bp ==BodyPart.Mouth){
g.drawArc(575, 200, 60, 50, 45, 90);
}else if(bp == BodyPart.Body){
g.drawLine(605, 230, 605 , 310);
}else if(bp == BodyPart.Left_Arm){
g.drawLine(550, 260, 605, 230 );
}else if(bp == BodyPart.Right_Arm){
g.drawLine(660, 260, 605, 230 );
}else if(bp == BodyPart.Left_Leg){
g.drawLine(550, 350, 605, 310 );
}else if(bp == BodyPart.Right_Leg){
g.drawLine(605, 310, 660, 350 );
}
}
//get Keyword from server
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
conn.getOut().println(getWord);
String inputFromServer = conn.getIn().readLine();
System.out.println(inputFromServer);
keyword = inputFromServer;
getWordLabels(keyword);
jButton1.setEnabled(false);
} catch (IOException ex) {
Logger.getLogger(twoPlayers.class.getName()).log(Level.SEVERE, null, ex);
}
}
//compare letter with word, if contain show it on jlabel
private void searchLetter(){
String let = txtLetter.getText();
char letter = let.toCharArray()[0];
int length = keyword.length();
lblKeyword = new JLabel[length];
int widhLebelKeyword = 100;
int heightLabelKeyword = 20;
int gapbetweenLetter = 350/length;
if(keyword.contains(let)){
char[] letters = keyword.toCharArray();
for(int i = 0 ; i < letters.length; i++){
lblKeyword[i] = new JLabel("_");
//jLabel1.revalidate();
jLabel1.repaint();
lblKeyword[i].setForeground(Color.white);
lblKeyword[i].setBounds((gapbetweenLetter * i + 100), 300, widhLebelKeyword, heightLabelKeyword);
if(letters[i] == letter) {
lblKeyword[i].setText(Character.toString(letter));
jLabel1.add(lblKeyword[i]);
}
}
}
}
//wrong letter not contain in keyword will keep in board to remind gamer which letter is wrong
private void wrongLetter(){
String wrongLetter = txtLetter.getText();
String wrongLetterLabel = jLabel4.getText();
String showWrongLetter ="";
if(wrongLetterLabel == null){
showWrongLetter = wrongLetterLabel + " " + wrongLetter;
}else{
showWrongLetter = wrongLetterLabel + ", " + wrongLetter;
}
jLabel4.setText(showWrongLetter);
System.out.println(jLabel4.getText());
}
private void drawHangman(){
if(countWrongLetter == 1){
DrawBodyPart(BodyPart.Head);
}else if(countWrongLetter == 2){
DrawBodyPart(BodyPart.Head);
DrawBodyPart(BodyPart.Left_Eye);
}else if(countWrongLetter == 3){
DrawBodyPart(BodyPart.Head);
DrawBodyPart(BodyPart.Left_Eye);
DrawBodyPart(BodyPart.Right_Eye);
}else if(countWrongLetter == 4){
DrawBodyPart(BodyPart.Head);
DrawBodyPart(BodyPart.Left_Eye);
DrawBodyPart(BodyPart.Right_Eye);
DrawBodyPart(BodyPart.Mouth);
}else if(countWrongLetter == 5){
DrawBodyPart(BodyPart.Head);
DrawBodyPart(BodyPart.Left_Eye);
DrawBodyPart(BodyPart.Right_Eye);
DrawBodyPart(BodyPart.Mouth);
DrawBodyPart(BodyPart.Body);
}else if(countWrongLetter == 6){
DrawBodyPart(BodyPart.Head);
DrawBodyPart(BodyPart.Left_Eye);
DrawBodyPart(BodyPart.Right_Eye);
DrawBodyPart(BodyPart.Mouth);
DrawBodyPart(BodyPart.Body);
DrawBodyPart(BodyPart.Left_Arm);
}else if(countWrongLetter == 7){
DrawBodyPart(BodyPart.Head);
DrawBodyPart(BodyPart.Left_Eye);
DrawBodyPart(BodyPart.Right_Eye);
DrawBodyPart(BodyPart.Mouth);
DrawBodyPart(BodyPart.Body);
DrawBodyPart(BodyPart.Left_Arm);
DrawBodyPart(BodyPart.Right_Arm);
}else if(countWrongLetter == 8){
DrawBodyPart(BodyPart.Head);
DrawBodyPart(BodyPart.Left_Eye);
DrawBodyPart(BodyPart.Right_Eye);
DrawBodyPart(BodyPart.Mouth);
DrawBodyPart(BodyPart.Body);
DrawBodyPart(BodyPart.Left_Arm);
DrawBodyPart(BodyPart.Right_Arm);
DrawBodyPart(BodyPart.Left_Leg);
}else if(countWrongLetter == 9 ){
DrawBodyPart(BodyPart.Head);
DrawBodyPart(BodyPart.Left_Eye);
DrawBodyPart(BodyPart.Right_Eye);
DrawBodyPart(BodyPart.Mouth);
DrawBodyPart(BodyPart.Body);
DrawBodyPart(BodyPart.Left_Arm);
DrawBodyPart(BodyPart.Right_Arm);
DrawBodyPart(BodyPart.Left_Leg);
DrawBodyPart(BodyPart.Right_Leg);
}
}
private void btLetterActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
String letter = txtLetter.getText();
conn.getOut().println(letter);
String inputFromServer = conn.getIn().readLine();
System.out.println(inputFromServer);
if(inputFromServer.equals("containt")){
searchLetter();
drawHangman();
}else{
wrongLetter();
countWrongLetter++;
System.out.println(countWrongLetter);
drawHangman();
}
} catch (IOException ex) {
Logger.getLogger(twoPlayers.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void btReadyActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.out.println(getPlayerID());
}
// Variables declaration - do not modify
private javax.swing.JButton btLetter;
private javax.swing.JButton btPlay;
private javax.swing.JButton btReady;
private javax.swing.JButton btSendChat;
private javax.swing.JButton btWord;
private javax.swing.JButton jButton1;
private javax.swing.JDesktopPane jDesktopPane1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField txtLetter;
private javax.swing.JTextField txtWord;
// End of variables declaration
}