Oi pessoal,
eu estou criando um jogo de batalha naval para a cadeira de programacão na faculdade. Eu ainda tenho um nivel muito basico então estou com algumas dificuldades.
O jogo precisa das seguintes coisas:
Tem que conter 3 classes: Game, GameBoard e Player
Entrar número de jogadores de 1 a 4
Entrar para cada jogador suas informacões pessoais (nome, idade e email)
Gerar um tabuleiro que o usuario define quantas colunas por quantas linhas terà (min. 10 - max. 20)
Gerar randonicamente um barco que tem que ter o tamanho de 1/3 do tamanho das colunas.
Cada jogador tenta uma jogada e acertando ou errando passa para o proximo jogador
Tem que manter os acertos e erros de cada jogador e com essas informacões manter um score para cada, printando quem ganhou no fim.
Bom, na class palyer eu criei um metodo para o numero de jogadores, um metodo para cada informacao requerida e um metodo para dar loop nas informacoes e um main method. No main method eu chamo o metodo numberOfPlayers(); e addArrayList();
Meu problema é que todas as vezes que roda o loop que está dentro do addArrayList(); aparece uma frase do metodo numberOfPlayers(); que não está em loop.
Sem ver seu código, fica difícil adivinhar. Se puder postá-lo, talvez fique mais fácil.
Uma pergunta: por que seus jogadores estão dentro da classe Player? Acredito que seria mais coerente na classe Game.
Abraço.
A
AndressaSchinoff
Sim, claro!
packageBattleship;importjava.io.FileWriter;importjava.io.PrintWriter;importjava.util.ArrayList;importjava.util.Scanner;/* * ======================================== * * Student: Andressa Martins Schinoff Alves * Student number: 2017280 * Teacher: Ken Healy * * ======================================== */publicclassplayer{//Score global variableintplayerScore;//Save age into a integerintage;//Name global variable that contains substrings firstName and surnameStringname="",firstName="",surname="";//Boolean to look at if it has spacesbooleanspaceUsed;//boolean to look at if it has @booleanvalidAT;//boolean to look if it has .combooleanvalidDotCom;//boolean to look if it has .iebooleanvalidDotIE;//It intspaceAt;//Email global variableStringemail;//Save the input of how many players will play into a intinthowManyPlayers;//This variable is to add which loop and change the player laterintplayer=1;/*this method is run methods numberOfPlayers, name, email and age after run it * save the player info a array list, also after it is in loop * to run how many times it is request.*/publicplayer(Stringname,intage,Stringemail){//calls method number of playersnumberOfPlayers();addArrayList();this.name=name;this.age=age;this.email=email;}//I made this method to add objects to array list//and do the for loop for each player publicvoidaddArrayList(){//Using for loop for run and save it for each player//int i starts on 1 to use also as number of the player on the screenfor(inti=1;i<howManyPlayers+1;i++){//Print on the screen what the user should insert//I used the int i to clarify for the user which information is being requestSystem.out.println("Insert player "+i+" details");//call methods for save it for each playername();age();email();ArrayList<player>myplayer=newArrayList<player>();myplayer.add(newplayer(name,age,email));}}publicvoidname(){//boolean value to validatebooleanvalid=false;do{//Read the inputScannerfullName=newScanner(System.in);//Print in the screen which input the user should insertSystem.out.println("What is your full name?");//Save the input as a variablename=fullName.nextLine();//It is to eliminate the space the user can insert for accident, but consider the space between wordsname=name.trim();//It is to find the space between first name and surnamespaceUsed=name.contains(" ");//I used the if Statement to do 2 things first to valid the input//but also to recognise the first name and surnameif(spaceUsed){valid=true;//It is used to recognise the space in the variable, it could be any type of variablespaceAt=name.indexOf(' ');//Recognise everything is insert before the first space and becomes it into a new variablefirstName=name.substring(0,spaceAt);//Take everything after the first space and becomes it into another variablesurname=name.substring(spaceAt+1,name.length());//RETIRAR ISSOSystem.out.println("Backwards, your name is: "+surname+" "+firstName);//if it not have first name and surname it's not valid}else{valid=false;//Print in the screen the error message, helping the user solve the problemSystem.out.println("Please, enter your first name and surname.");}//Anything else is not valid}while(valid==false);}publicintage(){//Boolean to valid booleanvalid=false;do{//Scanner is used to read the inputScannerageInput=newScanner(System.in);//Print what input the user should insert System.out.println("What is your age?");//input read equals variable ageage=ageInput.nextInt();//if statement used to if(age>=12&&age<=100){valid=true;}else{valid=false;System.out.println("Sorry you need have between 12 and 100 to play.");}}while(valid==false);returnage;}publicvoidemail(){booleanvalid=false;do{//Read the user inputScanneremailInput=newScanner(System.in);//Print on screen what input the user should insertSystem.out.println("What is your email?");//save the user input as a variable emailemail=emailInput.nextLine();//I used 3 variables to look if the variable email contains "@", ".com" and ".ie"//I don`t know if has how look the 3 info in the same variable//But it was the way I find to validate correctlyvalidAT=email.contains("@");validDotCom=email.contains(".com");validDotIE=email.contains(".ie");//Use the if statement to validate//it`s valid just if it has @ and .com OR @ and .ieif(validAT&&(validDotCom||validDotIE)){valid=true;}//Any email the don't contains @ or .com/.ie is not validelse{valid=false;System.out.println("Please, enter a valid email.");}}while(valid==false);}publicintscore(){//Score = Hit() - (Misses() * 2)returnplayerScore;}publicintHit(){inthits=0;intHit=0;hits++;returnHit;}//I use the method int to returns the number of players to use later in another classpublicintnumberOfPlayers(){//boolean to validate how many players since it can have min.1 and max.4 playersbooleanvalid=false;//Prints on the screen what the user should insertSystem.out.println("How many players will play? (Min.1 - Max.4)");do{Scannerplayers=newScanner(System.in);howManyPlayers=players.nextInt();if(howManyPlayers>=1&&howManyPlayers<=4){valid=true;}else{valid=false;System.out.println("Please, enter a valid number.");}}while(valid==false);returnhowManyPlayers;}}
A
AndressaSchinoff
packageBattleship;importjava.util.Random;importjava.util.Scanner;publicclassGameBoard{intwidth,height;int[]pickedShip;//Random location = new Random();GameBoardBattleship;int[][]board;int[][]guess;//= new int[height][width];int[][]ship;// = new int[height][width];inthorizontal;intvertical;into;intn;publicGameBoard(intcol,introw){this.width=col;this.height=row;board();drawBoard();GenerateBattleship();guess();}publicvoidboard(){booleanvalid=false;try{do{System.out.println("Enter the number of rows between 10 and 20");Scannercol=newScanner(System.in);width=col.nextInt();if(width>=10&&width<=20){valid=true;}else{valid=false;System.out.println("\n"+"Please insert a valid number: min.10, max.20");}}while(valid==false);do{System.out.println("\n"+"Enter the number of columns between 10 and 20");Scannerrow=newScanner(System.in);height=row.nextInt();if(height>=10&&height<=20){valid=true;}else{valid=false;System.out.println("Please insert a valid number: min.10, max.20");}}while(valid==false);ship=newint[height][width];board=newint[height][width];guess=newint[height][width];pickedShip=newint[width/3];}catch(Exceptione){System.out.println("Invalid input "+e);}}publicvoiddrawBoard(){intm=1;System.out.println("\n"+"Those numbers represent which position in the board : "+"\n");for(inti=0;i<height;i++){for(intj=0;j<width;j++){board[i][j]=m;m++;System.out.print(board[i][j]+"\t");ship[i][j]=board[i][j];}System.out.println();}}publicvoidGenerateBattleship(){inta=(int)(Math.random()*2);horizontal=(int)(Math.random()*width);vertical=(int)(Math.random()*height);intsize=Math.round(width/3);if(a==1){for(inti=0;i<size;i++){if(vertical+size<height){o=vertical+i;n=horizontal;System.out.println("p1 v+, "+ship[o][n]);pickedShip[i]=ship[o][n];}elseif(vertical+size>height){o=vertical-i;n=horizontal;System.out.println("p1 v-, "+ship[o][n]);pickedShip[i]=ship[o][n];}}}else{for(inti=0;i<size;){if(horizontal+size<width){o=vertical;n=horizontal+i;i++;//guess = new int [m][n];System.out.println("p0 h+, "+ship[o][n]);pickedShip[i]=ship[o][n];}elseif(horizontal+size>width){o=vertical;n=horizontal-i;//guess = new int [m][n];System.out.println("p0 h-, "+ship[o][n]);pickedShip[i]=ship[o][n];}}}}publicvoidguess(){System.out.println("\n"+"In the board 0 means hit and -1 means miss.");System.out.println("\n"+"Please, enter a position number: ");Scannerinput=newScanner(System.in);intanswer=input.nextInt();int[]resposta=null;booleanwin=false;for(inti=0;i<width/3;i++){resposta[i]=pickedShip[i];if(answer==pickedShip[i]){win=true;System.out.println("Hey! You hit it!");}else{System.out.println("Sorry, you miss it!");//drawBoard();}}}}
A
AndressaSchinoff
packageBattleship;/* * ======================================== * * Student: Andressa Martins Schinoff Alves * Student number: 2017280 * Teacher: Ken Healy * * ======================================== */publicclassGame{publicstaticvoidmain(String[]args){// TODO code application logic hereStringname="";intage=0;Stringemail="";introw=0;intcol=0;//player Player = new player(name, age, email);GameBoardBattleship=newGameBoard(row,col);}}
A
AndressaSchinoff
Essas são minhas 3 class.
S
staroski
Quando postar códigos, selecione eles e clique no botão </> senão fica horrível de visualizar.