Как добавить БОДМАС в математическую игру Unity 2dC#

Место общения программистов C#
Ответить
Anonymous
 Как добавить БОДМАС в математическую игру Unity 2d

Сообщение Anonymous »

Ребята, я делаю игру в Unity 2d, которая генерирует математические вопросы и проверяет ответ, данный пользователем, но она не соответствует методу решения BODMAS.

Код: Выделить всё

public void GenerateNewQuestion()
{
if (!infinitChance)
{
timerScript.RunScript();
}
// Randomly choose how many operands (at least 2, up to maxDigits)
int numOperands = Random.Range(2, maxDigits + 1);

int intResult = Random.Range(1, 10);  // Generate the first random number
string question = intResult.ToString(); // Initialize the question string with the first number

float floatResult = intResult; // Use floatResult to store the floating-point result

for (int i = 1; i < numOperands; i++)
{
string randomOperator = operators[Random.Range(0, operators.Length)];  // Choose a random operator
int nextNumber = Random.Range(1, 10);  // Generate the next random number

// Use switch statement to apply the chosen operator to the result
switch (randomOperator)
{
case "+":
floatResult += nextNumber;
break;
case "-":
floatResult -= nextNumber;
break;
case "*":
floatResult *= nextNumber;
break;
case "/":
// Avoid division by zero and ensure the result remains a float
nextNumber = Mathf.Max(1, nextNumber);
floatResult /= nextNumber;
break;
}

// Append the next part of the equation to the question string
question += " " + randomOperator + " " + nextNumber.ToString();
}

correctAnswer = floatResult; // Store the correct result for checking

questionText.text = question + " = "; // Display the question with integer operands
answerInput.text = "";  // Clear the previous input
resultText.text = "";   // Clear the result text
}

// Method to check the user's answer
public void CheckAnswer()
{
float userAnswer;

// Try to parse the user's input into a float
if (float.TryParse(answerInput.text, out userAnswer))
{
// Check if the answer is correct with a tolerance for floating-point precision
if (Mathf.Abs(userAnswer - correctAnswer) < tolerance)
{
tempChances = chances-1;
correctAudio.Play();
scorePoint += scorePointPerQuestion;
GenerateNewQuestion(); // Generate a new question if the answer is correct
ScoreReturn();
gameSaver.SaveScore();
manager.LoadData();
}
else if(tempChances>0)
{
if (infinitChance)
{
wrongAudio.Play();
print(tempChances);
}
else
{
resultText.text = "Incorrect. Chances left : " + tempChances;
wrongAudio.Play();
tempChances--;
scorePoint -= scorePointDesuctionRate;
}

}
else if (tempChances == 0)
{
DisplayAnswer();
resultText.text = "Game Over!!";
uiManager.GameOver();
}
}
else
{
resultText.text = "Please enter a valid number.";
wrongAudio.Play();
}
}

это часть кода, которая генерирует и проверяет вопрос.
Я действительно не пробовал ничего нового и использовал AI и Google, чтобы написать это код. но я не могу найти ничего, связанного с добавлением функции BODMAS в Unity, это беспокоит меня уже несколько недель.

Подробнее здесь: https://stackoverflow.com/questions/790 ... e-unity-2d
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»