java——棋牌类游戏斗地主(webddz1.0)之一

这是本人最近一段时间写的斗地主的java代码,大体框架都实现了,主要缺少,AI的智能算法。

本版本是在singleddz3.0的基础上修改的,修改为了网络版本。

主要修改代码如下:

package com;


import java.awt.Button;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import com.ddz.LordIsMsg;
import com.ddz.SendPorkerMsg;
import com.ddz.WinMsg;
import com.ddz.YourTurnMsg;
import common.GameServer;
import common.NetClient;

public class GamePanel extends JPanel implements ActionListener{
	
	public String[] cardNames ;
	
	public CardLabel deck[] = new CardLabel[54];
	
	private Player players[] = new Player[3];
	
	public List<String> lordList;//地主牌
	
	public List<String> allSendCards = new ArrayList<String>();//地主牌
	
	private Container container = null;// 定义容器
	
	private JButton landlords[]=new JButton[2];//抢地主按钮
	
	public JLabel lordIcon; //地主图标

	
	private List<JComponent> allJComponent = new ArrayList<JComponent>();
	
//	private GameThread gameThread ;
	
	private String[][] buttonNames = new String[][]{{"抢地主","不抢"},{"出牌","不出"}};
	
	//public JButton startButton=new JButton("开始");//开始按钮
	
	private int[][] locations = {{50,60,0,17},{180,450,23,0},{700,60,0,17},{300,10,80,0}};
	
	private int[][] currentLocations = {{200,60,0,17},{180,300,23,0},{550,60,0,17}};
	
	
	public int lordIndex = -1;
	
	public int turnIndex = -1;
	
	public int gameState ;
	
	public int id = 1;  
	
	public Integer[] playerOrder;  //显示顺序

	
	public GamePanel(String name){
		
		
		
		initOther();
		
		//reStart();
		
		//this.setlord(1);
		
	    setVisible(true);
		
		//new Thread(new PaintThread()).start();
	    
	    dialog.setVisible(true);
	    
	   
	}
	
	public int getLocationS( int id){
		for (int i = 0; i < playerOrder.length; i++) {
			if(id==playerOrder[i]){
				return i;
			}
		}
		return 0;
	}
	
	public void paint(Graphics g) {
		super.paint(g);
		
			
			int width = this.getWidth();
			int height = this.getHeight();
			g.setFont(new java.awt.Font("华文隶书", 1, 20));
		if(null!=playerOrder[1]){
			g.drawString(this.playerOrder[1]+"", (int) (width * 0.5),
					(int) (height * 0.5));
		}
			
		if(null!=players[0]){
			
			g.drawString(players[0].getName(), (int) (width * 0.01),
					(int) (height * 0.5));
			
			g.drawString(players[1].getName(), (int) (width * 0.5),
					(int) (height * 0.95));
			
			g.drawString(players[2].getName(), (int) (width * 0.9), (int) (height * 0.5));
		  }
	}
	
	// 初始化窗体
	public void reStart() {
		
		for(int i=0;i<2;i++){
			landlords[i].setText(buttonNames[0][i]);
		}

		//cardNames = Robot.refreshCard(Robot.CardInit());
		
		for (int i = 0; i < cardNames.length; i++) {
   	        deck[i].setName(cardNames[i]);
   	        deck[i].turnRear();
   	        deck[i].setVisible(true);
   	        deck[i].setClicked(false);
	    }
		
		List<String>[] listNames = Robot.sendCard(cardNames);
		
		for (int i = 0; i < players.length; i++) {
			players[i] = new Player(playerOrder[i]+" "+i,i);
			players[i].setPlayerCards(listNames[playerOrder[i]]);
			//players[i].userState = 0;
		}
		
		for (int i = 0; i < players.length; i++) {
			Robot.reSetCardLocation(locations[i][0], locations[i][1], locations[i][2], locations[i][3], deck,players[i].getPlayerCards());
		}
		
		Robot.reSetCardLocation(locations[3][0], locations[3][1], locations[3][2], locations[3][3], deck,listNames[3]);
		
		lordList = listNames[3];
		
		Robot.myCardTurn(Robot.myCardLabels(deck, players[1].getPlayerCards()));
		
		gameState = 1;
		//players[1].userState = -1;
//		
//		gameThread = new GameThread(this);
//		
//		gameThread.start();
//		
//		gameThread.turnIndex = 1;
			
	}	
	
	

