20200804-1, JAVA-String, FileInputStream, FileOutputStream 2, Doudizhu game.

20200804-1, JAVA-String, FileInputStream, FileOutputStream 2, Doudizhu game.

The rules are as follows:

1. There are three players, you can assign player names from the console, the players will have the attributes of the card collection, and whether they are landlords

2. Cards have two attributes: suits and points. There are 4 kinds of suits: black and red plum side (available enumeration) points corresponding to 13 plus two trump cards (available enumeration).

3. Playing card management: used to generate 54 cards in random order (card collection, 54 cards remain unchanged and become sequential), deal with players, randomly generate landlords, and give the remaining 3 cards to Landlord and show the hands of three players. At the same time, save the card information in the file

Claim:

1. Can produce a collection of 54 cards

2. Can generate a random collection of 54 cards or can realize the function of random card distribution

3. Assign the name of the player class and the three player objects

4. Able to randomly generate landlords and assign a set of cards to three players (

5. Realize to save the collection results to a file

Tip: Enumeration classes can have common properties and constructors, and enumeration objects can be constructor objects.

1. Class notes:

String
is a final type and cannot be inherited. The bottom layer is a char type array constant and cannot be changed
. The process of reassigning a String object is actually a process of creating a new object.
If you need to assign values ​​to String objects frequently, it is not recommended to use String
thread safety: synchronized Ensure the isolation between threads.
String: cannot be changed, and is safe in the true sense. In the case of frequent string splicing, the speed is very slow.
StringBuffer: Thread-safe
StringBuilder: Thread-unsafe

Absolute path and relative path: Absolute path generally starts from the root directory, write the full path
Relative path generally starts from the project directory

FileInputStream reads the file process:
1. FileInputStream object and String object declaration
2. Create fileInputStream object (file path and File object)
3. Read single byte or the whole read into byte array
4. Convert to string
5. Close FileInputStream stream
6. Return results

FileOutputStream write file process:
1. File object loading file path
2. Determine whether the parent directory of the file exists, create it if it does not exist
3. Declare FileOutputSteam object
4. Create fileOutputStream object (File object, whether to append)
5. Write the file The string is converted into a bytel array and written to the output stream
6. Close the FileOutputSream stream

2. The landlord game

Player class:

package homework2;

import java.util.ArrayList;

/*
 * @ClassName: Player

 * project name: 20200802-homework
 * @Description:
 */
public class Player {
    
    
    public String name;
    public ArrayList<String> list = new ArrayList();

    public ArrayList<String> getList() {
    
    
        return list;
    }

    public void setList(ArrayList<String> list) {
    
    
        this.list = list;
    }

    public Player() {
    
    
    }
    public Player(String name) {
    
    
        this.name = name;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }



    public String nameOfDiZhu(int i){
    
    
        String j = String.valueOf(i);
        return "player"+j+".txt";
    }
}

cards class:

package homework2;

import java.io.*;
import java.util.*;

/**
 * @ClassName: Cards
 * Date: 2020/8/2 21:44
 * project name: 20200802-homework
 * @Description:
 */
public class Cards {
    
    
//    ArrayList<String> players = new ArrayList();

    Player[] player = new Player[3];      //创建一个包含三个玩家的player对象

    public void xiCard(){
    
    
        Scanner input = new Scanner(System.in);
        for (int i = 0; i < player.length; i++) {
    
    
            System.out.println("请输入第"+(i+1)+"位玩家的姓名:");
            player[i] = new Player(input.next());//以此循环输入每一轮三位玩家的姓名
            writeFile("玩家姓名:"+player[i].name+"\n", "D:/myDoc/"+player[i].nameOfDiZhu(i+1), true);
            //再将玩家的姓名存入文件夹中
        }
        List<String> Card = new ArrayList();   //将54张牌存入Card集合中
        String[] card = {
    
    "A","2","3","4","5","6","7","8","9","10","J","Q","K"};
        String[] color = {
    
    "♠","♥","♣","♦"};
        for (String cards : card){
    
           //双重循环实现数字与花色的字符串叠加
            for (String colors : color){
    
    
                Card.add(colors + cards);
            }
        }
        Card.add("小王"); //最后单独加入两张大小王
        Card.add("大王");
        Collections.shuffle(Card); //洗牌

        for (int i = 0; i<Card.size()-3;i=i+3){
    
       //依此给3位玩家发牌
            player[0].getList().add(Card.get(i));
            player[1].getList().add(Card.get(i+1));
            player[2].getList().add(Card.get(i+2));
        }
        System.out.println("随机产生地主!");

        int diZhu;
        diZhu = (int)(Math.random()*3);  //随机数,随机产生地主的编号
        System.out.println("恭喜"+player[diZhu].name+"成为地主!获得三张底牌!");
        writeFile("此轮是地主\n", "D:/myDoc/"+player[diZhu].nameOfDiZhu(diZhu+1), true);
        //将地主信息存入文件夹中
        for (int i = 51; i <54 ; i++) {
    
    //再给产生的地主发放最后的三张底牌
            player[diZhu ].getList().add(Card.get(i));
        }

        for (int i = 0; i <3 ; i++) {
    
    //将三位玩家的牌存入文件夹中
            for (Object j:player[i].getList()) {
    
    
            writeFile(j+" ", "D:/myDoc/"+player[i].nameOfDiZhu(i+1), true);
            } /*以-----------作为分割线,切分每一轮比赛,将每一轮比赛发放的牌存入数组中的一个元素,这样,指定都一轮比赛,即选定数组的下标,
                    以此来输入某一轮比赛玩家的手牌。其中文件夹的路径使用了字符串拼接,因为不同的玩家信息存入不同的文件夹,文件夹的名称不相同。
                    (在player中定义了文件夹名称的方法)
                */
            writeFile("\n--------------------\n", "D:/myDoc/"+player[i].nameOfDiZhu(i+1), true);
        }


            int i =0;
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入您想展示第几次手牌?");
            i = sc.nextInt();
            System.out.println(readByOne("D:/myDoc/player1.txt",i));
            System.out.println(readByOne("D:/myDoc/player2.txt",i));
            System.out.println(readByOne("D:/myDoc/player3.txt",i));
            }




    public static void writeFile(String str,String path,boolean isAppend){
    
    
        File f = new File(path);
        if (!f.getParentFile().exists())   {
    
    
            f.getParentFile().mkdir();
        }
        FileOutputStream fos = null;

        try {
    
    
            fos = new FileOutputStream(f,isAppend);
            byte[] b=str.getBytes();
            fos.write(b);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }finally {
    
    
            try {
    
    
                fos.close();
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
    }

    public  String readByOne(String path, int i) {
    
    
        FileInputStream fis = null;
        String str = null;
        String print = null;
        String[] printword =new String[100];
        try {
    
    
            fis = new FileInputStream(path);
            StringBuffer sb = new StringBuffer();
            byte[] b = new byte[fis.available()];  //创建byte类型数据流数组
            fis.read( b);     //是读取文件里的字符串,然后给byte类型的数组b赋值,读取文件里的字符串放入b数组缓冲区内。
            str = new String(b);
            printword = str.split("\n--------------------\n");
        } catch (FileNotFoundException e) {
    
    
            e.printStackTrace();
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            try {
    
    
                fis.close();
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
        return  printword[i-1];
    }


    }



Test category:

package homework2;

/**
 * @ClassName: TestCards
 * Date: 2020/8/2 21:44
 * project name: 20200802-homework
 * @Description:
 */
public class TestCards {
    
    
    public static void main(String[] args) {
    
    
        Cards cards = new Cards();
        cards.xiCard();
    }

}

result:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_42005540/article/details/107780591