我正在尝试访问玩家的分数并在用户回答正确问题时更新它?但是,当我引用实例化对象时,会出现超出范围的错误。
如果问题正确,我会尝试在 TriviaItem 中增加用户分数。
这是我的 repl.it 链接:https ://repl.it/@tylermorales1/TriviaGame#Game.cs
// Game.cs
using static System.Console;
using System;
namespace Trivia
{
class Game
{
public Game()
{
Setup();
Play();
GameOver();
}
public void Setup()
{
// get player name
Player user = new Player();
user.score = 0;
}
public void Play()
{
// check answer
playerInput = ReadLine();
WriteLine(question.checkAnswer(playerInput));
}
}
public void GameOver(){
// Show total score
WriteLine($"Your score is: ");
}
}
}
using static System.Console;
class TriviaItem
{
public string Question;
public string Answer;
//overloaded constructor
public TriviaItem(string question, string answer)
{
Question = question;
Answer = answer;
}
// check answer
public string checkAnswer(string userInput)
{
if(this.Answer.ToLower() == userInput.ToLower()) {
user.score++;
return "Correct!!!";
} else {
return $"\nIncorrect :(\n The correct answer is: '{this.Answer}'\n Your answer was: '{userInput}'";
}
}
}
namespace Trivia
{
class Player
{
public string name = "Anonymous Person";
public int score = 0;
}
}