码迷,mamicode.com
首页 > 其他好文 > 详细

Monster Card Game的设计与实现之服务器篇

时间:2014-12-09 21:31:59      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:java   服务器   线程   通信   游戏   

服务器端大概有这么几个类:

MonsterCard类:定义卡牌的属性

Deck类:用来生产一堆卡牌,在这个游戏中共40张怪兽卡牌。

Player类:用来定义一个玩家,这个玩家具有40张怪兽卡牌和8000滴血,然后根据玩家的对战情况进行减少卡牌或扣除学的操作。

MyServerReader类:建立一个线程,根据对方玩家发来的的命令来对自己或对方玩家的怪兽卡牌进行操作

MyServerWriter类:建立一个线程,根据自己发出的的命令来对自己或对方玩家的怪兽卡牌进行操作

ServerTest类:负责和客户端进行通信,共享玩家的数据。

bubuko.com,布布扣

MonsterCard

//定义卡牌的属性

package game;

import java.util.Random;

public class MonsterCard {
	public static Random random=new Random();
	private String MonsterName;
	private int attactPower;
	private int defencePower;
	public MonsterCard(String name,int attack,int defence) {
		// TODO Auto-generated constructor stub
		MonsterName=name;
		attactPower=attack;
		defencePower=defence;
	}

	public int getAttackPower()
	{
		return attactPower;
	}
	public int getDefencePower()
	{
		return defencePower;
	}
	public String getName()
	{
		return MonsterName;
	}
}

Deck

//用来生产一堆卡牌,在这个游戏中共40张怪兽卡牌。

package game;
import java.util.LinkedList;

//**************************class Deck***************************
public class Deck {
	private LinkedList<MonsterCard>list=new LinkedList<MonsterCard>();
	private static int n=40;
	private int count;
	String []monsterName={"bear","tiger","dragan","lion","elephent","dog","cat","dophin"};
	int len=monsterName.length-1;
	public Deck()
	{
		count=n;
		int attackPower=0;
		int defencePower=0;
		for(int i=0;i<n;i++)
		{
			String name=monsterName[MonsterCard.random.nextInt(len)];
			attackPower=MonsterCard.random.nextInt(2500);
			defencePower=MonsterCard.random.nextInt(2000);
			list.addLast(new MonsterCard(name, attackPower, defencePower));
		}
	}
	//由Deck中取牌
	public  MonsterCard GetCard()
	{
		int num=MonsterCard.random.nextInt(count);
		MonsterCard temp=list.get(num);
		list.remove(num);
		count--;
		return temp;
	}
	
}


Player

//用来定义一个玩家,这个玩家具有40张怪兽卡牌和8000滴血,然后根据玩家的对战情况进行减少卡牌或扣除学的操作。

package game;

import java.util.Iterator;
import java.util.LinkedList;
//*********************class Player***************************
public class Player
{
	private boolean isOk;//标识是否可以对战场上的牌进行操作
	private int term=1;//记录第几局
	private  int blood=8000;
	private Deck deck=new Deck();
	private LinkedList<MonsterCard>cardInHand=new LinkedList<MonsterCard>();
	private LinkedList<MonsterCard>cardInFiled=new LinkedList<MonsterCard>();
	private int count=0;
	//初始化手中的牌
	public Player(){
		getCard();
	}
	//是否被打败
	public boolean beDefeated()
	{
		if(blood<=0||(count>=40&&cardInFiled.isEmpty()&&cardInHand.isEmpty()))
			return true;
		else 
			return false;
	}
	//杀死战场的怪兽
	public void killMonster(int n)
	{
		cardInFiled.remove(n-1);
	}
	//改变血量
	public void changeBlood(int n)
	{
		blood-=n;
	}
	//获得血量
	public int getBlood()
	{
		return blood;
	}
	//changeTerm
	public void changeTerm()
	{
		++term;
	}
	//get Term
	public int getTerm()
	{
		return term;
	}
	//获得手上的牌
	public LinkedList<MonsterCard>getCardInHand()
	{
		return cardInHand;
	}
	//获得战场上的牌
	public LinkedList<MonsterCard>getCardInField()
	{
		return cardInFiled;
	}
	//标识是否可以对战场上的牌进行操作
	public boolean isNotOk()
	{
		if(count>1)
			isOk=true;
		else {
			isOk=false;
		}
		return isOk;
	}
	//从deck堆中获得牌
	public void getCard()
	{
		cardInHand.addLast(deck.GetCard());
		count++;
		isNotOk();//用来标识是否可对自己战场上的牌进行操作
	}
	//显示牌
	public String showCard(LinkedList<MonsterCard>list)
	{
		StringBuffer sBuffer=new StringBuffer();
		Iterator<MonsterCard>iterator=list.listIterator();
		MonsterCard monster=null;
		while(iterator.hasNext())
		{
			monster=(MonsterCard)iterator.next();
			sBuffer.append("名字:"+monster.getName());
			sBuffer.append(" 攻击力:"+monster.getAttackPower());
			sBuffer.append("防御力:"+monster.getDefencePower());
			sBuffer.append("\n");
		}
		return sBuffer.toString();
	}
	//显示手中的牌
	public String showMyHand()
	{
		return showCard(cardInHand);
	}
	//显示手中的牌
	public String showMyBf()
	{
		return showCard(cardInFiled);
	}
	//召唤手中的牌到战场上
	public void SummonMonster(int n)
	{
		if(count==0)
			System.out.println("Player1 has been defeated!");
		MonsterCard monsterCard=cardInHand.get(n-1);
		cardInFiled.addLast(monsterCard);
		cardInHand.remove(n-1);
		count--;
	}
	//选择自己的怪兽
	public MonsterCard chooseMyMonster(int n)
	{
		return cardInFiled.get(n-1);
	}
	
}


