Olá,estou com problema nesse exercício:
O objetivo é criar o jogo sink a dot com (parecido com batalha naval,com uma grade de 7 x 7) , para isso há três classes:
DotcomBust - O jogo em si , possui os métodos para iniciar , continuar e finalizar o jogo.
Dotcom - as próprias dotComs a serem derrubadas,possuem duas principais características : sua posição na grade(uma ArrayList) e um nome.
GameHelper - Pega as entradas do usuário,gera as posições das dotComs e “manda” para a classe dotCom.
Onde está meu problema:
-
Não importa o que o usuário digitar o programa sempre retornará a mensagem de Correto mesmo que o palpite esteja errado.
-
Mesmo depois que todas são derrubadas o jogo não acaba(o método finishGame() não é executado).
principais métodos:
DotcomBust - setUpGame() (recebe da classe GameHelper as posições das dotComs e manda para as três DotComs(três instâncias do objeto DotCom).
DotcomBust - startPlaying () e checkUserGuess() (recebem da classe GameHelper o palpite do usuário,excluem da ArrayList a posição que o usuário acertar e exclui a dotCom quando ela for derrubada).
GameHelper - getUserInput() (Captura entradas do usuário).
GameHelper - placeDotCom() (Gera as posições para as dotComs).
Código :
classe Dotcom :
import java.util.ArrayList;
public class DotCom {
private String name;
private ArrayList<String> locationCells ;
public void setLocationCells(ArrayList<String> loc){
locationCells = loc;
}
public void setName(String n){
name = n;
}
public String checkYourself(String userGuess){
int index = locationCells.indexOf(userGuess);
String result = "Correto";
if (index >= 0){
locationCells.remove(index);
result = "Errado";
}
if(locationCells.isEmpty()){
result = "Eliminar";
System.out.println ("Você eliminou a "+name+"!");
}
return result;
}
}
classe DotcomBust:
import java.util.ArrayList;
public class DotcomBust {
private GameHelper helper = new GameHelper();
private ArrayList<DotCom> dotComsList = new ArrayList<DotCom>();
private int numOfGuesses;
void setUpGame(){
System.out.println ("Bem - vindo ao Sink a DotCom");
System.out.println ("Seu objetivo é derrubar as três DotComs");
System.out.println ("Use o menor número de palpites possível");
DotCom one = new DotCom();
DotCom two = new DotCom();
DotCom three = new DotCom();
one.setName ("Ask.com");
two.setName ("OneEye.com");
three.setName ("Sink.com");
dotComsList.add (one);
dotComsList.add (two);
dotComsList.add (three);
for(DotCom DotToSet : dotComsList){
ArrayList<String> newLocation = helper.placeDotCom(3);
DotToSet.setLocationCells(newLocation);
}
}
void startPlaying(){
while(!dotComsList.isEmpty() ){
String guess = helper.getUserInput("Insira um palpite:");
checkUserGuess(guess);
}
finishGame();
}
void checkUserGuess(String UserGuess){
numOfGuesses ++;
String result = "Errado";
for(DotCom DotToTest : dotComsList){
result = DotToTest.checkYourself(UserGuess);
if(result.equals("Correto")){
break;
}
if(result.equals("Eliminar")){
dotComsList.remove(DotToTest);
}
}
System.out.println (result);
}
void finishGame(){
System.out.println ("Fim de jogo.");
if(numOfGuesses <= 10){
System.out.println ("Parabéns");
}
else if (numOfGuesses <= 20){
System.out.println("Muito bem.");
}
else{
System.out.println ("Ok,você pode melhorar");
}
}
public static void main (String args []){
DotcomBust game = new DotcomBust();
game.setUpGame();
game.startPlaying();
}
}
GameHelper:
import java.io.*;
import java.util.*;
public 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 ("IO Exception "+ e);
}
return inputLine.toLowerCase();
}
public ArrayList<String> placeDotCom (int comSize){
ArrayList<String> alphacells = new ArrayList<String>();
String [] alphacoords = new String[comSize];
String temp = null;
int [] coords = new int [comSize];
int attempts = 0;
boolean success = false;
int location = 0;
comCount ++;
int incr = 1;
if((comCount % 2 )== 1){
incr = gridLength;
}
while(!success & attempts++ < 200){
location = (int) (Math.random() * gridSize);
System.out.println ("Tente aqui : "+location);
int x = 0;
success = true;
while(success && x<comSize){
if(grid[location]== 0){
coords[x++] = location;
location +=incr;
if(location >= gridSize){
success = false;
}
if (x > 0 && (location % gridLength == 0)){
success = false;
}
}else{
System.out.println ("Usado" + location);
success = false;
}
}
}
int x = 0;
int row = 0;
int column = 0 ;
System.out.println ("\n");
while (x<comSize){
grid[coords[x]] = 1;
row = (int) (coords[x] / gridLength);
column = coords[x] % gridLength;
temp = String.valueOf(Alphabet.charAt(column));
alphacells.add(temp.concat(Integer.toString(row)));
x++;
System.out.print ("Coord"+x+" = " + alphacells.get(x-1));
}
System.out.println ("\n");
return alphacells;
}
}
Agradeço a atenção.