Array index out of range

The array index is out of range and the code doesn’t work…

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ActionMaster {

    public enum Action {Tidy, Reset, EndTurn, EndGame};

    private int[] bowls = new int[21];
    private int bowl;

	public Action Bowl(int pins)
    {
        bowls[bowl - 1] = pins; ----Problem

        if (bowl == 21)
        {
            return Action.EndGame;
        }

        if (bowl >= 19 && pins == 10)
        {
            bowl++;
            return Action.Reset;
        } else if (bowl == 20)
        {
            bowl++;
            if (bowls[19 - 1] == 10 && bowls[20 - 1] == 0)
            {
                return Action.Tidy;
            } else if ((bowls[19 - 1] + bowls[20 - 1]) % 10 == 0)
            {
                return Action.Reset;
            } else if (Bowl21Awarded())
            {
                return Action.Tidy;
            } else
            {
                return Action.EndGame;
            }
        }

        if (pins < 0 || pins > 10)
        {
            throw new UnityException("Ivalid number of pins");
        }


        // If first bowl of frame 
        // return Action.Tidy

        if (bowl % 2 != 0) // First Bowl - Frame
        { // Shoot 2 times no spare
            if (pins == 10)
            {
                bowl += 2;
                return Action.EndTurn;
            } else
            {
                bowl += 1;
                return Action.Tidy;
            }
        } else if (bowl % 2 == 0) // Second Bowl - Frame or Make a spare
        {
            bowl += 1;
            return Action.EndTurn;
        }

        throw new UnityException("Not sure what action to return!");
    }

    private bool Bowl21Awarded()
    {
        return (bowls[19 - 1] + bowls[20 - 1] >= 10);
    }
}

Help :frowning:

By default the bowl variable is initialized to 0, so the first time the function Bowl() is called, the line

bowls[bowl - 1] = pins;

will try to access element -1 of the bowls array, which doesn’t exist.
Since what you want is to start the bowl variable at 1 instead of 0, simply initialize it like so:

private int bowl = 1;

TY very much :smiley:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms