欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java集合实现斗地主洗牌、发牌、看牌操作

程序员文章站 2022-07-12 09:09:03
...

源码如下:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Scanner;

class Poker{
	private List<String> poker;
	public Poker() {
		Character[] colors = new Character[] {'♥','♠','♦','♣'};
		Character[] number = new Character[] {'1','2','3','4','5','6','7','8','9','⑩','J','Q','K'};
		this.poker = new ArrayList<String>();
		for(Character c : colors) {
			for(Character n : number) {
				poker.add("" + c + n);
			}
		}
		poker.add("大王");
		poker.add("小王");
		
	}
	public void shufflePoker() {
		System.out.println("*******正在洗牌*******");
		Collections.shuffle(this.poker);
	}
	public List<String> getPoker(){
		return this.poker;
	}
}
class Player{
	private String name;
	private List<String> pokerList = new ArrayList<String>();
	public Player(String name) {
		this.name = name;
	}
	public String getName() {
		return this.name;
	}
	public List<String> getList(){
		return this.pokerList;
	}
}
class Desk{
	private Poker poker;
	private Player playerA;
	private Player playerB;
	private Player playerC;
	public Desk(String nameA,String nameB,String nameC) {
		this.playerA = new Player(nameA);
		this.playerB = new Player(nameB);
		this.playerC = new Player(nameC);
		this.poker = new Poker();
	}
	public void startGame() {
		this.playerA.getList().clear();
		this.playerB.getList().clear();
		this.playerC.getList().clear();
		System.out.println("*******游戏开始*******");
		this.poker.shufflePoker();
		for(int i = 1 ; i < 52 ; i ++) {
			if(i % 3 == 0) {
				this.playerA.getList().add(poker.getPoker().get(i-1));
			}else if(i % 2 == 0) {
				this.playerB.getList().add(poker.getPoker().get(i-1));
			}else {
				this.playerC.getList().add(poker.getPoker().get(i-1));
			}
		}
	}
	public void putPoker() {
		System.out.println("*******正在发牌*******");
		System.out.println(playerA.getName() + ":" + playerA.getList());
		System.out.println(playerB.getName() + ":" + playerB.getList());
		System.out.println(playerC.getName() + ":" + playerC.getList());
		System.out.println("底牌是:" + poker.getPoker().get(51) + "、" 
				+ poker.getPoker().get(52) + "、"
				+ poker.getPoker().get(53) );
	}
}

public class Demo1{
	public static void main(String[] args) {
		Desk desk = new Desk("张三", "李四", "王二麻子");
		Scanner in = new Scanner(System.in);
		while(true) {
			desk.startGame();
			desk.putPoker();
			System.out.println("按1重新洗牌!");
			if(in.nextInt() != 1) {
				break;
			}
		}
		
	}
}

附上程序运行的结果:

*******游戏开始*******
*******正在洗牌*******
*******正在发牌*******
张三:[♠⑩,3, ♣⑩,2,5,4,9, 小王, ♣Q,2,6, ♠J,3,1,7,9,2]
李四:[大王, ♣K,6,3,5, ♦Q,9,9,7, ♦K, ♥J,5,6, ♦⑩,3, ♥⑩, ♣J]
王二麻子:[1,8,4,8, ♥K, ♠K,8,7,5,7,1,2, ♠Q,8, ♥Q,4,6]
底牌是:♠4、♥1、♦J
按1重新洗牌!