Autor Tema: Ayuda con mini juego  (Leído 12934 veces)

0 Usuarios y 1 Visitante están viendo este tema.

Desconectado moyo18

  • The Communiter-
  • *
  • Mensajes: 1719
Ayuda con mini juego
« : noviembre 06, 2008, 03:38:14 pm »
Gueno es dis q juegoe s sencillo se trata d lo siguiente


pide tu nombre
se tira el dado supuestamente con un random number y t da un numero ejemplo 5
luego t pregunta si deseas tirarlo otra vez y le das q si t da otro numero 4
t pregunta otrs vez si deseas seguir le das q no
t da la suma de los dos numeros

ahora va la compu y hace lo mismo

puedes seguir jugando hasta q alcenzes un numero mayor d 24 o si el numero q tiras es uno entonces su score se regesa a 0.

luego t dice quien gano, el q tenga mayor puntaje, ahora t pregunta si deseas volver a jugar,  y el problema esta q ya no muestra el score sino q sigue correidno por ella misma y nose en q podria estar el error.

aki les dejo el codigo.

Código: [Seleccionar]
import java.util.Random;
import java.util.Scanner;
import java.io.*;       
/**
 * Play one turn of Pig
 * @author (Moyo)
 * @version (1.0)
 *
 */
public class Pig
{
    static Random r = new Random();  // a random number generator
    static Scanner kb = new Scanner(System.in);
    static String playerName;
    public static void main(String[] args)
    {
      System.out.println("This game is a dice game to play against the computer \n" +
                         " to win the game you have to get the greater score \n" +
                         " if the computer gets a greater score than you, then you \n" +
                         " will lose the game.\n");
      System.out.println("you can still playing if you get a score less then 24, but \n" +
                         "if you get 1 your score will be equal to 0 \n" );
      System.out.println("What is your name? ");
      playerName=getName();
      System.out.println(playerName+", your total "+turn());
      System.out.println("Computer's total "+computerTurn());
     
     
       
     
     
//       winner();
      playAgain();
    }
/**
 * Get the player's name
 * @return the player's name
 *
 */
    public static String getName()
    {
        return kb.next();
    }   
/**
 * Get the winner
 * of the game
*/   
    public static void winner()
    {
        int computerScore = 0;
        int playerScore = 0;
       
        computerScore = computerTurn();
        playerScore = turn();
       
        if ( computerScore < playerScore )
            System.out.println("The Winner is: " + playerName);
        else
            System.out.println("The Winner is the Computer");               
    }     
       
/**
 * Manage a turn of the dice game Pig
 * @return the value of the player's turn
 *
 */
    public static int turn()
    {
        int turnTotal = 0;
        int roll;
        int totalScore = 0;
        Boolean again=true;
        // repeatedly roll the die until a 1 is rolled
        // or the sum exceeds 24
        // or the user says halt
        do
        {       
            roll = toss(6);
            turnTotal += roll ;
            totalScore += turnTotal;
            System.out.println(playerName+", you rolled "+roll);
           
            if (roll!=1)
            {  // ask user if they want to roll again
                System.out.println("roll again? (y/n) ");
                again = kb.next().equals("y");
            }
         
        } while (again && roll!=1 && turnTotal<25);
        // return 0 if a 1 was rolled last, sum of the throws otherwise
        return (roll != 1) ? turnTotal : 0 ;               
    }
/**
 * Computer Turn
 * @return the value of the computer's turn
 *
 */   
    public static int computerTurn()
    {
        int compTurnTotal = 0;
        int compRoll = 0;                 
        // repeatedly roll the die until a 1 is rolled
        // or the sum exceeds 20       
        while (compRoll!=1 && compTurnTotal<25)
        {       
            compRoll = toss(6);
            compTurnTotal += compRoll ;
           
           
            System.out.println("Computer rolled "+compRoll);
           
           
           
        }
        // return 0 if a 1 was rolled last, sum of the throws otherwise
        return (compRoll != 1) ? compTurnTotal : 0 ;                               
    }
/**
 * Toss a die
 * @param numberSides the number of sides on the die
 * @return a random value between 1 and numberSides
 *
 */
    public static int toss(int numberSides)
    {
        return r.nextInt(numberSides)+1;       
    }
/**
 * Ask the user to play again
 */
    public static void playAgain()
    {
        System.out.println("Do you want to play again? (y/n) ");
        while (kb.next().equals("y"))
        {
            turn();
            computerTurn();
            System.out.println("Do you want to play again? (y/n) ");
        }
    }
}

la primera vez q corre lo hace bien pero si le doy q siga jugando pasa el problema

Desconectado moyo18

  • The Communiter-
  • *
  • Mensajes: 1719
Re: Ayuda con mini juego
« Respuesta #1 : noviembre 06, 2008, 03:56:36 pm »
el problema esta en quien es el ganador

Código: [Seleccionar]
// Find out who wins... the one with the greater score will win the game
      int computerScore = computerTurn();
      int playerScore = turn();
       
      if ( computerScore < playerScore )
          System.out.println("The Winner is: " + playerName);
      else
          System.out.println("The Winner is the Computer"); 

no se q hago mal ahi pero eso es lo q arruina todo....

Desconectado g00mba

  • The Communiter-
  • *
  • Mensajes: 14583
  • SOMOS LEGION
    • ALABADO SEA MONESVOL
Re: Ayuda con mini juego
« Respuesta #2 : noviembre 06, 2008, 04:02:20 pm »
hmm lo q veo es q la funcion playagain esta separada del main, te sugeriria mover el bucle de juego al main en lugar de tenerlo afuera. lo demas esta bien encapsulado asi a ojo de águila
« Última Modificación: noviembre 06, 2008, 04:04:17 pm por g00mba »

Desconectado moyo18

  • The Communiter-
  • *
  • Mensajes: 1719
Re: Ayuda con mini juego
« Respuesta #3 : noviembre 06, 2008, 04:08:18 pm »
medio lo tengo arreglado pero aun sigue el problema por el ganador, ya q si emito ese codigo el programa trabaja bien de lo contrario pasa el mismo problema...

asi lo tengo ahorita

Código: [Seleccionar]
import java.util.Random;
import java.util.Scanner;
import java.io.*;       
/**
 * Play one turn of Pig
 * @author (Moyo)
 * @version (1.0)
 *
 */
public class Pig
{
    static Random r = new Random();  // a random number generator
    static Scanner kb = new Scanner(System.in);
    static String playerName;
    public static void main(String[] args)
    {
      System.out.println("This game is a dice game to play against the computer \n" +
                         " to win the game you have to get the greater score \n" +
                         " if the computer gets a greater score than you, then you \n" +
                         " will lose the game.\n");
      System.out.println("you can still playing if you get a score less then 24, but \n" +
                         "if you get 1 your score will be equal to 0 \n" );
      System.out.println("What is your name? ");
      playerName=getName();
      System.out.println(playerName+", your total "+turn());
      System.out.println("Computer's total "+computerTurn());     
     
      [b]// Find out who wins... the one with the greater score will win the game
      int computerScore = computerTurn();
      int playerScore = turn();
       
      if ( computerScore < playerScore )
          System.out.println("The Winner is: " + playerName);
      else
          System.out.println("The Winner is the Computer");  [/b]
     
           
      // Ask the user if they want to continue playing     
      System.out.println("Do you want to play again? (y/n) ");
        while (kb.next().equals("y"))
        {
            System.out.println(playerName+", your total "+turn());
            System.out.println("Computer's total "+computerTurn());     

            System.out.println("Do you want to play again? (y/n) ");
        }
    }
/**
 * Get the player's name
 * @return the player's name
 *
 */
    public static String getName()
    {
        return kb.next();
    }   
/**
 * Manage a turn of the dice game Pig
 * @return the value of the player's turn
 *
 */
    public static int turn()
    {
        int turnTotal = 0;
        int roll;
        int totalScore = 0;
        Boolean again=true;
        // repeatedly roll the die until a 1 is rolled
        // or the sum exceeds 24
        // or the user says halt
        do
        {       
            roll = toss(6);
            turnTotal += roll ;           
            System.out.println(playerName+", you rolled "+roll);           
            if (roll!=1)
            {  // ask user if they want to roll again
                System.out.println("roll again? (y/n) ");
                again = kb.next().equals("y");
            }
         
        } while (again && roll!=1 && turnTotal<25);
        // return 0 if a 1 was rolled last, sum of the throws otherwise
        return (roll != 1) ? turnTotal : 0 ;               
    }
/**
 * Computer Turn
 * @return the value of the computer's turn
 *
 */   
    public static int computerTurn()
    {
        int compTurnTotal = 0;
        int compRoll = 0;                 
        // repeatedly roll the die until a 1 is rolled
        // or the sum exceeds 24       
        while (compRoll!=1 && compTurnTotal<25)
        {       
            compRoll = toss(6);
            compTurnTotal += compRoll ;                       
            System.out.println("Computer rolled "+compRoll);                                   
        }
        // return 0 if a 1 was rolled last, sum of the throws otherwise
        return (compRoll != 1) ? compTurnTotal : 0 ;                               
    }
/**
 * Toss a die
 * @param numberSides the number of sides on the die
 * @return a random value between 1 and numberSides
 *
 */
    public static int toss(int numberSides)
    {
        return r.nextInt(numberSides)+1;       
    }           
}

pero no se como arreglar eso del ganador porq eso vuelve loco los resultados
« Última Modificación: noviembre 06, 2008, 04:12:59 pm por moyo18 »

Desconectado g00mba

  • The Communiter-
  • *
  • Mensajes: 14583
  • SOMOS LEGION
    • ALABADO SEA MONESVOL
Re: Ayuda con mini juego
« Respuesta #4 : noviembre 06, 2008, 04:12:59 pm »
y cual es exactamente el problema con el ganador? traba el programa, se equivoca no muestra nada?

Desconectado g00mba

  • The Communiter-
  • *
  • Mensajes: 14583
  • SOMOS LEGION
    • ALABADO SEA MONESVOL
Re: Ayuda con mini juego
« Respuesta #5 : noviembre 06, 2008, 04:19:00 pm »
ah olvidalo ya lo entendi...

por alguna razon no limpia la variable y te sigue sumando.. creo q eso es el problema verdad

Desconectado g00mba

  • The Communiter-
  • *
  • Mensajes: 14583
  • SOMOS LEGION
    • ALABADO SEA MONESVOL
Re: Ayuda con mini juego
« Respuesta #6 : noviembre 06, 2008, 04:27:00 pm »
ahhh... de hecho vos le estas diciendo q siga sumando...
Código: [Seleccionar]
       while (kb.next().equals("y"))
        {
            System.out.println(playerName+", your total "+turn());
            System.out.println("Computer's total "+computerTurn());     

            System.out.println("Do you want to play again? (y/n) ");
        }
crea una nueva instancia o mata la anterior y volve a usarla. ahi solo estas añadiendo resultados a las mismas instancias.

ahhhh ya te entendi con lo q pusiste abajo
« Última Modificación: noviembre 06, 2008, 04:33:09 pm por g00mba »

Desconectado moyo18

  • The Communiter-
  • *
  • Mensajes: 1719
Re: Ayuda con mini juego
« Respuesta #7 : noviembre 06, 2008, 04:31:21 pm »
mira el problema es este ejemplo d como corre

What is your name?
ron
ron, you rolled 6
roll again? (y/n)
y
ron, you rolled 4
roll again? (y/n)
y
ron, you rolled 1
ron, your total 0





Computer rolled 3
Computer rolled 6
Computer rolled 3
Computer rolled 3
Computer rolled 4
Computer rolled 1
Computer's total 0

-------- hasta aki todo bien

---- aki empieza el devergue porq tendria q decir kien gano y no correr la comp y leugo el user.. y asi hasta el final
no hace lo q supuestamente tiene q hacer.

Computer rolled 1
ron, you rolled 4
roll again? (y/n)
n
The Winner is: ron
Do you want to play again? (y/n)
y
ron, you rolled 1
ron, your total 0
Computer rolled 6
Computer rolled 1
Computer's total 0
Do you want to play again? (y/n)
y
ron, you rolled 2
roll again? (y/n)
n
ron, your total 2
Computer rolled 5
Computer rolled 4
Computer rolled 3
Computer rolled 2
Computer rolled 3
Computer rolled 6
Computer rolled 3
Computer's total 26
Do you want to play again? (y/n)
n


para q corra bien tendria q ser algo asi

What is your name?
ron
ron, you rolled 6
roll again? (y/n)
y
ron, you rolled 4
roll again? (y/n)
y
ron, you rolled 6
roll again? (y/n)
n
ron, your total 16
Computer rolled 3
Computer rolled 6
Computer rolled 6
Computer rolled 4
Computer rolled 4
Computer rolled 3
Computer's total 26
Do you want to play again? (y/n)
y
ron, you rolled 3
roll again? (y/n)

y
ron, you rolled 3
roll again? (y/n)
y
ron, you rolled 1
ron, your total 0
Computer rolled 2
Computer rolled 2
Computer rolled 2
Computer rolled 3
Computer rolled 5
Computer rolled 2
Computer rolled 2
Computer rolled 1
Computer's total 0
Do you want to play again? (y/n)
n


ahi funciona bien sin el pedazo d codigo de

// Find out who wins... the one with the greater score will win the game
       int computerScore = computerTurn();
      int playerScore = turn();
        
       if ( computerScore < playerScore )
           System.out.println("The Winner is: " + playerName);
      else
          System.out.println("The Winner is the Computer");  



Desconectado g00mba

  • The Communiter-
  • *
  • Mensajes: 14583
  • SOMOS LEGION
    • ALABADO SEA MONESVOL
Re: Ayuda con mini juego
« Respuesta #8 : noviembre 06, 2008, 04:37:20 pm »
Código: [Seleccionar]
       int computerScore = computerTurn();
      int playerScore = turn();
       
       if ( computerScore < playerScore )
           System.out.println("The Winner is: " + playerName);
      else
          System.out.println("The Winner is the Computer"); 
ese pedazo de código debería de ser inofensivo 0_o
y si probas asi:
Código: [Seleccionar]
     
       if ( computerTurn() < turn() )
           System.out.println("The Winner is: " , playername);
      else
          System.out.println("The Winner is the Computer"); 

no lo he compilado, pero es lo q se me viene a la cabeza...
por cierto... instancia los juegos completos no solo los turnos.

te explico, el programa como lo tenes vos, es un solo juego q puede repetir las tiradas varias veces y volver a empezar, yo lo veria como un programa q puede tener multiples instancias y dentro de cada instancia multiples tiradas...
« Última Modificación: noviembre 06, 2008, 04:41:58 pm por g00mba »

Desconectado moyo18

  • The Communiter-
  • *
  • Mensajes: 1719
Re: Ayuda con mini juego
« Respuesta #9 : noviembre 06, 2008, 04:55:50 pm »
siempre da el mismo problema y cambiando el codigo como dices aunq asi no lo miro bien, prefiero darle el valod de turn() a una variable ya q asi me ense;aron ...

ahora no entiendo lo q dices aki

Citar
te explico, el programa como lo tenes vos, es un solo juego q puede repetir las tiradas varias veces y volver a empezar, yo lo veria como un programa q puede tener multiples instancias y dentro de cada instancia multiples tiradas...

mira aki esta mi tarea, aunq yo se q me falta pero esto es lo primero q tengo

http://io.uwinnipeg.ca/~rmcfadye/1903/1903Assignment06.htm

aki esta la respuesta a la parte A

http://io.uwinnipeg.ca/~rmcfadye/1903/Pig5.java
« Última Modificación: noviembre 06, 2008, 04:58:00 pm por moyo18 »

Desconectado Camus de Acuario

  • The Communiter-
  • *
  • Mensajes: 8455
  • Ōrora Ekusukyūshon!
Re: Ayuda con mini juego
« Respuesta #10 : noviembre 06, 2008, 05:14:37 pm »
el problema es porque a la segunda, tercera o x corrida ya no te dice quien es el ganador ni el puntaje???

es porque cuando haces el if de querer seguir jugando:

Código: [Seleccionar]
// Ask the user if they want to continue playing     
      System.out.println("Do you want to play again? (y/n) ");
        while (kb.next().equals("y"))
        {
            System.out.println(playerName+", your total "+turn());
            System.out.println("Computer's total "+computerTurn());     

            System.out.println("Do you want to play again? (y/n) ");
        }

aca adentro se te olvido poner lo de:
Código: [Seleccionar]
int computerScore = computerTurn();
      int playerScore = turn();

      if ( computerScore < playerScore )
          System.out.println("The Winner is: " + playerName);
      else
          System.out.println("The Winner is the Computer");

