【问题标题】:Using loops and arrays to switch between players in a quiz game在问答游戏中使用循环和数组在玩家之间切换
【发布时间】:2016-03-02 08:52:41
【问题描述】:

我正在编写一个非常简单的问答式棋盘游戏,它可以根据玩家是否正确回答问题以及掷出的骰子来移动棋盘。我正在尝试创建并传递一个存储玩家 1 和玩家 2 分数的数组方法,但该数组似乎并没有真正跟踪分数。例如部分代码片段如下:

public static int[] scorearray 
{
   int scoreplayer1 = 0;
   int scoreplayer2 = 0;
   return new int[] = {scoreplayer1, scoreplayer2};
}

public static int questions(int diceroll, int[] score)
{
   String textinput = input("What's 9+10?");
   int ans = Integer.parseInt(textinput);
      if (ans == 19)
      {
         output("Fantastic answer, that's correct!");
         diceroll = dicethrow(diceroll); // rolls the dice
         output("Move forward " + diceroll + " squares. You are on square " + score[0]); 
         //I need the output above to print position 0 in the above array
         score[0] = score[0] + diceroll; //array stores the cumulative score
      }
      else
      {
         output("Sorry, the answer was 19. Next player's turn.")
         //This is where I need the loop to switch between players
      }

另外,我需要想出一种在玩家1和2之间切换的方法,同时也切换到上面数组中的位置1,即我需要添加到玩家2的分数而不是玩家1的分数。我多年来一直在梳理这段代码,现在试图弄清楚如何做到这一点,但我只能想出使用 for/while 循环的想法。除此之外,我真的很难过。

谢谢。

编辑:看来我的数组在questions 方法中使用时显然仍然不存储分数。

我现在也意识到我可以通过创建另一种方法来控制轮到谁,例如public static void activePlayer(),但我仍然不确定如何使用循环(或其他任何方法)在两者之间切换.另外我担心的是我在questions 方法中使用score[0] = score[0] + diceroll; 的位置只保留玩家一的分数(或至少尝试;见上述问题)。我将如何切换它以保持score[1] 的分数?请。

【问题讨论】:

  • java 是按值传递的,因此当您在问题方法中更新分数时,它不会更改该函数之外的分数
  • 您尚未共享所有代码,但您可能希望为此使用类而不是静态方法
  • @pwilmot 我很乐意分享更多信息,但我正在处理大约 500 行非常混乱的代码,所以我尽量提供最好的部分。此外,我只被教导在我的方法中使用public static xxx,只是在我的代码开头使用一个类。我不知道如何使用一个类来实现我所需要的。另外,我将如何在问题之外更新分数?

标签: java arrays loops methods


【解决方案1】:

您的选项似乎是让您的问题函数输出分数或将您的分数对象更改为静态对象而不是静态函数。

public static int[] scorearray = [0,0];

public static int[] questions(int diceroll, int[] score)  

【讨论】:

  • 尝试创建另一个静态字段,即 activePlayer
  • 如何在播放器 1 和播放器 2 之间切换?此外,在我的public static int questions(int diceroll, int[] score) 方法中,我使用score[0]++; 来跟踪分数。当它切换到播放器 2 时,我需要它来代替 score[1]++;,但是如果不编写两次相同的方法(大约 200 行代码:/),我怎么能做到这一点?
  • 诚然,我告诉过您我理解您所写的内容并说它有效。在我看来,直到我输入一些代码来打印出分数数组并意识到它仍在打印出0。您能否概述一下您的答案的含义,这将对我有很大帮助! @pwilmot
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-15
  • 1970-01-01
相关资源
最近更新 更多