sinkADotCom Use a cabeça! Java Dúvida de como proceder

0 respostas
MonsterSmash

Olá galera sou novo no fórum e preciso tirar uma dúvida quanto ao jogo das DotComs do Head First! Java, eu preciso criar uma classe testadora, dentro da minha classe de teste eu fiz um sistema de palpite randômico para dar a classe DotCombust, mas tenho alguns problemas:
-Não sei como "simular" uma entrada pelo usuário no terminal, sem isso não consigo informar a classe que estou dando um palpite.
-Não sei como acessar uma variável que esta dentro de um método qualquer, sem isso não saberei as respostas obtidas ("kill","miss","hit")

Código da classe DotComBust a gerênciadora do jogo:
// Tiger version

import java.util.*;
public class DotComBust {
    public boolean isEnded = false;
    private GameHelper helper = new GameHelper();
    private ArrayList<DotCom> dotComsList = new ArrayList<DotCom>(); 
    private int numOfGuesses = 0; 

   private void setUpGame() {   
      // first make some dot coms and give them locations
      DotCom one = new DotCom();
      one.setName("Pets.com");
      DotCom two = new DotCom();
      two.setName("eToys.com");
      DotCom three = new DotCom();
      three.setName("Go2.com");
      dotComsList.add(one);
      dotComsList.add(two);
      dotComsList.add(three);

      System.out.println("Your goal is to sink three dot coms.");
      System.out.println("Pets.com, eToys.com, Go2.com");
      System.out.println("Try to sink them all in the shortest amount of guesses");
     
       for (DotCom dotComToSet : dotComsList) {   
          ArrayList<String> newLocation = helper.placeDotCom(3);
          //DotCom dotComToSet = (DotCom) dotComsList.get(i);
          dotComToSet.setLocationCells(newLocation);
     
      }
   }


   private void startPlaying() { 
   
     while(!dotComsList.isEmpty()) {
       
        String userGuess = helper.getUserInput("Enter a guess"); 
        checkUserGuess(userGuess);
        
      } // close while
      isEnded = true;
      finishGame();
    } // close startPlaying method


   private void checkUserGuess(String userGuess) {
      numOfGuesses++;
      String result  = "miss"; // assume a miss until told otherwise

      for (DotCom dotComToTest : dotComsList) {

         //DotCom dotComToTest = (DotCom) dotComsList.get(i);
         result = dotComToTest.checkYourself(userGuess);           
          
         if (result.equals("hit")) {
               
               break;
         }
        if (result.equals("kill")) {
               
               dotComsList.remove(dotComToTest); // he's gone
               break;
         }  

       } // close for

      System.out.println(result);
   }
 
 

  private void finishGame() {
     System.out.println("All Dot Coms are dead! Your stock is now worthless");
     if (numOfGuesses <= 9) {
        System.out.println("It only took you " + numOfGuesses + " guesses.  You get the Enron award!");
     } else {
        System.out.println("Took you long enough. "+ numOfGuesses + " guesses.");
        System.out.println("Too bad you didn't get out before your options sank.");
    }
 }
   
  
    public static void main (String[] args) {
      DotComBust game = new DotComBust();
      game.setUpGame();
      game.startPlaying();
    }
}
Classe de ajuda, a entrada e saida do jogo:
// Tiger version

import java.io.*;
import java.util.*;

class GameHelper {

  private static final String alphabet = "abcdefg";
  private int gridLength = 7;
  private int gridSize = 49;
  private int [] grid = new int[gridSize];
  private int comCount = 0;


  public String getUserInput(String prompt) {
     String inputLine = null;
     System.out.print(prompt + "  ");
     try {
       BufferedReader is = new BufferedReader(
	 new InputStreamReader(System.in));
       inputLine = is.readLine();
       if (inputLine.length() == 0 )  return null; 
     } catch (IOException e) {
       System.out.println("IOException: " + e);
     }
     return inputLine.toLowerCase();
  }

  
  