	// 初始化窗体
	private void initOther() {
		{
			container = this;
			container.setBackground(new Color(0, 112, 26)); // 背景为绿色
			container.setLayout(null);
		}

		{
			int[][] buttonLocations = {{320,400,100,0}};
			
			int[][] buttonSize = {{75,20},{40,40}};
			
			for(int i=0;i<2;i++)
			{
				landlords[i]=new JButton(buttonNames[0][i]);
				landlords[i].setBounds(buttonLocations[0][0]+i*buttonLocations[0][2],buttonLocations[0][1]+i*buttonLocations[0][3]
						,buttonSize[0][0],buttonSize[0][1]);
				landlords[i].addActionListener(this);
				landlords[i].setVisible(false);
				allJComponent.add(landlords[i]);
			}
			
			lordIcon=new JLabel(new ImageIcon("images/dizhu.gif"));
			lordIcon.setVisible(false);
			lordIcon.setSize(buttonSize[1][0],buttonSize[1][1]);
			allJComponent.add(lordIcon);
			
//			startButton.setBounds(buttonLocations[0][0],buttonLocations[0][1],buttonSize[0][0],buttonSize[0][1]);
//			startButton.addActionListener(this);
//			//landlords[i].setVisible(false);
//			allJComponent.add(startButton);
		}
		
		{
			
			for (int i = 0; i < deck.length; i++) {
		   	     deck[i] = new CardLabel("",this);
		   	     deck[i].setLocation(350, 50);
		   	     allJComponent.add(deck[i]);
		    }
			
			for (int i = 0; i < allJComponent.size(); i++) {
				container.add(allJComponent.get(i));
				container.setComponentZOrder(allJComponent.get(i), 0);
			}
		}

	}
	
	// 重设按钮
	public void rePlayCardLocation(int i) {
		Robot.reSetCardLocation(locations[i][0], locations[i][1], locations[i][2], locations[i][3], deck,getPlayers()[i].getPlayerCards());
	}
	
	// 重设按钮
	public void reCurrentCardLocation(int i) {
		int location = this.getLocationS(i);
		Robot.reSetCardLocation(currentLocations[location][0], currentLocations[location][1], currentLocations[location][2], currentLocations[location][3], 
				deck,getPlayers()[i].getSendCards());
	}
	
	// 重设按钮
	public void reButtonName() {
		for(int i=0;i<2;i++){
			if(landlords[i].getText().equals(buttonNames[0][i])){
				landlords[i].setText(buttonNames[1][i]);
			}else{
				landlords[i].setText(buttonNames[0][i]);
			}
		}
	}
	
	// 重设按钮可视性
	public void reButtonVisible(boolean visible) {
		for(int i=0;i<2;i++){
			landlords[i].setVisible(visible);
		}
	}

//	public int getGameState(){
//		return gameThread.gameState;
//	}
	
	// index 所出的牌
	public void sendCards(int index,List<String> sendCards) {
		if(null!=getPlayers()[index].getSendCards()){
			Robot.myCardLabelsVisible(deck, getPlayers()[index].getSendCards(), false);
		}
		
		allSendCards.addAll(sendCards);
		getPlayers()[index].setSendCards(sendCards);
		getPlayers()[index].getPlayerCards().removeAll(sendCards);
		reCurrentCardLocation(index);
		if(index!=id){
			Robot.myCardTurn(Robot.myCardLabels(deck, sendCards));
		}
		if(getPlayers()[index].getPlayerCards().size()==0){
			//gameState = -1;
			WinMsg msg = new WinMsg(id);
			gameThread.send(msg);
			
			//this.startButton.setVisible(true);
		}
		turnIndex = (turnIndex+1)%3;
	}
	
	public void setWinById(int id){

		for (int i = 0; i < getPlayers().length; i++) {
			Robot.myCardturnFront(Robot.myCardLabels(deck, players[i].getPlayerCards()));
		}
		String s = "恭喜电脑" + id + ",赢了! 你的智商有待提高哦";
		JOptionPane.showMessageDialog(this, s);

	}


