计算机网络课设 24分游戏

1.问题描述:

24点游戏是一种使用扑克牌来进行的益智类游戏。游戏内容是从一副扑克牌中抽去大小王剩下52张,任意抽取4张牌,把牌面上的数运用加、减、乘、除和括号等进行运算得出24。每张牌都必须使用一次,但不能重复使用,在本设计题目中,可以只选取在1-9这九张牌中随机取牌,降低软件开发的难度。
功能:游戏后台运行一个服务器软件,游戏者通过客户端程序登陆后,服务器随机产生四个 1-9 之间的随机数供游戏者使用,游戏者根据计算得出结果。若计算出结果,且在规定的时间内,则从客户端输入表达式,服务器端根据客户端的表达式计算,若正确,软件提示:“对了”,如果错了,软件提示“错了”,若超时,软件提示 “超时”。服务器同时记录并维护一个游戏玩家的 TOP10 排行榜,供玩家查询。
描述:服务器端:接收客户端的命令请求并提供相应的服务。 客户端:完成游戏人机界面的设计,以命令的方式向服务器请求服务,并显示相应的提示

2.项目设计

在这里插入图片描述

课程设计报告下载点我

3.开发环境:

Netbeans

4.实现代码:

服务器端:

main.java

package pkg24服务器;

import java.io.*;
import java.net.*;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 *
 * @author ZZH
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void game(OutputStreamWriter socketOut,BufferedReader socketReader){
        try {
                    int a,b,c,d;
                    List<String> answerStris;
                    do{        
                    a=1+(int)(Math.random()*9);
                    b=1+(int)(Math.random()*9);
                    c=1+(int)(Math.random()*9);
                    d=1+(int)(Math.random()*9);
                    System.out.println(a+"\n"+b+"\n"+c+"\n"+d);
                    answerStris=Count24.easyCount(new int[]{a,b,c,d});
                    }while(answerStris.isEmpty());
                    for (String string : answerStris) {
                            System.out.println(string);
                        }
                String abcd = a+" "+b+" "+c+" "+d;
                socketOut.write(abcd+"\r\n");
                socketOut.flush();
                //读取客户端的数据
                String line = null;
                int ret = 0;
                while((line = socketReader.readLine())!=null){
                    System.out.println("服务端接收到的数据:"+ line);    
                        for (String string : answerStris) {
                            //System.out.println(string);
                            if(line.equals(string))
                                ret = 1;
                        }
                    if(ret == 1){
                        line = "对了";
                        socketOut.write(line+"\r\n");
                        socketOut.flush();
                        String name = socketReader.readLine();
                        System.out.println(name);
                        String time = socketReader.readLine();
                        System.out.println(time);
                        int time_ = Integer.parseInt(time);
                        System.out.println(time_);
                        Rank.addPlayer(name,time_);
                        //Rank.addPlayer(name,time_);
                        break;
                    }
                    else{
                         if(line.equals("超时"))
                            break;
                        line = "错了";
                        socketOut.write(line+"\r\n");
                        socketOut.flush();
                    }
                }

  
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }  

   public static void main(String[] args) throws IOException {
        // TODO code application logic here
                 //建立tcp的服务端
                ServerSocket serverSocket = new ServerSocket(9090);
                //接受客户端的连接,产生一个SOcket
                Socket socket = serverSocket.accept();  

                //获取到Socket的输入流对象
                BufferedReader socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));  

                //获取到Socket输出流对象
                OutputStreamWriter socketOut =  new OutputStreamWriter(socket.getOutputStream());  

                //获取键盘的输入流对象
                //BufferedReader keyReader = new BufferedReader(new InputStreamReader(System.in));
                //获取到Socket的输出流(字符串数组)
                ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); 
                String input = null;
        do{
                input = socketReader.readLine();
                if(input.equals("1")){
                    game(socketOut,socketReader);
                }
                if(input.equals("2")){
                    top10(out);
                }   
        }while(!(input.equals("0")));
        //关闭资源
        serverSocket.close();
}

    private static void top10(ObjectOutputStream out) throws IOException {
        String[] rank = Rank.getList();
        
//        socketOut.write(rank.length);
//        socketOut.flush();
//        for(String string:rank){
//            System.out.println(string);
//            socketOut.write(rank[i]);
//            socketOut.flush();
//        }
         out.writeObject(rank);
    }



}

count24.java

package pkg24服务器;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 *
 * @author ZZH
 */