 public ArrayList<String> placeDotCom(int comSize) {                 // line 19
    ArrayList<String> alphaCells = new ArrayList<String>();
    String [] alphacoords = new String [comSize];      // holds 'f6' type coords
    String temp = null;                                // temporary String for concat
    int [] coords = new int[comSize];                  // current candidate coords
    int attempts = 0;                                  // current attempts counter
    boolean success = false;                           // flag = found a good location ?
    int location = 0;                                  // current starting location
    
    comCount++;                                        // nth dot com to place
    int incr = 1;                                      // set horizontal increment
    if ((comCount % 2) == 1) {                         // if odd dot com  (place vertically)
      incr = gridLength;                               // set vertical increment
    }

    while ( !success & attempts++ < 200 ) {             // main search loop  (32)
	location = (int) (Math.random() * gridSize);      // get random starting point
        //System.out.print(" try " + location);
	int x = 0;                                        // nth position in dotcom to place
        success = true;                                 // assume success
        while (success && x < comSize) {                // look for adjacent unused spots
          if (grid[location] == 0) {                    // if not already used
             coords[x++] = location;                    // save location
             location += incr;                          // try 'next' adjacent
             if (location >= gridSize){                 // out of bounds - 'bottom'
               success = false;                         // failure
             }
             if (x>0 & (location % gridLength == 0)) {  // out of bounds - right edge
               success = false;                         // failure
             }
          } else {                                      // found already used location
              // System.out.print(" used " + location);  
              success = false;                          // failure
          }
        }
    }                                                   // end while

    int x = 0;                                          // turn good location into alpha coords
    int row = 0;
    int column = 0;
    // System.out.println("\n");
    while (x < comSize) {
      grid[coords[x]] = 1;                              // mark master grid pts. as 'used'
      row = (int) (coords[x] / gridLength);             // get row value
      column = coords[x] % gridLength;                  // get numeric column value
      temp = String.valueOf(alphabet.charAt(column));   // convert to alpha
      
      alphaCells.add(temp.concat(Integer.toString(row)));
      x++;

      // System.out.print("  coord "+x+" = " + alphaCells.get(x-1));
      
    }
    // System.out.println("\n");
    
    return alphaCells;
   }
}
Objetos DotCom:
// Tiger version

import java.util.*;

public class DotCom {

   private ArrayList<String> locationCells;  
   private String name;

   public void setLocationCells(ArrayList<String> loc) {
      locationCells = loc;
   }

      public void setName(String n) {
      name = n;
  }

   public String checkYourself(String userInput) { 
      String result = "miss";
      int index = locationCells.indexOf(userInput);      
      if (index >= 0) {                              
          locationCells.remove(index);
         
         if (locationCells.isEmpty()) {
             result = "kill";
             System.out.println("Ouch! You sunk " + name + "  : ( ");
         } else {
             result = "hit";
         }  // close if                       
      } // close if            
       return result;

   } // close method
} // close class
Minha classe iniciante(porca e mal organizada) para teste:
class TestDotCom { 

    char[] letter = new char[7];
    String[] enume = new String [7];
    char c = 65;  
    DotComBust test = new DotComBust();

    public void configureGuess() {
         for (int i = 0; i < 7; i++) {
             String a = String.valueOf(i);  
             enume[i] = a;
             letter[i] = c;
              c++;
        }
}
    
    public void letsStart() {
        configureGuess();
        test.main();
        while (test.isEnded == false) {
           giveGuess();
                if (test.isEnded == true) {
                System.out.println("All right with your class");
                break;
            }
        }
            
  }

        
        public void giveGuess() {
            int random = 0 + (int)(Math.random() * 7) ;
            int random2 = 0 + (int)(Math.random() * 7) ;
            String a = enume[random];
            char b =  letter[random2];
            String c = Character.toString(b);  
            test.userGuess = a+c;
        }
    }

O que tentei fazer foi criar uma variável isEnded dentro da DotComBust e quando o jogo fosse terminado seu estado booleano mudasse e a classe de teste se fecharia, mas sem conseguir fazer com que o método giveGuess() passe o palpite não a nada a se fazer.

(Suposto funcionamento de minha classe:
- Declarar variaveis de instânica... duas matrizes, uma para "número" (String, pois no final quero que fique tudo uma string, que é o que pede o jogo) e outra para letra.
- Também declarar um char "c", para ser o inicializador das letras.
- Usar um loop for por 7 vezes (O quadro é 7x7) em que a cada vez ele transforme o valor númerico de i em uma String e atribua ao indice i essa variável, atribuir ao indice i agora das letras a letra de valor 65 ("A" maisculo no caso), acrescentar em 1 o valor de i e c
-Criar um método letsStart que chame o método de configuração dos palpites, chame o método main da classe a ser testada e enquanto não acabar o jogo, dar um palpite e verificar se o jogo acabou, se acabou exibir uma mensagem de confirmação.
-Criar um método giveGuess(), que através de um algoritimo randômico vai criar um palpite...(Ex: 1A, 5B, 6C, 7E etc...))

Muito obrigado desde já e espero que alguém saiba e possa me ajudar.

Criado 4 de fevereiro de 2010
Respostas 0
Participantes 1