	public static void main(String args[]) {
		GamePanel GamePanel = new GamePanel("daicy");
	
	}


	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		if(e.getSource() instanceof JButton){
			JButton button = (JButton) e.getSource();
//			if(startButton.equals(e.getSource())){
//				getPlayers()[1].userState = 0;
//			}else 
			reButtonVisible(false);
			if(button.getText().equals(buttonNames[0][0])){
				//reButtonName();
				LordIsMsg msg = new LordIsMsg(id);
				gameThread.send(msg);
			}else if(button.getText().equals(buttonNames[0][1])){
				YourTurnMsg msg = new YourTurnMsg((turnIndex+1)%3);
				gameThread.send(msg);
			}else if(button.getText().equals(buttonNames[1][0])){
				List<String> sendCards= Robot.mySendCardLabels(deck, this.getPlayers()[1].getPlayerCards());
				SendPorkerMsg msg = new SendPorkerMsg(id,sendCards);
				gameThread.send(msg);
				
				YourTurnMsg msg2 = new YourTurnMsg((turnIndex+1)%3);
				gameThread.send(msg2);
			}else if(button.getText().equals(buttonNames[1][1])){
				YourTurnMsg msg = new YourTurnMsg((turnIndex+1)%3);
				gameThread.send(msg);
			}
			
		}
	}

	public Player[] getPlayers() {
		return players;
	}

	public void setPlayers(Player[] players) {
		this.players = players;
	}
	

	
	
	
	private NetClient gameThread = new NetClient(this);
	
	ConnDialog dialog = new ConnDialog();
	
	
	class ConnDialog extends Dialog {
		Button b = new Button("确定");

		TextField tfIP = new TextField("127.0.0.1", 12);

		TextField tfPort = new TextField("" + GameServer.TCP_PORT, 4);

		TextField tfMyUDPPort = new TextField("2223", 4);

		public ConnDialog() {
			super((Frame) GamePanel.this.getParent(), true);

			this.setLayout(new FlowLayout());
			this.add(new Label("IP:"));
			this.add(tfIP);
			this.add(new Label("Port:"));
			this.add(tfPort);
			this.add(new Label("My UDP Port:"));
			this.add(tfMyUDPPort);
			this.add(b);
			this.setLocation(300, 300);
			this.pack();
			this.addWindowListener(new WindowAdapter() {
				@Override
				public void windowClosing(WindowEvent e) {
					setVisible(false);
				}
			});
			b.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent e) {
					String IP = tfIP.getText().trim();
					int port = Integer.parseInt(tfPort.getText().trim());
					int myUDPPort = Integer.parseInt(tfMyUDPPort.getText()
							.trim());
					gameThread.setUdpPort(myUDPPort);
					gameThread.connect(IP, port);
					setVisible(false);
				}

			});
		}

	}

	

}
package com;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class SocketData implements Serializable {
	/** */
	private static final long serialVersionUID = 1L;
	String[] cards;
	List<String> currentList[] =new ArrayList[3]; //  当前的出牌
	List<String> playerList[] = new ArrayList[3]; // 定义3个玩家表
	List<String> lordList;//地主牌
	public SocketData(){
		for (int i = 0; i < currentList.length; i++) {
			this.currentList[i] = new ArrayList<String>();
		}
		for (int i = 0; i < playerList.length; i++) {
			this.playerList[i] = new ArrayList<String>();
		}
		
		this.lordList = new ArrayList<String>();
		CardInit();
	}
	
    public void setAllPlayerList(Player players[], List<String> lordList){
		
		for (int i = 0; i < currentList.length; i++) {
			this.currentList[i] = players[i].getSendCards();
		}
		for (int i = 0; i < playerList.length; i++) {
			this.playerList[i] = players[i].getPlayerCards();
		}
		
		this.lordList = lordList;
	}
	
	public void initData(GamePanel gamePanel){
		gamePanel.cardNames = this.cards;
	}
	
	public void reverse(List<CardLabel> currentList[],List<CardLabel> playerList[],List<CardLabel> lordList){
		for (int i = 0; i < currentList.length; i++) {
			for (int j = 0; j < currentList[i].size(); j++) {
				currentList[i].get(j).setName(this.currentList[i].get(j));
			}
		}
		
		for (int i = 0; i < playerList.length; i++) {
			for (int j = 0; j < playerList[i].size(); j++) {
				playerList[i].get(j).setName(this.playerList[i].get(j));
			}
		}
		
		this.lordList = new ArrayList<String>();
		for (int j = 0; j < lordList.size(); j++) {
			lordList.get(j).setName(this.lordList.get(j));
		}
	}
	
	//初始化牌
	// 发牌洗牌
	public void CardInit() {
	    cards = Robot.refreshCard(Robot.CardInit());
		
		int t=0;
		for(int i=0;i<54;i++)
		{
			if(i>=51)//地主牌
			{
				lordList.add(cards[i]);
				continue;
			}
			playerList[(t++)%3].add(cards[i]);
		}
	}

	public String[] getCards() {
		return cards;
	}

	public void setCards(String[] cards) {
		this.cards = cards;
	}
	
	
	
}

