0

Trying to run this code ive worked on for way too long. Once I reach line "gameaccess.player.playerturn.Add(turn);" in method AddTurns() I get an indexoutofrange exception on the line "public Player player => PlayerList[playeraccess.Turnchecker];". This happens despite having added objects to "PlayerList" in method PlayGame(). I've tried pretty much everything and not sure why this occurs.

class Program
{
    static void Main(string[] args)
    {
        game dartgame = new game();
        dartgame.PlayGame();
    }
}

class game
{   
    public List<Player> PlayerList = new List<Player>();

    Player playeraccess = new Player();
    public Player player => PlayerList[playeraccess.Turnchecker];

    public game(int playercount = 0, int turncounter = 0)
    { 
        PlayerCount = playercount;
        Turncounter = turncounter;
    }

    public int PlayerCount { get; set; }
    public int Turncounter { get; set; }

    public void PlayGame()
    {
        Console.WriteLine("Välkommen och låt spelet börja!");
        Console.WriteLine("För att börja spelet, var vänlig ange antal spelare och spelarnas namn");
        Console.WriteLine("Skriv in antal spelare: ");
        PlayerCount = int.Parse(Console.ReadLine());
        Console.WriteLine("Okej! Du har angivit " + PlayerCount + " spelare.");
        for (int n = 0; n < PlayerCount; n++)
        {
            Console.WriteLine("Skriv nu in namn för spelare " + (n + 1) + ":");
            PlayerList.Add(new Player());
            PlayerList[n].PlayerName = Console.ReadLine();
        }

        Console.WriteLine("Ok, välkomna till spelet!");
        Console.WriteLine("Den spelare vars tur det är får kasta tre gånger");
        Console.WriteLine("genom att skriva 3 heltal");

        Player playeraccess = new Player();
        playeraccess.AddTurns();
    }

    public void winstate()
    {
        Console.WriteLine("Grattis till vinnaren!");
        Console.WriteLine("Du har lyckats samla 301 poäng!");
        Console.WriteLine("Vill ni spela igen? Y/N.");

        for (int exitloop = 0; exitloop == 1; exitloop++)
        {
            char restart = Console.ReadKey().KeyChar;

            if (restart == 'y')
            {
                PlayerCount = 0;
                PlayerList.Clear();
                PlayGame();
            }
            else if (restart == 'n')
            {
            }
            else
            {
                Console.WriteLine("Försök igen, något gick snett");
                --exitloop;
            }
        }
    }
}

class Player
{
    public List<Turns> playerturn = new List<Turns>();

    public Player(string playername = "", int throw1 = 0, int throw2 = 0, int throw3 = 0, int turnchecker = 0)
    {
        PlayerName = playername;
        Throw1 = throw1;
        Throw2 = throw2;
        Throw3 = throw3;
        Turnchecker = turnchecker;
    }

    public string PlayerName { get; set; }
    public int Throw1 { get; set; }
    public int Throw2 { get; set; }
    public int Throw3 { get; set; }
    public int Turnchecker { get; set; }

    public override string ToString()
    {
        return base.ToString();
    }

    public void CalculatePoints()
    {
        game gameaccess = new game();
        int calcpoints = gameaccess.player.playerturn[playerturn.Count].Throwscore1 + gameaccess.player.playerturn[playerturn.Count].Throwscore2 + gameaccess.player.playerturn[playerturn.Count].Throwscore3;

        Console.WriteLine("Du har " + calcpoints + " Poäng totalt.");

        if (calcpoints >= 301)
        {
            gameaccess.winstate();
        }
        else
        {
            if (Turnchecker >= gameaccess.PlayerCount - 1) 
            {
                Turnchecker = 0;
                calcpoints = 0;
                AddTurns();
            }
            else 
            {
                Turnchecker++;
                calcpoints = 0;
                AddTurns();
            }
        }
    }

