【发布时间】: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,只是在我的代码开头使用一个类。我不知道如何使用一个类来实现我所需要的。另外,我将如何在问题之外更新分数?