package common;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

import com.SocketData;
import com.ddz.Msg;
import com.ddz.NewGameMsg;
import com.ddz.YourTurnMsg;


/***************************************************************************
 * TODO
 * <br>Created on 2013-7-3 上午11:20:19<br>
 * @author daicy
 ***************************************************************************/
public class GameServer {
	//private static int ID = 0;
	
	/**
	 * TCP的监听端口
	 */
	public static final int TCP_PORT = 8888;
	
	/**
	 * UDP的监听端口
	 */
	public static final int UDP_PORT = 6666;
	
	public SocketData socketData;

	List<Client> clients = new ArrayList<Client>();
	
	DatagramSocket ds = null;
	
	public int gameState;  //0准备 1 抢地主2出牌; -1 结束
	
	/**
	 * 启动服务器
	 *
	 */
	public void start() {
		
		
		try {
			ds = new DatagramSocket(UDP_PORT);
		} catch (SocketException e) {
			e.printStackTrace();
		}
		System.out.println("UDP thread started at port :" + UDP_PORT);

		new Thread(new UDPThread()).start();

		ServerSocket ss = null;
		try {
			ss = new ServerSocket(TCP_PORT);
		} catch (IOException e) {
			e.printStackTrace();
		}


		while (true) {
			    if(gameState==0){
		    	    int size = 3-clients.size();
					for (int i = 0; i < size; i++)  {
						Socket s = null;
						try {
							s = ss.accept();
							ObjectInputStream dis = new ObjectInputStream(s.getInputStream());
							String IP = s.getInetAddress().getHostAddress();
							Integer udpPort = (Integer) dis.readObject();
							Client c = new Client(IP, udpPort);
							clients.add(c);
							ObjectOutputStream dos = new ObjectOutputStream(s.getOutputStream());
							dos.writeObject(i);
							// s.close();
							System.out.println("A Client Connect! Addr- "
									+ s.getInetAddress() + ":" + s.getPort()
									+ "----UDP Port:" + udpPort);
							
						} catch (IOException e) {
							e.printStackTrace();
						} catch (ClassNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} finally {
							if (s != null) {
								try {
									s.close();
									s = null;
								} catch (IOException e) {
									e.printStackTrace();
								}
							}
						}
					}
					newGame();
					
			    }
			  
		}
       
		
	}
	
	public void newGame(){
		socketData = new SocketData();
		for (int i = 0; i < 3; i++)  {
			NewGameMsg msg = new NewGameMsg(socketData);
			msg.send(ds, clients.get(i).IP, clients.get(i).udpPort);
		}
		
		//随机产生谁是地主
		Integer num = (int) (Math.random() * 3);
		YourTurnMsg msg = new YourTurnMsg(num);
		msg.send(ds, clients.get(num).IP, clients.get(num).udpPort);
		
		gameState = 1;
	}

	public static void main(String[] args) {
		GameServer gameServer = new GameServer();
		gameServer.socketData = new SocketData();
		gameServer.start();
	}
	
	private class Client {
		String IP;

		int udpPort;

		public Client(String IP, int udpPort) {
			this.IP = IP;
			this.udpPort = udpPort;
		}
	}

	private class UDPThread implements Runnable {

		byte[] buf = new byte[1024];