MyServerReader

//建立一个线程,根据对方玩家发来的的命令来对自己或对方玩家的怪兽卡牌进行操作

package game;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

//创建一个进程用来进行接收读取数据  
public class MyServerReader extends ServerTest3 implements Runnable{
    private DataInputStream dis; 
    private DataOutputStream dos;  
    public MyServerReader (DataInputStream dis,DataOutputStream dos){  
        this.dis = dis;  
        this.dos=dos;
    }  
    public void run(){  
        String msg;  
        String string=null;
        int lenSummon="Summon monster".length();
        int lenChoose="choose my card".length();
        int lenAttack="attack".length();
        int num=0;
        MonsterCard monsterCard=null;
        try{  
            while(true){
            	num=0;
            	string=null;
            	monsterCard=null;
                msg = dis.readUTF().trim();
                if(msg.equals("end the term"))
                {
                	player1.changeTerm();
                	dos.writeUTF("wait..."); 	
                	player1.getCard();
                	System.out.println("Term "+player1.getTerm()+":");
                	continue;
                }else if(msg.equals("show my hand"))
                {
                	string=player2.showMyHand();
                	dos.writeUTF(string);
                	continue;
                	//System.out.println(string);
                }else if (msg.equals("show my bf")) {
                	string=player2.showMyBf();
                	dos.writeUTF(string);
                	continue;
				}else if(msg.equals("show op bf"))
				{
					string = player1.showMyBf();
					dos.writeUTF(string);
					continue;
				}else if(msg.startsWith("summon monster"))
				{
					System.out.println("Summon monster start...");
					player2.SummonMonster(Integer.parseInt(msg.substring(lenSummon).trim()));
                	continue;
				}else if(msg.startsWith("choose my card"))
				{
					if(player2.isNotOk())
                	{
                		num=Integer.parseInt(msg.substring(lenChoose).trim());//自己手上的第几个怪兽
                		monsterCard=player2.chooseMyMonster(num);	
                		msg = dis.readUTF().trim();
                        if(msg.startsWith("attack"))
                        {
                        	int opNum=Integer.parseInt(msg.substring(lenAttack).trim());
                        	MonsterCard opMonsterCard=player1.chooseMyMonster(opNum);
                        	int attackPower=monsterCard.getAttackPower();
                        	int defencePower=opMonsterCard.getDefencePower();
                        	if(attackPower>defencePower)
                        	{
                        		player1.changeBlood(attackPower-defencePower);
                        		player1.killMonster(opNum);
                        	}else if(attackPower<defencePower)
                        	{
                        		player2.killMonster(num);
                        	}else {
                        		player2.killMonster(opNum);
                        		player1.killMonster(num);
							}
                        	if(player1.beDefeated())
                        	{
                        		System.out.println("You have been defeated!");
                        		dos.writeUTF("Congratulations!You are the winner.");
                        	}else if(player2.beDefeated())
                        	{
                        		System.out.println("Congratulations!You are the winner.");
                        		dos.writeUTF("You have been defeated!");
                        	}
                        }
                        
                	}
					continue;
				}else if(msg.equals("show my blood")){
					String str ="the current blood is:"+player2.getBlood();
					dos.writeUTF(str);
				}
				else if(msg.equals("bye")){  
                    System.out.println("对方下线,程序退出");  
                    System.exit(0);  
                }else {
                	System.out.println("Client:" + msg);  
				}
                
                
            }  
        }catch(IOException e){  
            System.out.println(e);  
        }  
    }  
}  


MyServerWriter

//建立一个线程,根据自己发出的的命令来对自己或对方玩家的怪兽卡牌进行操作

package game;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

