首页 > 编程 > Java > 正文

java实现纸牌游戏之小猫钓鱼算法

2019-11-26 09:20:18
字体:
来源:转载
供稿:网友

星期天小哼和小哈约在一起玩桌游,他们正在玩一个非常古怪的扑克游戏――“小猫钓鱼”。游戏的规则是这样的:将一副扑克牌平均分成两份,每人拿一份。小哼先拿出手中的第一张扑克牌放在桌上,然后小哈也拿出手中的第一张扑克牌,并放在小哼刚打出的扑克牌的上面,就像这样两人交替出牌。出牌时,如果某人打出的牌与桌上某张牌的牌面相同,即可将两张相同的牌及其中间所夹的牌全部取走,并依次放到自己手中牌的末尾。当任意一人手中的牌全部出完时,游戏结束,对手获胜。

假如游戏开始时,小哼手中有 6 张牌,顺序为 2 4 1 2 5 6,小哈手中也有 6 张牌,顺序为 3 1 3 5 6 4,最终谁会获胜呢?现在你可以拿出纸牌来试一试。接下来请你写一个程序来自动判断谁将获胜。这里我们做一个约定,小哼和小哈手中牌的牌面只有 1~9。 

输入

2 4 1 2 5 6
3 1 3 5 6 4

输出

小哼win
小哼当前手中的牌是 5 6 2 3 1 4 6 5 桌上的牌是 2 1 3 4

这道题目完全考察栈跟队列的应用,桌面上的牌是栈,个人手中的牌是队列。

附上JAVA实现的源码:

import java.util.LinkedList;import java.util.Scanner;import java.util.Stack; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); LinkedList<Integer> a = new LinkedList<Integer>();//A手中的牌 LinkedList<Integer> b = new LinkedList<Integer>();//B手中的牌 Stack<Integer> stack = new Stack<>();//记录桌面上的牌 int[] book = new int[10];//用来标记哪些牌已经在桌上 int n,t,s; for(int i = 0; i < 10; i++){  book[i] = 0; } System.out.println("输入手中牌的个数"); n = scanner.nextInt(); System.out.println("输入A君手中牌的大小"); for(int i = 1; i<=n; i++){  a.addLast(scanner.nextInt()); } System.out.println("输入B君手中牌的大小"); for(int i = 1; i<=n; i++){  b.addLast(scanner.nextInt()); } System.out.println("输入完毕开始游戏"); while (!a.isEmpty() && !b.isEmpty()) {//当有人手中没牌游戏结束  t = a.removeFirst();  if (book[t] == 0) {//A没有赢  stack.push(t);//桌面上加一张牌  book[t] = 1;//记录桌面上已经有这张牌了  }else {//A赢了  a.addLast(t);//将打出的牌到到末尾  while (!stack.peek().equals(t)) {//将桌面上的牌按顺序放到A的末尾   s = stack.pop();   a.addLast(s);   book[s] = 0;  }  }    //同上B取出牌  t = b.removeFirst();  if (book[t] == 0) {  stack.push(t);  book[t] = 1;  } else {  b.addLast(t);  while (!stack.peek().equals(t)) {   s = stack.pop();   b.addLast(s);   book[s]= 0;  }  } }  if (!a.isEmpty()) {//A胜利  System.out.println("A君胜利!A手中的牌是");  while (!a.isEmpty()) {  System.out.print(a.removeFirst()+ " ");  }  System.out.println();  if (!stack.isEmpty()) {//桌面上有牌  System.out.println("桌面上的牌是");  for (Integer x : stack) {    System.out.print(x + " ");         }   } else {  System.out.println("桌面没有牌了");  } } else {//B胜利  System.out.println("B君胜利!B手中的牌是");  while (!b.isEmpty()) {  System.out.print(b.removeFirst()+ " ");  }  System.out.println();  if (!stack.isEmpty()) {//桌面上有牌  System.out.println("桌面上的牌是");  for (Integer x : stack) {    System.out.print(x + " ");         }   } else {  System.out.println("桌面没有牌了");  } } return;//结束 }}

结果:

输入手中牌的个数
6
输入A君手中牌的大小
2 4 1 2 5 6
输入B君手中牌的大小
3 1 3 5 6 4
输入完毕开始游戏
A君胜利!A手中的牌是
5 6 2 3 1 4 6 5
桌面上的牌是
2 1 3 4

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表