		public void run() {
			
			while (ds != null) {
				DatagramPacket dp = new DatagramPacket(buf, buf.length);
				try {
					ds.receive(dp);
					if(!parse(dp)){
						for (int i = 0; i < clients.size(); i++) {
							Client c = clients.get(i);
							dp.setSocketAddress(new InetSocketAddress(c.IP,
									c.udpPort));
							ds.send(dp);
						}
					}
					
					System.out.println("a packet received!");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		
		private boolean parse(DatagramPacket dp) {
			ByteArrayInputStream bais = new ByteArrayInputStream(buf, 0, dp
					.getLength());
			ObjectInputStream dis ;
			int msgType = 0;
			try {
				dis = new ObjectInputStream(bais);
				msgType = (Integer) dis.readObject();
				switch (msgType) {
					case Msg.RESTART:
						   newGame();
						   return true;
					case Msg.WIN:
						   //newGame();
						
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return false;

		}


	}
}

package common;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

import com.GamePanel;
import com.Robot;
import com.SocketData;
import com.ddz.LordIsMsg;
import com.ddz.Msg;
import com.ddz.NewGameMsg;
import com.ddz.SendPorkerMsg;
import com.ddz.WinMsg;
import com.ddz.YourTurnMsg;


/***************************************************************************
 * TODO
 * <br>Created on 2013-7-3 上午11:20:28<br>
 * @author daicy
 ***************************************************************************/
public class NetClient {
	GamePanel tc;

	private int udpPort;

	String IP; // server IP

	DatagramSocket ds = null;
	
	SocketData socketData ;
	
	Integer[][] playerOrders = {{2,0,1},{0,1,2},{1,2,0}};

	
	// 设定地主
	public void setlord(int i) {
		tc.lordIndex = i;
		tc.turnIndex = i;
		
		int location = tc.getLocationS(i);
		
		{
			int[][] iconLocations = {{80,20},{80,430},{700,20}};
			tc.lordIcon.setLocation(iconLocations[location][0], iconLocations[location][1]);
			tc.lordIcon.setVisible(true);
			Robot.myCardTurn(Robot.myCardLabels(tc.deck, tc.lordList));
			Robot.second(3);
			tc.getPlayers()[location].getPlayerCards().addAll(tc.lordList);
			tc.rePlayCardLocation(location);
			if(location!=1){
				Robot.myCardTurn(Robot.myCardLabels(tc.deck, tc.lordList));
			}
			
		}
	}
	
	/**
	 * 根据场所构建网络客户端
	 * @param tc 游戏场所
	 */
	public NetClient(GamePanel tc) {
		this.tc = tc;

	}
	
	/**
	 * 连接服务器
	 * @param IP 服务器IP
	 * @param port 服务器端口
	 */
	public void connect(String IP, int port) {

		this.IP = IP;

		try {
			ds = new DatagramSocket(udpPort);
		} catch (SocketException e) {
			e.printStackTrace();
		}

		Socket s = null;
		try {
			s = new Socket(IP, port);
			ObjectOutputStream dos = new ObjectOutputStream(s.getOutputStream());
			dos.writeObject(udpPort);
			ObjectInputStream dis = new ObjectInputStream(s.getInputStream());
			int id = (Integer) dis.readObject();
			tc.id = id; 

			tc.playerOrder = playerOrders[id]; 
			System.out.println("Connected to server! and server give me a ID:"
					+ id);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (s != null) {
				try {
					s.close();
					s = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		new Thread(new UDPRecvThread()).start();
	}
	
	/**
	 * 发送消息
	 * @param msg 待发送的消息
	 */
	public void send(Msg msg) {
		msg.send(ds, IP, GameServer.UDP_PORT);
	}

	private class UDPRecvThread implements Runnable {

		byte[] buf = new byte[2048];

		public void run() {

			while (ds != null) {
				DatagramPacket dp = new DatagramPacket(buf, buf.length);
				try {
					ds.receive(dp);
					parse(dp);
					System.out.println("a packet received from server!");
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		private void parse(DatagramPacket dp) {
			ByteArrayInputStream bais = new ByteArrayInputStream(buf, 0, dp
					.getLength());
			ObjectInputStream dis ;
			int msgType = 0;
			try {
				dis = new ObjectInputStream(bais);
				msgType = (Integer) dis.readObject();
				Msg msg = null;
				switch (msgType) {
					case Msg.NEWGAME:
						msg = new NewGameMsg(NetClient.this.tc);
						msg.parse(dis);
						break;
					case Msg.LORDIS:
						msg = new LordIsMsg(NetClient.this.tc,NetClient.this);
						msg.parse(dis);
						break;
					case Msg.YOURTURN:
						msg = new YourTurnMsg(NetClient.this.tc);
						msg.parse(dis);
						break;
					case Msg.SENDEDPOKER:
						msg = new SendPorkerMsg(NetClient.this.tc);
						msg.parse(dis);
						break;
					case Msg.WIN:
						msg = new WinMsg(NetClient.this.tc,NetClient.this);
						msg.parse(dis);
						break;
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}
	
	/**
	 * 取得UDP端口(客户端接收数据用)
	 * @return
	 */
	public int getUdpPort() {
		return udpPort;
	}
	
	/**
	 * 设定UDP端口(客户端接收数据用)
	 * @param udpPort
	 */
	public void setUdpPort(int udpPort) {
		this.udpPort = udpPort;
	}
}



原文地址:https://www.cnblogs.com/daichangya/p/12959568.html