public class Count24 {
    private List<String> answerList=new ArrayList<String>();
    public List<String> getAnswerList() {
        return answerList;
    }
    public static class Data{
        public float[]  arr;
        public String expStr="";
        public String[] strs;
        public Data(){}
        public Data(int a,int b,int c,int d) {
            arr=new float[]{a,b,c,d};
            strs=new String[]{a+"",b+"",c+"",d+""};
            expStr=a+"";
        }
        public Data(int arr[]) {
            this.arr=new float[]{arr[0],arr[1],arr[2],arr[3]};
            this.strs=new String[]{arr[0]+"",arr[1]+"",arr[2]+"",arr[3]+""};
        }
    }
    public void count(Data data){
        float[] arr=data.arr;
        if(arr.length<=1){
            if(arr.length==1&&arr[0]==24){
                answerList.add(data.expStr.substring(1, data.expStr.length()-1));
            }
            return ;
        }
        for(int i=0,len=arr.length;i<len-1; i++){
            for(int j=i+1;j<len;j++){
                float x=arr[i];
                float y=arr[j];
                String xs=data.strs[i];
                String ys=data.strs[j];
                for(int k=0;k<6;k++){
                    Data newData=getNewArr(data,i);
                    switch(k){
                        case 0:
                        newData.arr[j-1]=x+y;
                            newData.expStr=xs+"+"+ys;
                        break;
                        case 1:
                        newData.arr[j-1]=x-y;
                            newData.expStr=xs+"-"+ys;
                        break;
                        case 2:
                        newData.arr[j-1]=y-x;
                        newData.expStr=ys+"-"+xs;
                        break;
                        case 3:
                        newData.arr[j-1]=x*y;
                            newData.expStr=xs+"*"+ys;
                        break;
                        case 4:
                        if(y!=0){
                            newData.arr[j-1]=x/y;
                                newData.expStr=xs+"/"+ys;
                        }else {
                            continue;
                        }
                        break;
                        case 5:
                        if(x!=0){
                            newData.arr[j-1]=y/x;
                                newData.expStr=ys+"/"+xs;
                        }else {
                            continue;
                        }
                        break;
                    }
                    newData.expStr="("+newData.expStr+")";
                    newData.strs[j-1]=newData.expStr;
                    count(newData);
                }
            }
        }
        
    }
    private static Data getNewArr(Data data, int i) {
        Data newData=new Data();
        newData.expStr=data.expStr;
        newData.arr=new float[data.arr.length-1];
        newData.strs=new String[data.arr.length-1];
        for(int m=0,len=data.arr.length,n=0;m<len;m++){
            if(m!=i){
                newData.arr[n]=data.arr[m];
                newData.strs[n]=data.strs[m];
                n++;
            }
        }
        return newData;
    }
    
    public static final List<String> easyCount(int[] curRandNums){
        Count24 count24=new Count24();
        count24.count(new Data(curRandNums));
        Set<String> set=new HashSet<String>(count24.getAnswerList());//去重
        return new ArrayList<String>(set);
    }
}

top10 rank.java

package pkg24服务器;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;

/**
 *
 * @author ZZH
 */
public class Rank {
 
	public static void addPlayer(String name, int score) {
		try {
			BufferedReader input=new BufferedReader(new FileReader("Rank.dat"));
			int n=Integer.parseInt(input.readLine());
			boolean r=false;
			String[] nameList=new String[n];
			int[] scoreList=new int[n];
			for (int i=0; i<n; i++) {
				nameList[i]=input.readLine();
				scoreList[i]=Integer.parseInt(input.readLine());
				if (nameList[i].equals(name)&&score<scoreList[i]) {
					scoreList[i] = score;
					r=true;
				}
			}
			if (!r) {
				n+=1;
			}
			boolean hasChanged=true;
			while (hasChanged) {
				hasChanged=false;
				for (int i=0; i<nameList.length-1; i++) {
					if (scoreList[i]>scoreList[i+1]) {
						int scoreTmp=scoreList[i];
						scoreList[i]=scoreList[i+1];
						scoreList[i+1]=scoreTmp;
						String nameTmp=nameList[i];
						nameList[i]=nameList[i+1];
						nameList[i+1]=nameTmp;
						hasChanged=true;
					}
				}
			}
			input.close();
			BufferedWriter output=new BufferedWriter(new FileWriter("Rank.dat"));
			output.write(n+"", 0, new String(n+"").length());
			output.newLine();
			for (int i=0; i<n; i++) {
				if (!r && i==n-1) {
					output.write(name, 0, name.length());
					output.newLine();
					output.write(score+"", 0, new String(score+"").length());
					output.newLine();
					break;
				}
				output.write(nameList[i], 0, nameList[i].length());
				output.newLine();
				output.write(scoreList[i]+"", 0, new String(scoreList[i]+"").length());
				output.newLine();
			}
			output.close();
		}
		catch (Exception ex1) {
			try {
				BufferedWriter output=new BufferedWriter(new FileWriter("Rank.dat"));
				output.write('1');
				output.newLine();
				output.write(name, 0, name.length());
				output.newLine();
				output.write(score+"", 0, new String(score+"").length());
				output.newLine();
				output.close();
			}
			catch (Exception ex2) {
			}
		}
	}