con eso ya te tira el resultado, ahora tu programa tiene varios errores, como que a veces la computadora tira 1, y luego vuelve a tirar y luego volves a tirar vos, bien raro
« Última Modificación: noviembre 06, 2008, 05:18:35 pm por Camus de Acuario »

Desconectado moyo18

  • The Communiter-
  • *
  • Mensajes: 1719
Re: Ayuda con mini juego
« Respuesta #11 : noviembre 06, 2008, 05:21:23 pm »
eso mismo q dices camus me escribio un man q es d los q ayuda en la universidad a los alumnos

Código: [Seleccionar]
I find your program only get scores but never compare them. You can change
to see if it follow your rule.

public static void playAgain() {
        System.out.println("Do you want to play again? (y/n) ");
        while (kb.next().equals("y")) {
            //turn();
            //computerTurn();
            winner();
            System.out.println("Do you want to play again? (y/n) ");
        }

lo mismo me dice y si los mismos errores pasan otra vez, osea q sin eso funciona como deberia pero con eso funciona a lo loco, ya no muestra el total ni quien gano ni nada, nada mas agarra puros numeros random y los muestra.

aki si funciona bien

Código: [Seleccionar]
import java.util.Random;
import java.util.Scanner;
import java.io.*;       
/**
 * Play one turn of Pig
 * @author (Moy)
 * @version (1.0)
 *
 */
public class Pig
{
    static Random r = new Random();  // a random number generator
    static Scanner kb = new Scanner(System.in);
    static String playerName;
    public static void main(String[] args)
    {
      System.out.println("This game is a dice game to play against the computer \n" +
                         " to win the game you have to get the greater score \n" +
                         " if the computer gets a greater score than you, then you \n" +
                         " will lose the game.\n");
      System.out.println("you can still playing if you get a score less then 24, but \n" +
                         "if you get 1 your score will be equal to 0 \n" );
      System.out.println("What is your name? ");
      playerName=getName();
      System.out.println(playerName+", your total "+turn());
      System.out.println("Computer's total "+computerTurn());     
     
     
      System.out.println("Do you want to play again? (y/n) ");
      while (kb.next().equals("y"))
      {
            System.out.println(playerName+", your total "+turn());
            System.out.println("Computer's total "+computerTurn());           
            System.out.println("Do you want to play again? (y/n) ");
      }
    }
/**
 * Get the player's name
 * @return the player's name
 *
 */
    public static String getName()
    {
        return kb.next();
    }   
/**
 * Manage a turn of the dice game Pig
 * @return the value of the player's turn
 *
 */
    public static int turn()
    {
        int turnTotal = 0;
        int roll;
        int totalScore = 0;
        Boolean again=true;
        // repeatedly roll the die until a 1 is rolled
        // or the sum exceeds 24
        // or the user says halt
        do
        {       
            roll = toss(6);
            turnTotal += roll ;           
            System.out.println(playerName+", you rolled "+roll);           
            if (roll!=1)
            {  // ask user if they want to roll again
                System.out.println("roll again? (y/n) ");
                again = kb.next().equals("y");
            }
         
        } while (again && roll!=1 && turnTotal<25);
        // return 0 if a 1 was rolled last, sum of the throws otherwise
        return (roll != 1) ? turnTotal : 0 ;               
    }
/**
 * Computer Turn
 * @return the value of the computer's turn
 *
 */   
    public static int computerTurn()
    {
        int compTurnTotal = 0;
        int compRoll = 0;                 
        // repeatedly roll the die until a 1 is rolled
        // or the sum exceeds 24       
        while (compRoll!=1 && compTurnTotal<25)
        {       
            compRoll = toss(6);
            compTurnTotal += compRoll ;                       
            System.out.println("Computer rolled "+compRoll);                                   
        }
        // return 0 if a 1 was rolled last, sum of the throws otherwise
        return (compRoll != 1) ? compTurnTotal : 0 ;                               
    }
/**
 * Toss a die
 * @param numberSides the number of sides on the die
 * @return a random value between 1 and numberSides
 *
 */
    public static int toss(int numberSides)
    {
        return r.nextInt(numberSides)+1;       
    }
}

pero parto d ese pero naxa al agregar el codigo de winner todo se jode...
« Última Modificación: noviembre 06, 2008, 05:25:08 pm por moyo18 »

Desconectado g00mba

  • The Communiter-
  • *
  • Mensajes: 14583
  • SOMOS LEGION
    • ALABADO SEA MONESVOL
Re: Ayuda con mini juego
« Respuesta #12 : noviembre 06, 2008, 05:23:10 pm »
vaya lo q te digo es q encapsules todo el proceso central del juego para q el main solo lo ocupes para llamar todas las instancias del juego q necesites, el main te quedaría bien chiquito por solo necesitar la llamada a la instancia y un while para preguntar si desea iniciar otro juego, al rato te pongo un ejemplo sencillito
« Última Modificación: noviembre 06, 2008, 05:27:55 pm por g00mba »

Desconectado Camus de Acuario

  • The Communiter-
  • *
  • Mensajes: 8455
  • Ōrora Ekusukyūshon!
Re: Ayuda con mini juego
« Respuesta #13 : noviembre 06, 2008, 05:26:02 pm »
ya vi cual es el error ese que te digo, que computadora y tu juegan 2 veces, como te digo, primero jugas vos, luego la compu, luego la compu otra vez y luego tu, y es por esto:

Código: [Seleccionar]
     System.out.println(playerName+", your total "+turn());
      System.out.println("Computer's total "+computerTurn());      
      
      // Find out who wins... the one with the greater score will win the game
      int computerScore = computerTurn();
      int playerScore = turn();

sea como sea, imprimiendo turn() o asignandole el valor a una variable int, ambas veces llamas la misma funcion y cada una se ejecuta con tiradas diferentes, por eso cada uno juega 2 veces

System.out.println(playerName+", your total "+turn());
aca jugas la primera vez

System.out.println("Computer's total "+computerTurn());  
aca la compu juega la primera vez

int computerScore = computerTurn();
aca la compu juega la segunda vez

int playerScore = turn();
aca jugas la segunda vez

para mi que quites esas todo eso y pongas:

Código: [Seleccionar]
     // Find out who wins... the one with the greater score will win the game
      int computerScore = computerTurn();
      int playerScore = turn();
      
      System.out.println(playerName+", your total "+playerScore);
      System.out.println("Computer's total "+computerScore);
      
      if ( computerScore < playerScore )
          System.out.println("The Winner is: " + playerName);
      else
          System.out.println("The Winner is the Computer");  
      
            
      // Ask the user if they want to continue playing      
      System.out.println("Do you want to play again? (y/n) ");
        while (kb.next().equals("y"))
        {
         computerScore = computerTurn();
            playerScore = turn();
            
            System.out.println(playerName+", your total "+playerScore);
            System.out.println("Computer's total "+computerScore);
            
            if ( computerScore < playerScore )
                System.out.println("The Winner is: " + playerName);
            else
                System.out.println("The Winner is the Computer");
            
            System.out.println("Do you want to play again? (y/n) ");
        }

EDIT: ahora que ya encontramos el error, concuerdo con goomba para que encapsules la main class para que solo haga las llamadas de lo que necesitas, facil y tranquilo, ahorita lo hago y lo pego por aca
« Última Modificación: noviembre 06, 2008, 05:28:22 pm por Camus de Acuario »

Desconectado moyo18

  • The Communiter-
  • *
  • Mensajes: 1719
Re: Ayuda con mini juego
« Respuesta #14 : noviembre 06, 2008, 05:30:57 pm »
Citar
System.out.println(playerName+", your total "+turn());
aca jugas la primera vez

System.out.println("Computer's total "+computerTurn()); 
aca la compu juega la primera vez

int computerScore = computerTurn();
aca la compu juega la segunda vez

int playerScore = turn();
aca jugas la segunda vez

eso pense hace un buen rato, pero no encontraba como guardar los valores, porq si me imagine que al llamar las los metodos y guardarlos en esas variables serian otro valores no se si me entiendes bueno se q si lol.. pero por ahi andaba, no taba tan perdido tampoco.

Desconectado Camus de Acuario

  • The Communiter-
  • *
  • Mensajes: 8455
  • Ōrora Ekusukyūshon!
Re: Ayuda con mini juego
« Respuesta #15 : noviembre 06, 2008, 05:33:26 pm »
cual ayudante de universidad de winnipeg ni que chacharaca, aca en la mera svcommunity sacamos el orgullo y casta salvadoreña jajajajaja
una cosa, a la hora de poner:

Código: [Seleccionar]
int computerScore = computerTurn();
int playerScore = turn();

dale vuelta porque asi empieza jugando la compu

Desconectado g00mba

  • The Communiter-
  • *
  • Mensajes: 14583
  • SOMOS LEGION
    • ALABADO SEA MONESVOL
Re: Ayuda con mini juego
« Respuesta #16 : noviembre 06, 2008, 05:37:11 pm »
jajaja awebos, solo q yo lo hago al revés... primero encapsulo y despues veo donde esta la cagada... es mas fácil identificarla así :P vos lo haces al reves camus... cada quien hace su arte a su manera  :D
lolz
yo te sugeria q el main te quedara como en este ejemplo de una babosadita q hice en la u:

Código: [Seleccionar]
package GuiaEj1;

/**
 *
 * @author antonio
 */
public class Main {


public static void main(String [] argumentos){
     if(argumentos.length!=3) {
             System.out.println("Escriba tres argumentos ej: 3 x 3");
             return;}
     else{
    Ej1 instancia= new Ej1();
    instancia.transforma(argumentos);
    instancia.escojeOperador(instancia.oper);}
   
   
}

}
si te fijas ese main no hace nada mas q controlar q los argumentos sean correctos y despues comienza a llamar métodos para obtener respuestas, toda la lógica esta encapsulada en procedimientos separados, en tu caso, tu main solo se tiene que encargar de correr el juego la primera vez (la primera instancia) y de ahi preguntarte si lo queres seguir corriendo (seguir instanciando)
« Última Modificación: noviembre 06, 2008, 05:39:11 pm por g00mba »

Desconectado Camus de Acuario

  • The Communiter-
  • *
  • Mensajes: 8455
  • Ōrora Ekusukyūshon!
Re: Ayuda con mini juego
« Respuesta #17 : noviembre 06, 2008, 05:42:23 pm »
Yo tambien lo hago como vos, pero en este caso el programa ya estaba hecho y resultaba mas facil ver donde estaba el error, para reconstruirlo, porque si encapsulabamos de un solo y sin querer podiamos arreglar el error y al final ni sabriamos porque era.....

ahora pregunta, es regla del pig (nombre de ese juego) que si tenes resultado iguales gane la compu???


Desconectado moyo18

  • The Communiter-
  • *
  • Mensajes: 1719
Re: Ayuda con mini juego
« Respuesta #18 : noviembre 06, 2008, 05:43:11 pm »
Código: [Seleccionar]
int computerScore = computerTurn();
int playerScore = turn();

si es cierto eso estaba viendo, no se porq .... ya arreglo para q solo metodos salgan en el main

Desconectado g00mba

  • The Communiter-
  • *
  • Mensajes: 14583
  • SOMOS LEGION
    • ALABADO SEA MONESVOL
Re: Ayuda con mini juego
« Respuesta #19 : noviembre 06, 2008, 05:44:28 pm »
ahora pregunta, es regla del pig (nombre de ese juego) que si tenes resultado iguales gane la compu???
jajaj lo decis por q no hay condicion para empate? yo también me fijé en eso   :huh:

Desconectado Camus de Acuario

  • The Communiter-
  • *
  • Mensajes: 8455
  • Ōrora Ekusukyūshon!
Re: Ayuda con mini juego
« Respuesta #20 : noviembre 06, 2008, 05:56:00 pm »
bueno aca esta lo que hice:

Código: [Seleccionar]
import java.util.Random;
import java.util.Scanner;
import java.io.*;       
/**
 * Play one turn of Pig
 * @author (Moyo)
 * @version (1.0)
 *
 */
public class Pig
{
    static Random r = new Random();  // a random number generator
    static Scanner kb = new Scanner(System.in);
    static String playerName;
    static int playerScore;
    static int computerScore;
   
    public static void main(String[] args)
    {
      System.out.println("This game is a dice game to play against the computer \n" +
                         " to win the game you have to get the greater score \n" +
                         " if the computer gets a greater score than you, then you \n" +
                         " will lose the game.\n");
      System.out.println("you can still playing if you get a score less then 24, but \n" +
                         "if you get 1 your score will be equal to 0 \n" );
      System.out.println("What is your name? ");
      playerName=getName();
     
      // Find out who wins... the one with the greater score will win the game
      playerScore = turn();
      computerScore = computerTurn();
     
      System.out.println(playerName+", your total "+playerScore);
      System.out.println("Computer's total "+computerScore);
     
      if ( computerScore < playerScore )
          System.out.println("The Winner is: " + playerName);
      else
          System.out.println("The Winner is the Computer"); 
     
           
      // Ask the user if they want to continue playing     
      System.out.println("Do you want to play again? (y/n) ");
        while (kb.next().equals("y"))
        {
        playerScore = turn();
        computerScore = computerTurn();
           
            System.out.println(playerName+", your total "+playerScore);
            System.out.println("Computer's total "+computerScore);
           
            if ( computerScore < playerScore )
                System.out.println("The Winner is: " + playerName);
            else
                System.out.println("The Winner is the Computer");
           
            System.out.println("Do you want to play again? (y/n) ");
        }
    }
/**
 * Play the game
 * @return the player's name
 *
 */

   
/**
 * Get the player's name
 * @return the player's name
 *
 */
    public static String getName()
    {
        return kb.next();
    }   
/**
 * Manage a turn of the dice game Pig
 * @return the value of the player's turn
 *
 */
    public static int turn()
    {
        int turnTotal = 0;
        int roll;
        int totalScore = 0;
        Boolean again=true;
        // repeatedly roll the die until a 1 is rolled
        // or the sum exceeds 24
        // or the user says halt
        do
        {       
            roll = toss(6);
            turnTotal += roll ;
            if (roll != 1)
            {
            System.out.println(playerName+", you rolled "+roll+" TOTAL: "+turnTotal);
            }
            else
            System.out.println(playerName+", you rolled "+roll+" TOTAL: 0");
           
            if (roll!=1)
            {  // ask user if they want to roll again
                System.out.println("roll again? (y/n) ");
                again = kb.next().equals("y");
            }
         
        } while (again && roll!=1 && turnTotal<25);
        // return 0 if a 1 was rolled last, sum of the throws otherwise
        return (roll != 1) ? turnTotal : 0 ;               
    }
/**
 * Computer Turn
 * @return the value of the computer's turn
 *
 */   
    public static int computerTurn()
    {
        int compTurnTotal = 0;
        int compRoll = 0;                 
        // repeatedly roll the die until a 1 is rolled
        // or the sum exceeds 24       
       
        while (compRoll!=1 && compTurnTotal<25)
        {       
            compRoll = toss(6);
            compTurnTotal += compRoll ;                       
            if (compRoll != 1)
            {
            System.out.println("Computer rolled "+compRoll+" TOTAL: "+compTurnTotal);
            }
            else
            System.out.println("Computer rolled "+compRoll+" TOTAL: 0");
                                               
        }
        // return 0 if a 1 was rolled last, sum of the throws otherwise
        return (compRoll != 1) ? compTurnTotal : 0 ;                               
    }
/**
 * Toss a die
 * @param numberSides the number of sides on the die
 * @return a random value between 1 and numberSides
 *
 */
    public static int toss(int numberSides)
    {
        return r.nextInt(numberSides)+1;       
    }           
}

que hice?
-arregle los errores que habian
-mejore un poquito los tiros para que vaya mostrando el total, asi estas mas al tanto

falta:
-encapsulamiento, clase principal

no la hago porque ya estoy saliendo del trabajo y me voy a vagar para desestresarme jajajajajaja saludos

Moyo: un placer como siempre ayudarte
Goomba: me llega  :thumbsup: nunca habia tenido la oportunidad de hablar con vos y veo que sabes nos estamos viendo al raton

saludos

Desconectado moyo18

  • The Communiter-
  • *
  • Mensajes: 1719
Re: Ayuda con mini juego
« Respuesta #21 : noviembre 06, 2008, 05:57:34 pm »
jajaj lo decis por q no hay condicion para empate? yo también me fijé en eso   :huh:

si eso no lo he hecho.... tengo q arreglar eso

el main me queda asi

Código: [Seleccionar]
public static void main(String[] args)
    {
      //Begins
      rules();                 
      //Ask player's name
      System.out.println("What is your name? ");
      playerName=getName();
      //Find out who wins the game... the one with the greater score will win
      players();
      // Ask the user if they want to continue playing     
      playAgain();
    }

ademas hay algo q no me queda claro en el ejercicio q quieren q haga

Citar
You will need another version of turn(), call it computerTurn(), that is used by the second player, the "computer".  You can decide on the strategy for the computer to use in computerTurn(), and you can adjust your strategy as well by modifying turn(). 

ya hice la copia con el q trabaja el computerturn, pero no entiendo a lo q el se refiere con estrategias de juego...


Desconectado Camus de Acuario

  • The Communiter-
  • *
  • Mensajes: 8455
  • Ōrora Ekusukyūshon!
Re: Ayuda con mini juego
« Respuesta #22 : noviembre 06, 2008, 06:01:53 pm »
mmmmm alli eso de estrategias es de IA, inteligencia artificial, como vos tiras primero, supuestamente la compu ya sabe cual es tu marcador, y tendria que ser capaz de que cuando tire, si en ese tiro ya tiene un numero mayor que vos y que por lo tanto gane, que ya no siga tirando porque le puede salir un 0 y perder ella

asi: tiras y al final te quedas en 19, no te sale 1 que te resetee el contador pero le pones que ya no queres tirar, luego tira la compu, saca 20 y decide ya no tirar porque ya te gano

otro ejemplo tiras, tiras, tiras, sacas 1 y se te resetea el total a 0, viene la compu, tira 2, y ya no sigue tirando porque ya te gano

asi lo comprendo

bueno, IA IA no es jajajaja es nada mas un if que evalue tu puntaje y decida si jugar o no juaaaaaaaaa!!!!!

Desconectado g00mba

  • The Communiter-
  • *
  • Mensajes: 14583
  • SOMOS LEGION
    • ALABADO SEA MONESVOL
Re: Ayuda con mini juego
« Respuesta #23 : noviembre 06, 2008, 06:02:18 pm »

ya hice la copia con el q trabaja el computerturn, pero no entiendo a lo q el se refiere con estrategias de juego...

bueno siendo un juego de dados...  no hay mucha estrategia definida, pero podrias poner una condicion q la computadora jugara "conservativamente" q si al acercarse a digamos 20 parara de tirar o si juega "arriesgado" y trata de llegar al valor mas cercano sin cagarla...

Desconectado moyo18

  • The Communiter-
  • *
  • Mensajes: 1719
Re: Ayuda con mini juego
« Respuesta #24 : noviembre 06, 2008, 06:16:18 pm »
Citar
bueno siendo un juego de dados...  no hay mucha estrategia definida, pero podrias poner una condicion q la computadora jugara "conservativamente" q si al acercarse a digamos 20 parara de tirar o si juega "arriesgado" y trata de llegar al valor mas cercano sin cagarla...

bueno lo q dicen los dos ya lo tenia algo asi antes, nada mas q tenia si la pc alcanza 15, pero me imagine q si el player saca 20 y deja d jugar la pc no tendra posibilidad de ganar.

creo q ire por lo q dice camus.... creare una par d if para comprobar resultado y si el resultado d el jugador es menor q la pc entonces q break el ciclo la pc y gane
« Última Modificación: noviembre 06, 2008, 06:33:18 pm por moyo18 »

Desconectado g00mba

  • The Communiter-
  • *
  • Mensajes: 14583
  • SOMOS LEGION
    • ALABADO SEA MONESVOL
Re: Ayuda con mini juego
« Respuesta #25 : noviembre 06, 2008, 06:50:31 pm »
Goomba: me llega  :thumbsup: nunca habia tenido la oportunidad de hablar con vos y veo que sabes nos estamos viendo al raton
grax, un gusto tambien! pero creo q ya habiamos parlado  :huh: no me acuerdo :P soy medio despistado :P

lo de los 20 era un ejemplo, creo q seria de q tratara de ganar con la menor cantidad posible de tiradas, como de meta lo q saca el jugador +1 con límite 25, ya seria un poco más elaborado.


Desconectado moyo18

  • The Communiter-
  • *
  • Mensajes: 1719
Re: Ayuda con mini juego
« Respuesta #26 : noviembre 06, 2008, 06:58:57 pm »
ya lo hice.. lo q hice fue por ejemplo como son numeros random los q tira osea q hasta la pc puede perder, pero igual digmos si la suma de el jugador es 10 cuando se retira entonces va la pc, si la pc no tiene 1 todavia entonces ira si llega a tener mas q 10 entonces ganara.

ahora si el jugador pasa de los 24 y la pc tambien sera d ver quien obtiene el mayor puntaje, y claro si el jugador tiene 0 la pc si tira la primera vez y tiene mas q 0 entonces hasta ahi llegara y ganara.

Código: [Seleccionar]
while (compRoll!=1 && compTurnTotal<25)
        {       
            compRoll = toss(6);
            compTurnTotal += compRoll ;           
            System.out.println("Computer rolled "+compRoll);
           
            // if the player score is less the computer score then break the while and
            // the computer will win
            if ( playerScore < compTurnTotal)
                break;
        }

Desconectado Camus de Acuario

  • The Communiter-
  • *
  • Mensajes: 8455
  • Ōrora Ekusukyūshon!
Re: Ayuda con mini juego
« Respuesta #27 : noviembre 07, 2008, 10:54:37 am »
bueno les traigo el juego terminado, encapsulado el main y con un pequeño toque de ia, basica que ni se le puede llamar ia pero por lo menos hace la paja

Código: [Seleccionar]
import java.util.Random;
import java.util.Scanner;       
/**
 * Play one turn of Pig
 * @author (Moyo)
 * @version (1.0)
 *
 */
public class Pig
{
    static Random r = new Random();  // a random number generator
    static Scanner kb = new Scanner(System.in);
    static String playerName;
    static int playerScore;
    static int computerScore;
    static int roll;
    static int compTurnTotal;
    static int compRoll;
    static int turnTotal = 0;
   
   
    public static void main(String[] args)
    {
      init();
     
      playerName=getName();

      players();
     
      winner();
     
      playAgain();
     
    }

/**
 * Print the initialization rules
 *
 */
    public static void init()
    {
    System.out.println("This game is a dice game to play against the computer \n" +
                "to win the game you have to get the greater score \n" +
                "if the computer gets a greater score than you, then you \n" +
                "will lose the game.\n");
System.out.println("you can still playing if you get a score less then 24, but \n" +
                "if you get 1 your score will be equal to 0 \n" );
}

/**
 * Get the player's name
 * @return the player's name
 *
 */
    public static String getName()
    {
    System.out.println("What is your name? ");
    return kb.next();
    }     
   
/**
 * Players games
 *
 */
    public static void players()
    {
    // Find out who wins... the one with the greater score will win the game
        playerScore = turn();
        computerScore = computerTurn(); 
    }

/**
 * Find the winner
 *
 */
    public static void winner()
    {
    System.out.println(playerName+", your total is: "+playerScore);
        System.out.println("Computer's total is: "+computerScore);
       
        if ( computerScore < playerScore )
            System.out.println("The Winner is: " + playerName);
        else if ( computerScore == playerScore )
            System.out.println("It's a draw");
        else
            System.out.println("The Winner is: The Computer");
    }

/**
 * Players plays again
 *
 */
    public static void playAgain()
    {
    System.out.println("Do you want to play again? (y/n) ");
        while (kb.next().equals("y"))
        {
          players();
         
          winner();
         
                System.out.println("Do you want to play again? (y/n) ");
        }
    }
   

   
/**
 * Manage a turn of the dice game Pig
 * @return the value of the player's turn
 *
 */
    public static int turn()
    {
    turnTotal = 0;
        Boolean again=true;
        roll = 0;
        // repeatedly roll the die until a 1 is rolled
        // or the sum exceeds 24
        // or the user says halt
        while (again && roll!=1 && turnTotal<25)
        {       
            roll = toss(6);
            turnTotal += roll ;
            if (roll != 1)
            {
            System.out.println(playerName+", you rolled "+roll+" TOTAL: "+turnTotal);
            // ask user if they want to roll again
                System.out.println("roll again? (y/n) ");
                again = kb.next().equals("y");
            }
            else
            { 
            turnTotal = 0;
            //System.out.println(playerName+", you rolled "+roll+" TOTAL: "+turnTotal);
            System.out.println(playerName+", you rolled "+roll+" TOTAL: 0");
            }
        }
        // return 0 if a 1 was rolled last, sum of the throws otherwise
        return (roll != 1) ? turnTotal : 0 ;               
    }

/**
 * Computer Turn
 * @return the value of the computer's turn
 *
 */   
    public static int computerTurn()
    {
        // repeatedly roll the die until a 1 is rolled
        // or the sum exceeds 24       
       
    compTurnTotal = 0;
        compRoll = 0;
                 
        while (compRoll!=1 && compTurnTotal<25 && compTurnTotal<=turnTotal)
        {       
            compRoll = toss(6);
            compTurnTotal += compRoll ;                       
            if (compRoll != 1)
            {
            System.out.println("Computer rolled "+compRoll+" TOTAL: "+compTurnTotal);
            }
            else
            System.out.println("Computer rolled "+compRoll+" TOTAL: 0");
                                               
        }
       
        // return 0 if a 1 was rolled last, sum of the throws otherwise
        return (compRoll != 1) ? compTurnTotal : 0 ;                               
    }

/**
 * Toss a die
 * @param numberSides the number of sides on the die
 * @return a random value between 1 and numberSides
 *
 */
    public static int toss(int numberSides)
    {
        return r.nextInt(numberSides)+1;       
    }           
}
« Última Modificación: noviembre 07, 2008, 11:29:28 am por Camus de Acuario »

Desconectado kikeuntercio

  • Sv Vampire Team ®
  • The Communiter-
  • ***
  • Mensajes: 1545
  • -] java Adict [-
    • Comunidad Bitcoin de Oriente
Re: Ayuda con mini juego
« Respuesta #28 : noviembre 07, 2008, 02:12:35 pm »
y como se juega, y otros detalles mas porfa, claro si se puede sino tacará batallar para ver si se le encuentra la idea XD digo para uno que es medio burro.
Miembro y co-fundador original de VampireTeam
Bitcoiner
CopyMaster en Finandy.com como: WillockSV

Desconectado g00mba

  • The Communiter-
  • *
  • Mensajes: 14583
  • SOMOS LEGION
    • ALABADO SEA MONESVOL
Re: Ayuda con mini juego
« Respuesta #29 : noviembre 07, 2008, 02:28:26 pm »
q bien te quedó camus, bien abstraido, me gusta la sencillez de la funcion de playagain.


untencio, es mas o menos como jugar 21 (o black jack) pero con un dado.


Desconectado moyo18

  • The Communiter-
  • *
  • Mensajes: 1719
Re: Ayuda con mini juego
« Respuesta #30 : noviembre 07, 2008, 03:23:37 pm »
si es como jugar 21, na mas q t dan una carta d primero... una en una y pues no es carta si no un dado lol...

ahora tengo otro deber, q si necesito ayuda lo posteo..

el d camus esta bien, algo similar lo deje yo, na mas q yo no use no use el init method si no q lo use como rules.

pero todo lo demas se parece a lo q entregue.