//创建一个进程用来写入并发送数据  
public class MyServerWriter extends ServerTest3 implements Runnable{ 
    private DataOutputStream dos;  
    public MyServerWriter(DataOutputStream dos){  
        this.dos = dos;  
    }  
    public void run(){  
        InputStreamReader isr = new InputStreamReader(System.in);  
        BufferedReader br = new BufferedReader(isr);  
        String msg;  
        String str=null;
        int len=0;
        int lenSummon="Summon monster".length();
        int lenChoose="choose my card".length();
        int lenAttack="attack".length();
        MonsterCard monsterCard=null;
        int num=0;
        try{  
            while(true){ 
            	str=null;
            	msg=null;
            	monsterCard=null;
                msg = br.readLine();
                str=msg.trim();
                len=str.length();
                if(str.equals("show my hand"))
                {
                	str=player1.showMyHand();
                	System.out.println(str);
                	continue;
                }
                else if(str.equals("show my bf"))
                {
                	str=player1.showMyBf();
                	System.out.println(str);
                	continue;
                }
                else if(str.equals("show op bf"))
                {
                	str=player2.showMyBf();
                	System.out.println(str);
                	continue;
                }
                else if(str.equals("end the term"))
                {
                	player2.changeTerm();//回合结束,修改自己的回合数
                	System.out.println("wait...");
                	player2.getCard();//启动另一个回合
                	dos.writeUTF("Term "+player2.getTerm()+":");
                	continue;
                }
                else if(str.startsWith("summon monster"))
                {
                	System.out.println("Summon monster start...");
                	player1.SummonMonster(Integer.parseInt(str.substring(lenSummon).trim()));
                	continue;
                }	
                else if(str.startsWith("choose my card"))
                {
                	if(player1.isNotOk())
                	{
                		num=Integer.parseInt(str.substring(lenChoose).trim());//自己手上的第几个怪兽
                		monsterCard=player1.chooseMyMonster(num);	
                		msg = br.readLine();
                		str=msg.trim();
                        len=str.length();
                        if(str.startsWith("attack"))
                        {
                        	int opNum=Integer.parseInt(str.substring(lenAttack).trim());
                        	MonsterCard opMonsterCard=player2.chooseMyMonster(opNum);
                        	int attackPower=monsterCard.getAttackPower();
                        	int defencePower=opMonsterCard.getDefencePower();
                        	if(attackPower>defencePower)
                        	{
                        		player2.changeBlood(attackPower-defencePower);
                        		player2.killMonster(opNum);
                        	}else if(attackPower<defencePower)
                        	{
                        		player1.killMonster(num);
                        	}else {
                        		player2.killMonster(opNum);
                        		player1.killMonster(num);
							}
                        	if(player1.beDefeated())
                        	{
                        		System.out.println("You have been defeated!");
                        		dos.writeUTF("Congratulations!You are the winner.");
                        	}else if(player2.beDefeated())
                        	{
                        		System.out.println("Congratulations!You are the winner.");
                        		dos.writeUTF("You have been defeated!");
                        	}
                        	
                        }
                        continue;
                	}
                		
                }else if(msg.equals("show my blood")){
					System.out.println("the current blood is:"+player1.getBlood());
					continue;
				}
                  
                else if(msg.equals("bye")){  
                    System.out.println("自己下线,程序退出");  
                    System.exit(0);  
                }else {
                	dos.writeUTF("Server:"+msg);
				} 
            }  
            }catch(IOException e){  
            	e.printStackTrace();
        }  
    }  
} 

ServerTest

//负责和客户端进行通信,共享玩家的数据。

package game;

import java.io.*;  
import java.net.*;  


public class ServerTest3{ 
	protected  static Player player1=new Player();//创建玩家<span id="_xhe_cursor"></span>1,子类共享基类的变量
	protected  static Player player2=new Player();//创建玩家2
	ServerTest3 server=null;
	private  MonsterCard monsterOp=null;
	public  MonsterCard getMonsterCard(){
		return monsterOp;
	}
	public void  SetMonsterCard(MonsterCard monster)
	{
		this.monsterOp=monster;
	}
	public static void main(String[] args){ 
		ServerTest3 server =new ServerTest3();//创建连接实例
		server.connectToClient();//通信函数
    }
	public void connectToClient()
	{
		DataOutputStream serverDos =null;
		DataOutputStream serverDos1 =null;
		DataInputStream serverDis =null;
		try{  
            //设置sever端的链接  
            ServerSocket s = new ServerSocket(10004); 
            Socket s1 =null;
            try {
            	s1 = s.accept();//sever等待链接  
                System.out.println("Link in succeed...");
                System.out.println("Term 1:");
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
            //实例化输出流  
            OutputStream os = s1.getOutputStream();  
            serverDos= new DataOutputStream(os);  
            OutputStream os1 = s1.getOutputStream();  
            serverDos1= new DataOutputStream(os1); 
            //实例化输入流  
            InputStream is = s1.getInputStream();  
            serverDis= new DataInputStream(is);  
            //实例化两个线程的对象  
            MyServerReader msr = new MyServerReader(serverDis,serverDos1);  
            MyServerWriter msw = new MyServerWriter(serverDos);  
            //启动线程  
            new Thread(msr).start();
            new Thread(msw).start();
        }  
        //捕获异常  
        catch(SocketException e){  
            System.out.println(e);  
        }catch(IOException e){  
            System.out.println(e);  
        }
	}  
}  
 

Monster Card Game的设计与实现之服务器篇

标签:java   服务器   线程   通信   游戏   

原文地址:http://blog.csdn.net/mnmlist/article/details/41828745

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!