十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
自己纯手打,老半天才弄出来啊
创新互联-专业网站定制、快速模板网站建设、高性价比沾益网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式沾益网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖沾益地区。费用合理售后完善,10年实体公司更值得信赖。
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.util.Random;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Demo2 extends JFrame {
private JLabel lb1, lb2, lb3, lb4; // 提示标签
private JTextField ta1, ta2;// 两个文本框
private JButton b1, b2, b3; // 三个按钮
private JPanel p1, p2; // 两个JPanel面板
public Demo2() {
// 初始化所有组件
lb1 = new JLabel("欢迎使用人机猜拳程序");
lb2 = new JLabel("你出拳: ");
lb3 = new JLabel("电脑出拳:");
lb4 = new JLabel("结果");
ta1 = new JTextField();
ta1.setPreferredSize(new Dimension(60, 60)); // 设置大小
ta1.setEditable(false);//设置不可编辑
ta2 = new JTextField();
ta2.setPreferredSize(new Dimension(60, 60));
ta2.setEditable(false);//设置不可编辑
b1 = new JButton("剪刀");
b2 = new JButton("石头");
b3 = new JButton("布");
p1 = new JPanel();
p2 = new JPanel();
// 设置第一个面板内容
Box box = Box.createVerticalBox();
Box box1 = Box.createHorizontalBox();
box1.add(lb2);
box1.add(ta1);
box1.add(lb3);
box1.add(ta2);
box.add(lb1);
box.add(Box.createVerticalStrut(40));
box.add(box1);
box.add(Box.createVerticalStrut(10));
box.add(lb4);
box.add(new JLabel());
p1.add(box);
// 设置第二个面板
p2.setLayout(new GridBagLayout()); // 使用GridBagLayout布局管理器
p2.setPreferredSize(new Dimension(0, 60));
GridBagConstraints g2 = new GridBagConstraints();
g2.fill = GridBagConstraints.BOTH;
g2.weightx = 1.0;
g2.weighty = 1.0;
g2.gridx = 0;
g2.gridy = 0;
p2.add(b1, g2);
g2.gridx = 1;
p2.add(b2, g2);
g2.gridx = 2;
p2.add(b3, g2);
//为3个按钮添加事件
b1.addActionListener(new buttonAction());
b2.addActionListener(new buttonAction());
b3.addActionListener(new buttonAction());
this.getContentPane().add(p1);
this.getContentPane().add(p2, BorderLayout.SOUTH);
this.setTitle("机器人猜拳游戏");
this.setSize(300, 300);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//事件类
class buttonAction extends AbstractAction{
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==b1){
ta1.setText("剪刀");
init(ta1.getText());
}else if(e.getSource()==b2){
ta1.setText("石头");
init(ta1.getText());
}else if(e.getSource()==b3){
ta1.setText("布");
init(ta1.getText());
}
}
// 模拟电脑出拳,产生三个随机数。0代表剪刀,1代表石头,2代表布
public String getQuan(){
String str="";
int num=new Random().nextInt(3) ;
if(num==0){
str="剪刀";
}else if(num==1){
str="石头";
}else if(num==2){
str="布";
}
return str;
}
// 判断输赢方法
public String isying(String s1,String s2){
String s="";
if(s1.equals(s2)){
s="平局";
}else if(s1.equals("剪刀")s2.equals("布")){
s="你赢";
}else if(s1.equals("石头")s2.equals("剪刀")){
s="你赢";
}else if(s1.equals("布")s2.equals("石头")){
s="你赢";
}else{
s="电脑赢";
}
return s;
}
public void init(String wo){
String sy=""; // 保存输赢结果
String dncq=getQuan(); //电脑出拳
if(wo.equals(dncq)){
sy="平局";
}else if(wo.equals("剪刀")dncq.equals("布")){
sy="你赢";
}else if(wo.equals("石头")dncq.equals("剪刀")){
sy="你赢";
}else if(wo.equals("布")dncq.equals("石头")){
sy="你赢";
}else{
sy="电脑赢";
}
ta2.setText(dncq);// 电脑出拳
lb4.setText("结果:"+sy);
}
}
public static void main(String[] args) {
new Demo2();
}
}
java网络五子棋
下面的源代码分为4个文件;
chessClient.java:客户端主程序。
chessInterface.java:客户端的界面。
chessPad.java:棋盘的绘制。
chessServer.java:服务器端。
可同时容纳50个人同时在线下棋,聊天。
没有加上详细注释,不过绝对可以运行,j2sdk1.4下通过。
/*********************************************************************************************
1.chessClient.java
**********************************************************************************************/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
class clientThread extends Thread
{
chessClient chessclient;
clientThread(chessClient chessclient)
{
this.chessclient=chessclient;
}
public void acceptMessage(String recMessage)
{
if(recMessage.startsWith("/userlist "))
{
StringTokenizer userToken=new StringTokenizer(recMessage," ");
int userNumber=0;
chessclient.userpad.userList.removeAll();
chessclient.inputpad.userChoice.removeAll();
chessclient.inputpad.userChoice.addItem("所有人");
while(userToken.hasMoreTokens())
{
String user=(String)userToken.nextToken(" ");
if(userNumber0 !user.startsWith("[inchess]"))
{
chessclient.userpad.userList.add(user);
chessclient.inputpad.userChoice.addItem(user);
}
userNumber++;
}
chessclient.inputpad.userChoice.select("所有人");
}
else if(recMessage.startsWith("/yourname "))
{
chessclient.chessClientName=recMessage.substring(10);
chessclient.setTitle("Java五子棋客户端 "+"用户名:"+chessclient.chessClientName);
}
else if(recMessage.equals("/reject"))
{
try
{
chessclient.chesspad.statusText.setText("不能加入游戏");
chessclient.controlpad.cancelGameButton.setEnabled(false);
chessclient.controlpad.joinGameButton.setEnabled(true);
chessclient.controlpad.creatGameButton.setEnabled(true);
}
catch(Exception ef)
{
chessclient.chatpad.chatLineArea.setText("chessclient.chesspad.chessSocket.close无法关闭");
}
chessclient.controlpad.joinGameButton.setEnabled(true);
}
else if(recMessage.startsWith("/peer "))
{
chessclient.chesspad.chessPeerName=recMessage.substring(6);
if(chessclient.isServer)
{
chessclient.chesspad.chessColor=1;
chessclient.chesspad.isMouseEnabled=true;
chessclient.chesspad.statusText.setText("请黑棋下子");
}
else if(chessclient.isClient)
{
chessclient.chesspad.chessColor=-1;
chessclient.chesspad.statusText.setText("已加入游戏,等待对方下子...");
}
}
else if(recMessage.equals("/youwin"))
{
chessclient.isOnChess=false;
chessclient.chesspad.chessVictory(chessclient.chesspad.chessColor);
chessclient.chesspad.statusText.setText("对方退出,请点放弃游戏退出连接");
chessclient.chesspad.isMouseEnabled=false;
}
else if(recMessage.equals("/OK"))
{
chessclient.chesspad.statusText.setText("创建游戏成功,等待别人加入...");
}
else if(recMessage.equals("/error"))
{
chessclient.chatpad.chatLineArea.append("传输错误:请退出程序,重新加入 \n");
}
else
{
chessclient.chatpad.chatLineArea.append(recMessage+"\n");
chessclient.chatpad.chatLineArea.setCaretPosition(
chessclient.chatpad.chatLineArea.getText().length());
}
}
public void run()
{
String message="";
try
{
while(true)
{
message=chessclient.in.readUTF();
acceptMessage(message);
}
}
catch(IOException es)
{
}
}
}
public class chessClient extends Frame implements ActionListener,KeyListener
{
userPad userpad=new userPad();
chatPad chatpad=new chatPad();
controlPad controlpad=new controlPad();
chessPad chesspad=new chessPad();
inputPad inputpad=new inputPad();
Socket chatSocket;
DataInputStream in;
DataOutputStream out;
String chessClientName=null;
String host=null;
int port=4331;
boolean isOnChat=false; //在聊天?
boolean isOnChess=false; //在下棋?
boolean isGameConnected=false; //下棋的客户端连接?
boolean isServer=false; //如果是下棋的主机
boolean isClient=false; //如果是下棋的客户端
Panel southPanel=new Panel();
Panel northPanel=new Panel();
Panel centerPanel=new Panel();
Panel westPanel=new Panel();
Panel eastPanel=new Panel();
chessClient()
{
super("Java五子棋客户端");
setLayout(new BorderLayout());
host=controlpad.inputIP.getText();
westPanel.setLayout(new BorderLayout());
westPanel.add(userpad,BorderLayout.NORTH);
westPanel.add(chatpad,BorderLayout.CENTER);
westPanel.setBackground(Color.pink);
inputpad.inputWords.addKeyListener(this);
chesspad.host=controlpad.inputIP.getText();
centerPanel.add(chesspad,BorderLayout.CENTER);
centerPanel.add(inputpad,BorderLayout.SOUTH);
centerPanel.setBackground(Color.pink);
controlpad.connectButton.addActionListener(this);
controlpad.creatGameButton.addActionListener(this);
controlpad.joinGameButton.addActionListener(this);
controlpad.cancelGameButton.addActionListener(this);
controlpad.exitGameButton.addActionListener(this);
controlpad.creatGameButton.setEnabled(false);
controlpad.joinGameButton.setEnabled(false);
controlpad.cancelGameButton.setEnabled(false);
southPanel.add(controlpad,BorderLayout.CENTER);
southPanel.setBackground(Color.pink);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
if(isOnChat)
{
try
{
chatSocket.close();
}
catch(Exception ed)
{
}
}
if(isOnChess || isGameConnected)
{
try
{
chesspad.chessSocket.close();
}
catch(Exception ee)
{
}
}
System.exit(0);
}
public void windowActivated(WindowEvent ea)
{
}
});
add(westPanel,BorderLayout.WEST);
add(centerPanel,BorderLayout.CENTER);
add(southPanel,BorderLayout.SOUTH);
pack();
setSize(670,548);
setVisible(true);
setResizable(false);
validate();
}
public boolean connectServer(String serverIP,int serverPort) throws Exception
{
try
{
chatSocket=new Socket(serverIP,serverPort);
in=new DataInputStream(chatSocket.getInputStream());
out=new DataOutputStream(chatSocket.getOutputStream());
clientThread clientthread=new clientThread(this);
clientthread.start();
isOnChat=true;
return true;
}
catch(IOException ex)
{
chatpad.chatLineArea.setText("chessClient:connectServer:无法连接,建议重新启动程序 \n");
}
return false;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==controlpad.connectButton)
{
host=chesspad.host=controlpad.inputIP.getText();
try
{
if(connectServer(host,port))
{
chatpad.chatLineArea.setText("");
controlpad.connectButton.setEnabled(false);
controlpad.creatGameButton.setEnabled(true);
controlpad.joinGameButton.setEnabled(true);
chesspad.statusText.setText("连接成功,请创建游戏或加入游戏");
}
}
catch(Exception ei)
{
chatpad.chatLineArea.setText("controlpad.connectButton:无法连接,建议重新启动程序 \n");
}
}
if(e.getSource()==controlpad.exitGameButton)
{
if(isOnChat)
{
try
{
chatSocket.close();
}
catch(Exception ed)
{
}
}
if(isOnChess || isGameConnected)
{
try
{
chesspad.chessSocket.close();
}
catch(Exception ee)
{
}
}
System.exit(0);
}
if(e.getSource()==controlpad.joinGameButton)
{
String selectedUser=userpad.userList.getSelectedItem();
if(selectedUser==null || selectedUser.startsWith("[inchess]") ||
selectedUser.equals(chessClientName))
{
chesspad.statusText.setText("必须先选定一个有效用户");
}
else
{
try
{
if(!isGameConnected)
{
if(chesspad.connectServer(chesspad.host,chesspad.port))
{
isGameConnected=true;
isOnChess=true;
isClient=true;
controlpad.creatGameButton.setEnabled(false);
controlpad.joinGameButton.setEnabled(false);
controlpad.cancelGameButton.setEnabled(true);
chesspad.chessthread.sendMessage("/joingame "+userpad.userList.getSelectedItem()+" "+chessClientName);
}
}
else
{
isOnChess=true;
isClient=true;
controlpad.creatGameButton.setEnabled(false);
controlpad.joinGameButton.setEnabled(false);
controlpad.cancelGameButton.setEnabled(true);
chesspad.chessthread.sendMessage("/joingame "+userpad.userList.getSelectedItem()+" "+chessClientName);
}
}
catch(Exception ee)
{
isGameConnected=false;
isOnChess=false;
isClient=false;
controlpad.creatGameButton.setEnabled(true);
controlpad.joinGameButton.setEnabled(true);
controlpad.cancelGameButton.setEnabled(false);
chatpad.chatLineArea.setText("chesspad.connectServer无法连接 \n"+ee);
}
}
}
if(e.getSource()==controlpad.creatGameButton)
{
try
{
if(!isGameConnected)
{
if(chesspad.connectServer(chesspad.host,chesspad.port))
{
isGameConnected=true;
isOnChess=true;
isServer=true;
controlpad.creatGameButton.setEnabled(false);
controlpad.joinGameButton.setEnabled(false);
controlpad.cancelGameButton.setEnabled(true);
chesspad.chessthread.sendMessage("/creatgame "+"[inchess]"+chessClientName);
}
}
else
{
isOnChess=true;
isServer=true;
controlpad.creatGameButton.setEnabled(false);
controlpad.joinGameButton.setEnabled(false);
controlpad.cancelGameButton.setEnabled(true);
chesspad.chessthread.sendMessage("/creatgame "+"[inchess]"+chessClientName);
}
}
catch(Exception ec)
{
isGameConnected=false;
isOnChess=false;
isServer=false;
controlpad.creatGameButton.setEnabled(true);
controlpad.joinGameButton.setEnabled(true);
controlpad.cancelGameButton.setEnabled(false);
ec.printStackTrace();
chatpad.chatLineArea.setText("chesspad.connectServer无法连接 \n"+ec);
}
}
if(e.getSource()==controlpad.cancelGameButton)
{
if(isOnChess)
{
chesspad.chessthread.sendMessage("/giveup "+chessClientName);
chesspad.chessVictory(-1*chesspad.chessColor);
controlpad.creatGameButton.setEnabled(true);
controlpad.joinGameButton.setEnabled(true);
controlpad.cancelGameButton.setEnabled(false);
chesspad.statusText.setText("请建立游戏或者加入游戏");
}
if(!isOnChess)
{
controlpad.creatGameButton.setEnabled(true);
controlpad.joinGameButton.setEnabled(true);
controlpad.cancelGameButton.setEnabled(false);
chesspad.statusText.setText("请建立游戏或者加入游戏");
}
isClient=isServer=false;
}
}
public void keyPressed(KeyEvent e)
{
TextField inputWords=(TextField)e.getSource();
if(e.getKeyCode()==KeyEvent.VK_ENTER)
{
if(inputpad.userChoice.getSelectedItem().equals("所有人"))
{
try
{
out.writeUTF(inputWords.getText());
inputWords.setText("");
}
catch(Exception ea)
{
chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接 \n");
userpad.userList.removeAll();
inputpad.userChoice.removeAll();
inputWords.setText("");
controlpad.connectButton.setEnabled(true);
}
}
else
{
try
{
out.writeUTF("/"+inputpad.userChoice.getSelectedItem()+" "+inputWords.getText());
inputWords.setText("");
}
catch(Exception ea)
{
chatpad.chatLineArea.setText("chessClient:KeyPressed无法连接,建议重新连接 \n");
userpad.userList.removeAll();
inputpad.userChoice.removeAll();
inputWords.setText("");
controlpad.connectButton.setEnabled(true);
}
}
}
}
public void keyTyped(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}
public static void main(String args[])
{
chessClient chessClient=new chessClient();
}
}
/******************************************************************************************
下面是:chessInteface.java
******************************************************************************************/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
class userPad extends Panel
{
List userList=new List(10);
userPad()
{
setLayout(new BorderLayout());
for(int i=0;i50;i++)
{
userList.add(i+"."+"没有用户");
}
add(userList,BorderLayout.CENTER);
}
}
class chatPad extends Panel
{
TextArea chatLineArea=new TextArea("",18,30,TextArea.SCROLLBARS_VERTICAL_ONLY);
chatPad()
{
setLayout(new BorderLayout());
add(chatLineArea,BorderLayout.CENTER);
}
}
class controlPad extends Panel
{
Label IPlabel=new Label("IP",Label.LEFT);
TextField inputIP=new TextField("localhost",10);
Button connectButton=new Button("连接主机");
Button creatGameButton=new Button("建立游戏");
Button joinGameButton=new Button("加入游戏");
Button cancelGameButton=new Button("放弃游戏");
Button exitGameButton=new Button("关闭程序");
controlPad()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
setBackground(Color.pink);
add(IPlabel);
add(inputIP);
add(connectButton);
add(creatGameButton);
add(joinGameButton);
add(cancelGameButton);
add(exitGameButton);
}
}
class inputPad extends Panel
{
TextField inputWords=new TextField("",40);
Choice userChoice=new Choice();
inputPad()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
for(int i=0;i50;i++)
{
userChoice.addItem(i+"."+"没有用户");
}
userChoice.setSize(60,24);
add(userChoice);
add(inputWords);
}
}
/**********************************************************************************************
下面是:chessPad.java
**********************************************************************************************/
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
class chessThread extends Thread
{
chessPad chesspad;
chessThread(chessPad chesspad)
{
this.chesspad=chesspad;
}
public void sendMessage(String sndMessage)
{
try
{
chesspad.outData.writeUTF(sndMessage);
}
catch(Exception ea)
{
System.out.println("chessThread.sendMessage:"+ea);
}
}
public void acceptMessage(String recMessage)
{
if(recMessage.startsWith("/chess "))
{
StringTokenizer userToken=new StringTokenizer(recMessage," ");
String chessToken;
String[] chessOpt={"-1","-1","0"};
int chessOptNum=0;
while(userToken.hasMoreTokens())
{
chessToken=(String)userToken.nextToken(" ");
if(chessOptNum=1 chessOptNum=3)
{
chessOpt[chessOptNum-1]=chessToken;
}
chessOptNum++;
}
chesspad.netChessPaint(Integer.parseInt(chessOpt[0]),Integer.parseInt(chessOpt[1]),Integer.parseInt(chessOpt[2]));
}
else if(recMessage.startsWith("/yourname "))
{
chesspad.chessSelfName=recMessage.substring(10);
}
else if(recMessage.equals("/error"))
{
chesspad.statusText.setText("错误:没有这个用户,请退出程序,重新加入");
}
else
{
//System.out.println(recMessage);
}
}
public void run()
{
String message="";
try
{
while(true)
{
message=chesspad.inData.readUTF();
acceptMessage(message);
}
}
catch(IOException es)
{
}
}
}
class chessPad extends Panel implements MouseListener,ActionListener
{
int chessPoint_x=-1,chessPoint_y=-1,chessColor=1;
int chessBlack_x[]=new int[200];
int chessBlack_y[]=new int[200];
int chessWhite_x[]=new int[200];
int chessWhite_y[]=new int[200];
int chessBlackCount=0,chessWhiteCount=0;
int chessBlackWin=0,chessWhiteWin=0;
boolean isMouseEnabled=false,isWin=false,isInGame=false;
TextField statusText=new TextField("请先连接服务器");
Socket chessSocket;
DataInputStream inData;
DataOutputStream outData;
String chessSelfName=null;
String chessPeerName=null;
String host=null;
int port=4331;
chessThread chessthread=new chessThread(this);
chessPad()
{
setSize(440,440);
setLayout(null);
setBackground(Color.pink);
addMouseListener(this);
add(statusText);
statusText.setBounds(40,5,360,24);
statusText.setEditable(false);
}
public boolean connectServer(String ServerIP,int ServerPort) throws Exception
{
try
{
chessSocket=new Socket(ServerIP,ServerPort);
inData=new DataInputStream(chessSocket.getInputStream());
outData=new DataOutputStream(chessSocket.getOutputStream());
chessthread.start();
return true;
}
catch(IOException ex)
{
statusText.setText("chessPad:connectServer:无法连接 \n");
}
return false;
}
public void chessVictory(int chessColorWin)
{
this.removeAll();
for(int i=0;i=chessBlackCount;i++)
{
chessBlack_x[i]=0;
chessBlack_y[i]=0;
}
for(int i=0;i=chessWhiteCount;i++)
{
chessWhite_x[i]=0;
chessWhite_y[i]=0;
}
chessBlackCount=0;
chessWhiteCount=0;
add(statusText);
statusText.setBounds(40,5,360,24);
if(chessColorWin==1)
{ chessBlackWin++;
statusText.setText("黑棋胜,黑:白为"+chessBlackWin+":"+chessWhiteWin+",重新开局,等待白棋下子...");
}
else if(chessColorWin==-1)
{
chessWhiteWin++;
statusText.setText("白棋胜,黑:白为"+chessBlackWin+":"+chessWhiteWin+",重新开局,等待黑棋下子...");
}
}
public void getLocation(int a,int b,int color)
{
if(color==1)
{
chessBlack_x[chessBlackCount]=a*20;
chessBlack_y[chessBlackCount]=b*20;
chessBlackCount++;
}
else if(color==-1)
{
chessWhite_x[chessWhiteCount]=a*20;
chessWhite_y[chessWhiteCount]=b*20;
chessWhiteCount++;
}
}
public boolean checkWin(int a,int b,int checkColor)
{
int step=1,chessLink=1,chessLinkTest=1,chessCompare=0;
if(checkColor==1)
{
chessLink=1;
for(step=1;step=4;step++)
{
for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)
{
if(((a+step)*20==chessBlack_x[chessCompare]) ((b*20)==chessBlack_y[chessCompare]))
{
chessLink=chessLink+1;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;
}
for(step=1;step=4;step++)
{
for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)
{
if(((a-step)*20==chessBlack_x[chessCompare]) (b*20==chessBlack_y[chessCompare]))
{
chessLink++;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;
}
chessLink=1;
chessLinkTest=1;
for(step=1;step=4;step++)
{
for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)
{
if((a*20==chessBlack_x[chessCompare]) ((b+step)*20==chessBlack_y[chessCompare]))
{
chessLink++;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;
}
for(step=1;step=4;step++)
{
for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)
{
if((a*20==chessBlack_x[chessCompare]) ((b-step)*20==chessBlack_y[chessCompare]))
{
chessLink++;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;
}
chessLink=1;
chessLinkTest=1;
for(step=1;step=4;step++)
{
for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)
{
if(((a-step)*20==chessBlack_x[chessCompare]) ((b+step)*20==chessBlack_y[chessCompare]))
{
chessLink++;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;
}
for(step=1;step=4;step++)
{
for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)
{
if(((a+step)*20==chessBlack_x[chessCompare]) ((b-step)*20==chessBlack_y[chessCompare]))
{
chessLink++;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;
}
chessLink=1;
chessLinkTest=1;
for(step=1;step=4;step++)
{
for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)
{
if(((a+step)*20==chessBlack_x[chessCompare]) ((b+step)*20==chessBlack_y[chessCompare]))
{
chessLink++;
if(chessLink==5)
{
return(true);
}
}
}
if(chessLink==(chessLinkTest+1))
chessLinkTest++;
else
break;
}
for(step=1;step=4;step++)
{
for(chessCompare=0;chessCompare=chessBlackCount;chessCompare++)
{
if(((a-step)*20==chessBlack_x[chessCompare]) ((b-step)*20==chessBlack_y[chessCompare]))
{
chessLink++;
if(chessLink==5)
{
return(true);
}
}
我之前写了个猜拳游戏的源代码,不过没你想的这么精彩。你才给5分就给你你自己修改了,应该很简单的。要多给点分我可以帮你修改。
import java.util.Scanner;
import java.util.Random;
public class caiquan
{
final int jiandao=0;
final int shitou=1;
final int bu=2;
public static void main(String[] args)
{
String yn=;y;;
while (yn.equals(;y;))
{
Scanner scanner = new Scanner(System.in);
System.out.println(;欢迎玩猜拳游戏。请输入0,1,2:0表示剪刀,1表示石头,2表示布;);
int a = scanner.nextInt();
Random rd = new Random();
int b = rd.nextInt(3);
switch (b)
{
case 0:
{
System.out.println(;系统出的是剪刀;);
switch(a)
{
case 0:System.out.println(;平;);break;
case 1:System.out.println(;赢;);break;
case 2:System.out.println(;输;);break;
}
}
break;
case 1:
{
System.out.println(;系统出的是石头;);
switch(a)
{
case 0:System.out.println(;输;);break;
case 1:System.out.println(;平;);break;
case 2:System.out.println(;赢;);break;
}
}
break;
case 2:
{
System.out.println(;系统出的是布;);
switch(a)
{
case 0:System.out.println(;赢;);break;
case 1:System.out.println(;输;);break;
case 2:System.out.println(;平;);break;
}
}
}
Scanner ynn = new Scanner(System.in);
System.out.println(;是否继续?是请输入y,否则输入n。;);
yn=ynn.next();
}
}
}
先建立个Game包
然后我做的是分了5个类来做的
TestStartGuess 类
package com.game.guess;
public class TestStartGuess {
/**
* 人机互动版猜拳游戏
* 程序入口
*/
public static void main(String[] args) {
Game game=new Game();
game.initial();
game.startGame();
}
}
2.Person 类
package com.game.guess;
import java.util.Scanner;
/**
* 用户类
*阶段1完成
* @param Scanner
*/
public class Person {
String name ="匿名";//名字
int score =0;//积分
/**
* 出拳
*@return出拳结果:1.剪刀 2.石头 3.布
*/
public int showFist(){
//接收用户的选择
Scanner input =new Scanner(System.in);
System.out.print("\n请出拳:1.剪刀 2.石头 3.布 (输入相应数字):");
int show=input.nextInt();
//输出出拳结果,并返回
switch(show){
case 1:
System.out.println("你出拳:剪刀");
break;
case 2:
System.out.println("你出拳:石头");
break;
case 3:
System.out.println("你出拳:布");
break;
}
return show;
}
}
3.Computer 类
package com.game.guess;
/**
*计算机类
*阶段2完成
*/
public class Computer{
String name="电脑";//名字
int score = 0;;//积分
/**
*出拳
*@return 出拳结果:1.剪刀 2.石头 3.布
*/
public int showFist(){
//产生随机数
int show =(int)(Math.random()*10)%3+1;//产生随机数,表示电脑出拳
//输出出拳结果并返回
switch(show){
case 1:
System.out.println(name+"你出拳:剪刀");
break;
case 2:
System.out.println(name+"你出拳:石头");
break;
case 3:
System.out.println(name+"你出拳:布");
break;
}
return show;
}
}
4.Game 类
package com.game.guess;
import java.util.Scanner;
/**
* 游戏类类完全版
* 阶段7:功能扩展
* @param computer
*
*/
public class Gamecomputer {
Person person; //甲方
Computer computer; //乙方
int count;//对战次数
/**
* 初始化
*/
public void initial(){
person=new Person();
computer=new Computer();
count=0;
}
/**
* 开始游戏
*/
@SuppressWarnings("resource")
public void startGame(){
System.out.println("-------欢迎进入游戏世界-------\n");
System.out.println("\n\t\t***************");
System.out.println("\t\t**猜拳,开始 **");
System.out.println("\t\t***************");
System.out.println("\n\n出拳规则:1.剪刀,2.石头,3.布");
Scanner input=new Scanner(System.in);
String exit="n"; //退出系统
do{
initial();//初始化
/*选择对方角色*/
System.out.print("请选择对方角色:(1:刘备,2:孙权,3:曹操):");
int role=input.nextInt();
if(role==1){
computer.name="刘备";
}else if(role==2){
computer.name="孙权";
}else if(role==3){
computer.name="曹操";
}
//扩展功能1:输入用户姓名
/*输入用户姓名*/
System.out.print("请输入你的姓名:");
person.name=input.next();
System.out.println(person.name+"VS"+computer.name+"对战\n");
//扩展功能1结束
System.out.print("要开始吗?(y/n)");
String start=input.next();//开始每一局游戏
int perFist; //用户出的拳
int compFist; //计算机出的拳
while(start.equals("y")){
/*出拳*/
perFist=person.showFist();
compFist=computer.showFist();
/*裁决*/
if((perFist==1compFist==1)||(perFist==2compFist==2)||(perFist==3compFist==3)){
System.out.println("结果:和局,真衰!嘿嘿,等着瞧吧!\n"); //平局
}else if((perFist==1compFist==3)||(perFist==2compFist==1)||(perFist==3compFist==2)){
System.out.println("结果:恭喜,你赢了!"); //用户赢
person.score++;
}else{
System.out.println("结果说:^_^,你输了,真笨!\n"); //计算机赢
computer.score++;
}
count++;
System.out.println("\n是否开始下一轮(y/n):");
start=input.next();
}
/*显示结果*/
showResult();
//扩展功能3:循环游戏,知道退出系统
System.out.print("\n要开始下一局吗?(y/n):");
exit=input.next();
System.out.println();
//扩展功能3结束
}while(!exit.equals("n"));
System.out.println("系统退出!");
}
/**
* 显示比赛结果
*/
public void showResult(){
/*显示对战次数*/
System.out.println("-------------------------------");
System.out.println(computer.name+"VS"+person.name);
System.out.println("对战次数:"+count);
//扩展功能2:显示最终的得分
System.out.println("\n姓名\t得分");
System.out.println(person.name+"\t"+person.score);
System.out.println(computer.name+"\t"+computer.score+"\n");
//扩展功能2结束
/*显示对战结果*/
int result=calcResult();
if(result==1){
System.out.println("结果:打成平手,下次再和你一分高下!");
}else if(result==2){
System.out.println("结果:恭喜恭喜!"); //用户获胜
}else{
System.out.println("结果:呵呵,笨笨,下次加油啊!"); //计算机获胜
}
System.out.println("--------------------------------");
}
/**
* 计算比赛结果
* @return1:战平; 2:用户赢; 3:电脑赢
*/
public int calcResult(){
if(person.score==computer.score){
return 1;//战平
}else if(person.scorecomputer.score){
return 2;//用户赢
}else{
return 3;//电脑赢
}
}
}
5.Start 类
package com.game.guess;
public class StartGuess {
public static void main (String[] args){
Game c = new Game();
c.initial();
c.startGame();
}
}
然后编译执行就OK了
希望能帮到你
根据你的改了个!不好意思,其中读写的思路稍微有点不同!不过可以做参考!
Server端代码:
import java.net.*;
import java.io.*;
import java.util.*;
public class TestServer {
ServerSocket s = null;
boolean started = false;//用来监听服务器是否启动!
ListServerReaderWriter clients = new ArrayListServerReaderWriter();//用来存放启动的客服端
public static void main(String[] args) {
new TestServer().start();
}
public void start() {
try {
s = new ServerSocket(5050);
started = true;
} catch(SocketException e) {
System.out.println("5050端口正在使用中!!!请关掉相关程序并重新运行服务器!");
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
int i = 1;
try {
while(started) {
Socket ss = s.accept();
ServerReaderWriter c = new ServerReaderWriter(ss);//建立客服端
System.out.println("第" + i + "个客服端启动!");
++i;
new Thread(c).start();//启动线程
clients.add(c);
}
} catch (EOFException e) {
System.out.println("客服端被关闭!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerReaderWriter implements Runnable { //建议使用Runnable避免你重写run方法麻烦!
private Socket s;
private DataInputStream dis = null;//注意赋值,养成好习惯!
private DataOutputStream dos = null;
private boolean bConnected = false;//用于调用连接成功后的run方法
public ServerReaderWriter(Socket s) {
this.s = s;
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
bConnected = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String str) {
try {
dos.writeUTF(str);
} catch (IOException e) {
clients.remove(this);
System.out.println("有客户退出!");
}
}
public void run() {
try {
while (bConnected) {
String input = dis.readUTF();
System.out.println(input);
for(int i=0; iclients.size(); ++i) {
ServerReaderWriter c = clients.get(i);
c.send(input);
}
}
} catch(SocketException e) {
System.out.println("一个客服端已关闭,请勿再像他发送信息!");
} catch (EOFException e) {
System.out.println("谢谢使用!");
}catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (dis != null) {
dis.close();
}
if (dos != null) {
dos.close();
}
if (s != null) {
s.close();
s = null;
}
//clients.clear();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
Client端代码:
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class TestClient extends Frame { //用到Frame生产界面比较直观
Socket s = null;
DataOutputStream dos = null;
DataInputStream dis = null;
private boolean bConnected = false;
TextField tfText = new TextField();
TextArea taContent = new TextArea();
Thread tRecv = new Thread(new ClientReaderWriter());
public static void main(String[] args){
new TestClient().launchFrame();
}
public void launchFrame() {
this.setSize(300, 300); //设置客服端窗口格式
this.setLocation(400, 300);
add(tfText, BorderLayout.SOUTH);
add(taContent, BorderLayout.NORTH);
this.pack();
this.addWindowListener(new WindowAdapter() { //监听窗口关闭事件
public void windowClosing(WindowEvent arg0) {
disconnect();
System.exit(0);
}
});
tfText.addActionListener(new TFListener());
setVisible(true);
connect();
tRecv.start();
}
public void connect() {
try {
s = new Socket("127.0.0.1", 5050); //依据自己的服务器,我这里用的localhost
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
System.out.println("连接服务器!");
bConnected = true;
} catch(ConnectException e) {
System.out.println("请检查服务器是否启动!");
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.exit(0);
}
catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
dos.close();
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private class TFListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str = tfText.getText().trim();
tfText.setText("");
try {
dos.writeUTF(str);
if(str.equals("bye")){
System.exit(0);
}
dos.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
class ClientReaderWriter implements Runnable {
public void run() {
try {
while(bConnected) {
String input = dis.readUTF();
taContent.setText(taContent.getText() + input +'\n');
}
} catch (SocketException e) {
System.out.println("轻轻的我走了!Bye-bye!");
} catch (EOFException e) {
System.out.println("我断网了,再见!");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}