	public static String[] getList() {
		try {
			BufferedReader input=new BufferedReader(new FileReader("Rank.dat"));
			int n=Integer.parseInt(input.readLine());
			int count=0;
			String[] list=new String[(n-1)/10+1];
			for (int i=0; i<n; i++) {
				if (list[count]==null) {
					list[count]="";
				}
				list[count]+=input.readLine()+" : "+Integer.parseInt(input.readLine());
				if ((i+1)%10==0) {
					count++;
				} else {
					list[count]+="\n";
				}
			}
			input.close();
			return list;
		}
		catch (Exception ex) {
			return new String[] {"没有记录"};
		}
	}
}
客户端:

main.java

package pkg24客户端;

import java.io.*;
import java.net.*;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ZZH
 */
public class Main {
    private static void menu() {
        System.out.println("***24点游戏*********************************");
        System.out.println("*********** 1.PLAY     *********************");
        System.out.println("*********** 2.TOP      *********************");
        System.out.println("*********** 3.ACCOUNT  *********************");
        System.out.println("*********** 0.EXIT     *********************");

    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException{
        // TODO code application logic here
        Socket socket = new Socket(InetAddress.getLocalHost(),9090);
        //获取socket的输出流对象。
        OutputStreamWriter socketOut =  new OutputStreamWriter(socket.getOutputStream());
        //获取socket的输入流对象
        BufferedReader socketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        //获取键盘的输入流对象,读取数据
        BufferedReader keyReader = new BufferedReader(new InputStreamReader(System.in));
       //获取socket的输入流对象(接受数组)
        ObjectInputStream oi = new ObjectInputStream(socket.getInputStream());
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入你的登录名:");
        String name = sc.next();
        int input = 0;
        do{
            menu();
            input = sc.nextInt();
            socketOut.write(input+"\r\n");
            socketOut.flush();
            switch(input){
                case 1: game(socketOut,socketReader,keyReader,name);break;
                case 2: top10(oi);break;
                case 3:{
                           System.out.println("请输入你的登录名:");
                           name = sc.next();
                    break;
                }
                case 0: System.out.println("退出游戏。。。");break;
                default: System.out.println("输入错误:");break;
            }
            
        }while(input != 0);
        //关闭资源
        socket.close();
    }

    private static void game(OutputStreamWriter socketOut,BufferedReader socketReader, BufferedReader keyReader,String name){
        try {  
            System.out.println("下列给出四个数字,使用+,-,*,/进行计算使最后计算结果为24(eg:请使用两组括号)");
            String abcd = socketReader.readLine();
            System.out.println(abcd);
            String line = null;
           long beginTime=System.currentTimeMillis();

            //System.out.println(beginTime);
            //不断的读取键盘录入的数据,然后把数据写出
            while((line = keyReader.readLine())!=null&&System.currentTimeMillis()-beginTime<=1000*60*1){
                
                socketOut.write(line+"\r\n");
                //刷新
                socketOut.flush();
                //读取服务端回送的数据
                line = socketReader.readLine();
               // System.out.println(line);
                if(line.equals("对了")){
                    long end = System.currentTimeMillis();
                    System.out.println("对了");
                    socketOut.write(name+"\r\n");
                    socketOut.flush();
                    socketOut.write(end - beginTime+"\r\n");
                    socketOut.flush();
                    break;
                }
                if(line.equals("错了")){
                    System.out.println("错了");
                }    
            }
            if(System.currentTimeMillis()-beginTime>1000*60*1)
            {
                System.out.println("超时");
                line = "超时";
                socketOut.write(line+"\r\n");
                socketOut.flush();
            }

        } catch (IOException ex) {  
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }            

    private static void top10( ObjectInputStream oi) throws IOException, ClassNotFoundException{
//        String[] rank = {""};
//        String rank_len = socketReader.readLine();
//        int n = Integer.parseInt(rank_len);
//        for(int i =0; i<2; i++)
//        {
//            rank[i] = socketReader.readLine();
//            System.out.println(rank[i]);
//        }
    String [] arr = (String[]) oi.readObject();
    for(int i =0; i<arr.length; i++){
        System.out.println(arr[i]);
    }
    }
}

5.运行结果:

在这里插入图片描述
在这里插入图片描述

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值