慕课网-简易扑克牌游戏 思路清晰 简易版

Obelia ·
更新时间:2024-11-13
· 959 次阅读

游戏流程 创建一副全新的扑克牌; 加入两名玩家; 两位玩家各自随机抽取一张扑克牌; 比较点数大小,分出胜负。 对象 卡牌类 import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class Cards { private final String[] suit = {"黑桃", "红桃", "方块", "梅花"}; private final String[] points = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"}; private String[][] cards; //便于后续排序 private Map compare; //构造函数 public Cards() { cards = new String[suit.length][points.length]; compare=new HashMap(); for(int i=0;i<points.length;i++){ compare.put(points[i],i); } } //创建扑克牌 public void CreatCards() { for (int i = 0; i < suit.length; i++) { for (int j = 0; j < points.length; j++) { cards[i][j] = suit[i] + points[j]; } } } //得到扑克牌 public String[][] getCards(){ return this.cards; } public Map getMap(){ return this.compare; } //打印扑克牌 public void printCards() { for (String[] each : cards) { System.out.println(Arrays.toString(each)); } } }

2.玩家类

public class Players { private final int cardsNumber=1; private String name; private String card; //构造函数 public Players(String name){ this.name=name; } //得到名字 public String getName(){ return this.name; } 得到卡牌 public String getCard(){ return this.card; } } 游戏 import java.util.Map; import java.util.Scanner; public class TestCards { public static void main(String[] args) { //新的扑克牌 System.out.println("---创建扑克牌---"); Cards aCards = new Cards(); aCards.CreatCards(); aCards.printCards(); String[][] cards = aCards.getCards(); //客户1 Scanner in = new Scanner(System.in); System.out.print("请输入第一位玩家姓名:"); String name1 = in.nextLine(); Players player1 = new Players(name1); //客户2 System.out.print("请输入第二位玩家姓名:"); String name2 = in.nextLine(); Players player2 = new Players(name2); //发牌 System.out.println("---随机抽牌---"); //玩家1的牌 System.out.print(player1.getName() + "的牌:"); String card1 = cards[(int) (Math.random() * (cards.length - 1))][(int) (Math.random() * (cards[0].length - 1))]; System.out.println(card1); //玩家2的牌 System.out.print(player1.getName() + "的牌:"); String card2 = cards[(int) (Math.random() * (cards.length - 1))][(int) (Math.random() * (cards[0].length - 1))]; while(card2.equals(card1)) card2 = cards[(int) (Math.random() * (cards.length - 1))][(int) (Math.random() * (cards[0].length - 1))]; System.out.println(card2); //比较大小 System.out.println("---一决胜负---"); Map map=aCards.getMap(); int condition=map.get(card1.substring(2,3)).compareTo(map.get(card2.substring(2,3))); switch(condition){ case 1: System.out.println(player1.getName()+"胜利!"); break; case 0: System.out.println(player1.getName()+"和"+player2.getName()+"打平"); break; case -1: System.out.println(player2.getName()+"胜利!"); break; } } } 精简(不足)之处 用随机抽牌代替洗牌过程; 每人只抽了一张牌; 输入姓名缺少了异常捕捉; 比较大小没有利用Comparable等接口。

如有建议,欢迎评论区交流~



扑克牌 慕课网

需要 登录 后方可回复, 如果你还没有账号请 注册新账号