    public void AddTurns()
    {
        game gameaccess = new game();  
        {
            var turn = new Turns();
            Throw1 = 0;
            Throw2 = 0;
            Throw3 = 0;
            Console.WriteLine("spelare " + (Turnchecker + 1) + ", skriv in ditt första kast.");
            Throw1 = int.Parse(Console.ReadLine());
            Console.WriteLine("spelare " + (Turnchecker + 1) + ", skriv in ditt andra kast.");
            Throw2 = int.Parse(Console.ReadLine());
            Console.WriteLine("spelare " + (Turnchecker + 1) + ", Skriv in ditt sista kast.");
            Throw3 = int.Parse(Console.ReadLine());

            gameaccess.player.playerturn[playerturn.Count].Throwscore1 = gameaccess.player.playerturn[playerturn.Count].Throwscore1 + Throw1;
            gameaccess.player.playerturn[playerturn.Count].Throwscore2 = gameaccess.player.playerturn[playerturn.Count].Throwscore2 + Throw2;
            gameaccess.player.playerturn[playerturn.Count].Throwscore3 = gameaccess.player.playerturn[playerturn.Count].Throwscore3 + Throw3;
            gameaccess.player.playerturn.Add(turn);
            Query();
        }
    }

    public void Query() 
    {
        char query;

        for (int queryloop = 0; queryloop < 1; queryloop++) 
        {
            Console.WriteLine("Vill du se dina poäng? Y/N");
            query = Console.ReadKey().KeyChar;

            if (query == 'y') 
            {
                queryloop = 0;
                Turns turnsaccess = new Turns();
                turnsaccess.GetScore();
            }
            else if (query == 'n')
            {
                queryloop = 0;
                CalculatePoints();
            }
        }
    }
}

public class Turns
{
    public Turns(int turn1 = 0, int turn2 = 0, int turn3 = 0, int turntotal = 0)
    {
        Throwscore1 = turn1;
        Throwscore2 = turn2;
        Throwscore3 = turn3;
        Throwscoretotal = turntotal;
    }

    public int Throwscore1 { get; set; }
    public int Throwscore2 { get; set; }
    public int Throwscore3 { get; set; }
    public int Throwscoretotal { get; set; }

    public void GetScore()
    {
        Player playeraccess2 = new Player();
        Console.WriteLine("Du har fått såhär mycket poäng denna runda:");
        Console.WriteLine("Kast 1: " + playeraccess2.Throw1 + ".");
        Console.WriteLine("Kast 2: " + playeraccess2.Throw2 + ".");
        Console.WriteLine("Kast 3: " + playeraccess2.Throw3 + ".");
        playeraccess2.CalculatePoints();
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 4
    You've posted a lot of code. It's much easier for both yourself and us to debug your problem if you instead post a [mre]. – gunr2171 Apr 01 '21 at 17:27
  • 3
    Just reading your first sentence it's clear that `playeraccess.Turnchecker` is a number that's larger than the size of `PlayerList`. Probably a good time to use the debugger to step through your code – Rufus L Apr 01 '21 at 17:38
  • The code is really convoluted and hard to understand, but in many of your methods you create new objects instead of using existing ones. The problem is likely due to this - adding players to one class then checking them in another one. Remember, every time you use `new`, you're creating a new instance with it's own property values, with nothing shared from any other instances. You might consider using properties and fields to store state instead. – Rufus L Apr 01 '21 at 17:59

1 Answers1

0

Main() sets up game dartgame = new game(); and starts to play dartgame.PlayGame(); but once you get into playeraccess.AddTurns(); the first thing that happens is game gameaccess = new game();.

There's your problem... this new local variable gameaccess has not been initialised, it has a PlayerCount of 0 and a PlayerList with no entries - which you then try to access PlayerList[anything]... Boom! IndexOutOfRange

This is not the only flaw but the common thread is "object relationships". For example the fact that AddTurns() is a (non-static) method of class game and so when a Player object (different class) is told to AddTurns() it somehow has to "know the game it is in".

Time to re-think your design: maybe change the call to AddTurns(game) or save the game in a Player-member variable/property in a prior setup/initialisation method like Player.EnterGame(game).

AlanK
  • 1,827
  • 13
  • 16