【问题标题】:UNO game in java early stages issueJava早期阶段的UNO游戏问题
【发布时间】:2019-11-10 23:57:32
【问题描述】:

作为我本周作业的一部分(计算机编程 I),我应该研究我们在整个课堂上都在研究的 UNO 游戏。游戏将仅在计算机之间进行,因此除了偶尔输入以使游戏继续外,没有键盘输入(有点无聊吧?)。本周我们应该为游戏的每个部分制作一些类(例如 CARD 类和 HAND 类)。我能够做到这一点,但我的任务的第二部分 - 有一个驱动程序:“创建一个甲板 UNO 牌,将牌发给两个或更多玩家,并显示每个玩家的内容 玩家的手。”——让我卡住了。我尝试了多种打印方法,但我的技能非常有限,但我什么也没想出来。有什么想法吗?

这是代码:

public class CARD
{
    public String color;
    public int value;
    private Random random;
    private String face;

    public CARD(int v, String c)
    {
        value = v;
        color = c; 
    }

public CARD()
{
    random = new Random();
    value = random.nextInt(28); // 108 cards in a deck and it Can be reduced to 27 which ignores colors
    // Assigns value
    if (value >= 14) // Some cards show up more often (numbers)
        value -= 14;
    // Assigns color
    random = new Random();
    switch(random.nextInt(4) ) //learned about switches here: https://www.youtube.com/watch?v=RVRPmeccFT0
    {
        case 0: color = "Red"; 
            break;
        case 1: color = "Green"; 
            break;
        case 2: color = "Blue"; 
            break;
        case 3: color = "Yellow"; 
            break;
    }
    // If the card is wild 
    if (value >= 13)
        color = "none";
    }
}

【问题讨论】:

  • 不知何故,每个CARD 创建自己的new Random() 似乎有点矫枉过正。
  • 另外请注意,UNO 牌组没有任何随机性。套牌总是包含完全相同的一组卡片。 UNO 游戏的随机性在您洗牌牌时进入(即,当您拿起固定的牌组并以随机选择的顺序排列它们时)。

标签: java output


【解决方案1】:

根据您提供的代码,我建议使用 for 循环来制作卡片:

public class DriverProgram {
    static final int players = 2, numberOfCards = 7;
    public static void main (String[] args){
         java.util.ArrayList<CARD> c = new java.util.ArrayList<CARD>();
         for(int i=0; i<numberOfCards; i++){
             c.add(new CARD()); // The previous example used a fixed size array
         } // Arrays.fill() would make all the cards identical
         System.out.println(c); 
         // Note: ArrayLists print themselves nicely with their toString method.
         // If you'd like, you could do String.replace("[", "").replace... to remove
         // certain characters.
    }
}

How do I print my Java object without getting "SomeType@2f92e0f4"?

【讨论】:

  • 您需要创建卡片才能使用它们。
  • 我应该使用什么样的循环?抱歉,我真的很陌生。
  • 我以为是我的代码制作了卡片,我需要添加什么?
  • 那是一个卡片类。它实际上并没有制作卡片。它只是描述了一张卡片到底是什么。你真的不需要在你的卡片类中添加任何东西,但我会推荐一个 toString 方法覆盖。
  • 您不需要任何循环,因为我已经意识到您可以简单地打印它。此外,您可以使用while(!c.isEmpty()) System.out.println(c.remove(0))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-23
相关资源
最近更新 更多