Pontuação de Jogo de Boliche usando arrays

Pessoal eu estou com um problema para resolver aqui da faculdade. Estou fazendo um intercâmbio aqui nos Estados Unidos e escolhi Java 1 para ser uma das cadeiras a cursar. O professor nos passou um problema que valerá 10% da minha nota e eu realmente estou me enrolando todo com ele. O problem pode ser visto aqui nesta página ( http://www.cs.montana.edu/paxton/classes/spring-2013/csci111/programs/program5/ ) mas vou explicar resumidamente aqui.

O que eu tenho q fazer basicamente é simular um jogo de boliche no que se diz respeito a pntuação. Como todos sabem quando voce faz um strike as duas proximas jogadas contam para a pontuação e no caso do spare apenas a proxima conta para a pontuação.

Pelo que voces estão vendo eu vou ter que ficar indo e voltando no array de jogadas o tempo todo e vou ter que ficar somando posições e dependendo se tiver sido strike ou spare eu tenho q somar outras posições também.

Tenho uma dúvida a princípio básica, estou tentando pecorrer o vetor de jogadas que por exemplo pode ser como abaixo em um caso de um jogo normal de 10 frames e 20 tentativas (em um jogo de boliche tem-se 2 tentativas para derrubar os pinos).

rolls = new int[] {1, 1, 2, 2, 3, 3, 4, 4, 5, 4, 6, 3, 2, 7, 1, 8, 0, 9, 0, 0};

Para pecorrer estava tentando o loop que segue

for(int i=0;i<=rolls.length;i++)
        {
            
            for(int numberFrame=1;numberFrame<=frames;numberFrame++)
            {
                while(i!=(rolls.length-1))
                {
                    System.out.println("+---+---+   Frame"+ numberFrame);
                    System.out.println("| "+rolls[i]+" | "+rolls[i+1]+" |");
                    System.out.println("|---+---|");
                    System.out.println("|     "+(rolls[i]+rolls[i+1])+" |");
                    System.out.println("+-------+");
                }
            }
        }

O problema é que tenho um erro de execução quando eu tento acessa uma posição do vetor maior que o tamanho do vetor pois estou tentado a principio so somar todas as jogadas e dividir em a pontuação nos frames.

Alguém tem alguma dica para mim, creio que qualquer ajuda será muito bom. Obrigado pessoal.

Cara, eu dei uma lida no seu post, entrei nos links que você enviou e finalmente consegui entender o que você tem que fazer.
Você viu que tem que atender àquela classe Driver, não? Basicamente você tem que fazer o seu programa funcionar do jeito que ela espera.

Você tem que colocar as regras do boliche no seu loop. Caso ele faça um spare ou um strike, você não pode mudar de frame.
É isso. Qualquer coisa dá um grito aí.

Opa,

Cara, eu devo esta complicando muito as coisas viu, por que eu não consigo raciocinar para manusear o array e formatar para mostrar os frames do jeito que é exigido. Eu entendi o que o driver faz mas fazer o método play é q esta complicado. Eu fiz um metodo so para colocar os valores dos frames num array…


public void frames()
    {
        int j=0;
        for(int i = 0;i<framesScore.length;i++)
        {   
            if(j!=rolls.length-1)
            {
                if(i==0)
                {
                    framesScore[i] = rolls[j]+rolls[j+1];
                    j = j+2;
                }
                else
                {
                    framesScore[i] = framesScore[i-1]+rolls[j]+rolls[j+1];
                    j = j+2;
                }
            }
        }
    }

Dessa forma eu vou ter todos os valores dos frames mas só se não tiver strikes e spares…tentei printar isso formatado da forma que foi exigido e esta meio tenso. Tu tem como me ajudar com a logica dos strikes e spares?

Tem sim. Eu acho que tem que ficar mais ou menos assim:[code]

boolean temRodadaAdicional = false;

Se foi um Strike e está na primeira rodada // se acertou 10 na primeira rodada
	Multiplica os pontos para o strike;
	temRodadaAdicional = true; //Espera-se 3 rodadas nesse frame;
Fim se;

Se está na 2 rodada e fez um spare (o valor da rodada anterior + o valor desta = 10)
	Multiplica os pontos para o spare;
	temRodadaAdicional = true //Espera-se 3 rodadas nesse frame;
Fim se;

Se (temRodadaAdicional = true)
	// calcula os pontos da rodada
Fim se;

[/code]
Senão, o resto continua normalmente, você recebe o valor, se não for 10 nas duas primeiras, calcula e já era.
Tenta isso e vê se dá certo… eu acho que dá pra ficar melhor, mas por enquanto isso vai te quebrar o galho

Fala pessoal, acabei de terminar o meu programa e para não deixar o tópico sem um fim vou postar aqui. Jaboot muito Obrigado pela ajuda cara, foi de grande valia.

Segue abaixo o código. Ps. os comentarios estão em inglês por que o tenho que entregar o projeto aqui na faculdade mesmo.



/**
 * Simulate the calculation used to calculate a bowling game score
 * 
 * @author Kaio Jonathas Alencar Gurgel
 * @version April 2, 2013
 */
public class Bowling
{
    private int[] rolls;
    private int frames;

    /**
     * Constructor for objects of the class Bowling
     *
     * @param   inRolls A array with the rolls of a bowling game
     * @param   inFrames A int number with the number of frames
    */
    public Bowling(int[] inRolls, int inFrames)
    {
        rolls = inRolls;
        frames = inFrames;
    }
    
    /**
     * Make all the calculations needed to calculate the score of the bowling game
     * using the array rolls and the number of frames. To print a well formatted frame
     * of the game the method uses a private method called printFrame and in the case 
     * of the last frame with three rolls it is called the method printLastFrame
     */
    public void play()
    {   
        int numberFrame = 1; //The frame number starts in 1 and is incremented each time we print the frame
        int scoreSoFar = 0; //Score at each frame (it is being changed periodically)
        
        for(int i=0;i<rolls.length-1;i=i+2)
        {   
            if(rolls[rolls.length-3] == 10 || rolls[rolls.length-3] + rolls[rolls.length-2] == 10) //Extra Roll at the end
            {
                if (i>=rolls.length-3)
                {
                    scoreSoFar = scoreSoFar + rolls[i] + rolls[i+1] + rolls[i+2];
                    printLastFrame(numberFrame,rolls[i], rolls[i+1], rolls[i+2],scoreSoFar);
                    numberFrame++;
                }
                
                else if(rolls[i]==10) //if it is a strike
                {
                    scoreSoFar = scoreSoFar + rolls[i] + rolls[i+1] + rolls[i+2];
                    printFrame(numberFrame,rolls[i], 0,scoreSoFar); //When we have a strike the second roll doesn't apply
                    numberFrame++;
                    i--;
                }
                
                else if(rolls[i]+rolls[i+1]==10 && rolls[i] != 10)
                {
                    scoreSoFar = scoreSoFar + rolls[i] + rolls[i+1] + rolls[i+2];
                    printFrame(numberFrame,rolls[i], rolls[i+1],scoreSoFar);
                    numberFrame++;
                }
                
                else
                {
                    scoreSoFar = scoreSoFar + rolls[i] + rolls[i+1];
                    printFrame(numberFrame,rolls[i], rolls[i+1],scoreSoFar);
                    numberFrame++;
                }
            }
            else if(rolls[i]==10) //if it is a strike
            {
                scoreSoFar = scoreSoFar + rolls[i] + rolls[i+1] + rolls[i+2];
                printFrame(numberFrame,rolls[i], 0,scoreSoFar); //When we have a strike the second roll doesn't apply
                numberFrame++;
                i--;
            }
            else if(rolls[i]+rolls[i+1]==10 && rolls[i] != 10)
            {
                scoreSoFar = scoreSoFar + rolls[i] + rolls[i+1] + rolls[i+2];
                printFrame(numberFrame,rolls[i], rolls[i+1],scoreSoFar);
                numberFrame++;
            }
            else
            {
                scoreSoFar = scoreSoFar + rolls[i] + rolls[i+1];
                printFrame(numberFrame,rolls[i], rolls[i+1],scoreSoFar);
                numberFrame++;
            }
        }
    }

     /**
     * Print one well formatted frame of the bowling game
     *
     * @param   numberFrame The number of frames of the game
     * @param   roll1 The first roll of the frame
     * @param   roll2 The second and last roll of the frame
     * @param   score The updated score of the game
     */
    private void printFrame(int numberFrame,int roll1, int roll2, int score)
    {
        System.out.println("+---+---+   Frame"+ numberFrame);
        if (roll1 + roll2 == 10 && roll1 != 10)
        {
            System.out.println("| "+roll1+" | / |");
        }
        else if (roll1==10)
        {
            System.out.println("|   | X |");
        }
        else
        {
             System.out.println("| "+roll1+" | "+roll2+" |");
        }
        System.out.println("|---+---|");
        if (score>=10 && score<=99)
        {
            System.out.println("|    "+score+" |");
        }
        else if (score>=100)
        {
            System.out.println("|   "+score+" |");
        }
        else 
        {
            System.out.println("|     "+score+" |");
        }
        System.out.println("+-------+");
        System.out.println(" ");
    }
    
     /**
     * Print one well formatted frame of the bowling game in the special case of the last frame with three rolls
     *
     * @param   numberFrame The number of frames of the game
     * @param   roll1 The first roll of the frame
     * @param   roll2 The roll of the frame
     * @param   roll2 The third and last roll of the frame
     * @param   score The updated score of the game
     */
    private void printLastFrame(int numberFrame,int roll1, int roll2, int roll3, int score)
    {
        System.out.println("+---+---+---+   Frame"+ numberFrame);
        if(roll1 == 10 && roll2 != 10 && roll3 != 10 && roll2 + roll3 != 10)
        {
            System.out.println("| X | "+roll2+" | "+roll3+" |");
        }
        else if(roll1 == 10 && roll2 == 10 && roll3 != 10)
        {
            System.out.println("| X | X | "+roll3+" |");
        }
        else if(roll1 == 10 && roll2 == 10 && roll3 == 10)
        {
            System.out.println("| X | X | X |");
        }
        else if(roll1 + roll2 == 10 && roll1 != 10 && roll3 != 10)
        {
            System.out.println("| "+roll1+" | / | "+roll3+" |");
        }
        else if(roll2 + roll3 == 10 && roll1 == 10 && roll2 != 10)
        {
            System.out.println("| X | "+roll2+" | / |");
        }
        else if(roll1 + roll2 == 10 && roll1 != 10 && roll3 == 10)
        {
            System.out.println("| "+roll1+" | / | X |");
        }
        System.out.println("|---+---+---|");
        if(score>=10 && score<=99)
        {
            System.out.println("|        "+score+" |");
        }
        else if(score<10)
        {
            System.out.println("|         "+score+" |");
        }
        else if(score>100)
        {
            System.out.println("|       "+score+" |");
        }
        System.out.println("+-----------+");
        System.out.println(" ");
    }
}

Vou colocar a classe Driver que estou usando.



/**
 * The driver for CSCI 111 Program 5; Bowling
 * 
 * @author John Paxton 
 * @version March 9, 2013
 */

public class Driver
{
    public static void main (String [] args)
    {
        Bowling game;
        int [] rolls;
        
        rolls = new int[] {1, 1, 2, 2, 3, 3, 4, 4, 5, 4, 6, 3, 2, 7, 1, 8, 0, 9, 0, 0};
        oneGame(rolls, 10);   // bowl a game with 10 frames
        
        rolls = new int[] {10, 10, 10, 10, 10, 10, 10};
        oneGame(rolls, 5);    // bowl a game with 5 frames
        
        rolls = new int[] {6, 4, 5};
        oneGame(rolls, 1);    // bowl a game with 1 frame
        
        rolls = new int[] {10, 2, 8};
        oneGame(rolls, 1);
        
        rolls = new int[] {2, 8, 10};
        oneGame(rolls, 1);
        
        rolls = new int[] {10, 2, 7};
        oneGame(rolls, 1);
        
        rolls = new int[] {10, 10, 2};
        oneGame(rolls, 1);
        
    }
    
    private static void oneGame(int [] rolls, int frames)
    {
        Bowling game = new Bowling(rolls, frames);
        
        System.out.println(">>>>> New Bowling Game <<<<<\n");
        game.play();
    }
}

Então assim fecho o tópico, todo o material necessário para simular a pontuação de um jogo de boliche esta aqui nesse topico, espero que seja de grande valia para alguém no futuro por que eu sofri um pouco para codificar. Até mais gente.