Я пишу код для игры Yahtzee, класс, над которым я работаю, принимает определенное количество кубиков с заданными значениями, которое определяется в конструкторе. Существуют два массива, которые также используются в этом классе, Available [] и Fixed []. Все кости начинаются в массиве Available [], а массив Fixed [] имеет ту же длину, что и массив Available [], но имеет 0 для всех его значений, поскольку любое значение, которое меньше 1, не используется для другого подсчета очков методы.Добавление значений из одного массива в другой
Существует один метод, называемый keep(), который дает вам значение, и это значение должно быть перемещено из массива Available [] в массив Fixed []. Если значение, заданное keep, не находится в доступном массиве [], оно игнорируется.
Я знаю, что вы не можете удалить значения из массивов, но я знаю, что вы можете их изменить. Я написал тестовый пример, который вызывает метод keep() для сохранения значений 3 и 5, оба из которых можно найти в доступном массиве из [3, 3, 3, 5, 6]. Проблема в том, что когда я вызываю метод, он возвращает новый доступный массив из [3, 3, 5, 0, 0] и фиксированный массив из [0, 0, 0, 0, 0]. Вместо этого я хочу, чтобы доступный массив был [3, 3, 6, 0, 0], а фиксированный массив - [3, 5, 0, 0, 0]. Вот код, который у меня есть для метода keep.
public void keep(int value)
{
if(rolls < rollsMax)
{
for(int i = 0; i < Available.length - 1; i++)
{
if(Available[i] == value)
{
Fixed[i] = Available[i];
Available[i] = Available[i + 1];
Available[Available.length - 1] = 0;
}
}
}
}
В частности, я не понимаю, почему
Fixed[i] = Available[i]
не добавляет значение для фиксированного массива. Любая помощь будет оценена по достоинству.
Вот весь код:
package hw3;
import java.util.Random;
/**
* This class represents values of a group of dice for a dice game such as Yahtzee in which
* multiple rolls per turn are allowed. The number of faces on the dice,
* the number of dice in the Hand, and the maximum number of rolls are configurable
* via the constructor. At any time some of the dice may be <em>available</em>
* to be rolled, and the other dice are <em>fixed</em>. Calls to the
* <code>roll()</code> method will select new, random values for the available
* dice only. After the maximum number of rolls, all dice are automatically
* fixed; before that, the client can select which dice to "keep" (change from
* available to fixed) and which dice to "free" (change from fixed to
* available).
* <p>
* Note that valid die values range from 1 through the given
* <code>maxValue</code>.
*/
public class Hand
{
private int[] fixed;
private int[] available;
private int[] values;
private int groupDice;
private int valueMax;
private int rollsMax;
private int rolls;
/**
* Constructs a new Hand in which each die initially has
* the (invalid) value zero.
* @param numDice
* number of dice in this group
* @param maxValue
* largest possible die value, where values range from 1
* through <code>maxValue</code>
* @param maxRolls
* maximum number of total rolls
*/
public Hand(int numDice, int maxValue, int maxRolls)
{
groupDice = numDice;
valueMax = maxValue;
rollsMax = maxRolls;
available = values;
}
/**
* Constructs a new Hand in which each die initially has
* the value given by the <code>initialValues</code> array.
* If the length of the array is greater than the number of dice, the
* extra values are ignored. If the length of the array is smaller
* than the number of dice, remaining dice
* will be initialized to the (invalid) value 0.
* <p>
* This version of the constructor is primarily intended for testing.
* @param numDice
* number of dice in this group
* @param maxValue
* largest possible die value, where values range from 1
* through <code>maxValue</code>
* @param maxRolls
* maximum number of total rolls
* @param initialValues
* initial values for the dice
*/
public Hand(int numDice, int maxValue, int maxRolls, int[] initialValues)
{
groupDice = numDice;
values = new int[numDice];
valueMax = maxValue;
rollsMax = maxRolls;
available = values;
for(int i = 0; i < numDice; i++)
{
if(i >= initialValues.length)
{
values[i] = 0;
}
else
{
values[i] = initialValues[i];
}
}
}
/**
* Returns the number of dice in this group.
* @return
* number of dice in this group
*/
public int getNumDice()
{
return groupDice;
}
/**
* Returns the maximum die value in this group.
* Valid values start at 1.
* @return
* maximum die value
*/
public int getMaxValue()
{
return valueMax;
}
/**
* Rolls all available dice; that is, each available
* die value in this group is replaced by a randomly generated
* value produced by the given random number generator.
* @param rand
* random number generator to be used for rolling dice
*/
public void roll(Random rand)
{
rand = new Random();
int values = rand.nextInt(valueMax) + 1;
}
/**
* Selects a die value to be moved from the available dice to the
* fixed dice. Has no effect if the given value is
* not among the values in the available dice. Has no effect if
* the number of rolls has reached the maximum.
* @param value
* die value to be moved from available to fixed
*/
public void keep(int value)
{
if(rolls < rollsMax)
{
for(int i = 0; i < available.length; i++)
{
if(available[i] == value)
{
fixed[i] += available[i];
available[i] = available[i + 1];
available[available.length - 1] = 0;
}
}
}
}
/**
* Selects a die value to be moved from the fixed dice to
* the available dice, so it will be re-rolled in the
* next call to <code>roll()</code>. Has no effect if the given value is
* not among the values in the fixed dice. Has no effect if
* the number of rolls has reached the maximum.
* @param value
* die value to be moved
*/
public void free(int value)
{
if(rolls < rollsMax)
{
}
}
/**
* Causes all die values be moved from the available dice to the
* fixed dice. Has no effect if
* the number of rolls has reached the maximum.
*/
public void keepAll()
{
if(rolls < rollsMax)
{
for(int i = 0; i < available.length; i++)
{
fixed[i] = available[i];
}
available[available.length - 1] = 0;
}
}
/**
* Causes all die values be moved from the fixed dice to the
* available dice. Has no effect if
* the number of rolls has reached the maximum.
*/
public void freeAll()
{
if(rolls < rollsMax)
{
for(int i = 0; i < available.length; i++)
{
available[i] = fixed[i];
}
fixed[fixed.length - 1] = 0;
}
}
/**
* Determines whether there are any dice available to be
* rolled in this group.
* @return
* true if there are no available dice, false otherwise
*/
public boolean isComplete()
{
for(int i = 0; i < available.length; i++)
{
if(available[i] > 0)
{
return false;
}
}
return true;
}
/**
* Returns the values of the dice that are currently fixed (not
* available to be rerolled) in ascending order.
* @return
* values of the dice that are currently fixed
*/
public int[] getFixedDice()
{
fixed = new int[groupDice];
return fixed;
}
/**
* Returns the values of the dice that are currently available to
* be rerolled by a subsequent call to <code>roll()</code>,
* in ascending order.
* @return
* dice that are available to be rerolled
*/
public int[] getAvailableDice()
{
return available;
}
/**
* Returns all die values in this group, in ascending order.
* @return
* all die values in this group
*/
public int[] getAll()
{
for(int i = 0; i < values.length; i++)
{
for(int j = i + 1; j < values.length; j++)
{
int temp = 0;
if(values[i] > values[j])
{
temp = values[i];
values[i] = values[j];
values[j] = temp;
}
}
}
return values;
}
Почему 'eclipse' тег? –
Это был несчастный случай, я изменил его – Zebs
'Исправлено [i] = Доступно [i]' перезаписывает значение Fixed массива со значением доступного массива. Вы хотите '+ ='? –