publicclassPasswordGuessGame{privatestaticfinalintDIFFICULTY_MULTIPLIER=5;privatestaticintguessesLeft=4;privatestaticbooleangameIsWon=false;privatestaticchar[]winningCombination;publicstaticvoidmain(String[]args)throwsIOException{Scannerin=newScanner(System.in);System.out.println("Difficulty? (1-5)");intdifficulty=in.nextInt();in.nextLine();List<String>wordHints=getWords(difficulty);Randomrand=newRandom();winningCombination=wordHints.get(rand.nextInt(wordHints.size())).toCharArray();while(notGameOver()){for(Stringhint:wordHints){System.out.println(hint);}System.out.println("Guess ("+guessesLeft+" left)?");StringnextLine=in.nextLine();intresult=compare(nextLine);finalintwordLength=difficulty*2+DIFFICULTY_MULTIPLIER;if(result==wordLength){gameIsWon=true;}else{guessesLeft--;System.out.println(result+"/"+wordLength+" correct");}}printWinOrLose();}privatestaticbooleannotGameOver(){returnguessesLeft!=0&&!gameIsWon;}privatestaticvoidprintWinOrLose(){if(gameIsWon){System.out.println("You are victorious");}elseif(guessesLeft==0){System.out.println("You have ran out of guesses, try again");}}privatestaticintcompare(Stringinput){inttotalCorrectCharacters=0;char[]inputCharArray=input.toCharArray();if(input.length()!=winningCombination.length){System.out.println("Please input a string of the same size");return0;}for(inti=0;i<inputCharArray.length;i++){if(inputCharArray[i]==winningCombination[i]){totalCorrectCharacters++;}}returntotalCorrectCharacters;}privatestaticList<String>getWords(intdifficulty)throwsIOException{List<String>strings=readFile();List<String>sameLengthStrings=getSameLengthStrings(difficulty,strings);Set<String>randomWords=extractRandomStrings(sameLengthStrings);returnnewArrayList<String>(randomWords);}privatestaticList<String>readFile()throwsIOException{List<String>strings=newArrayList<String>();BufferedReaderbr=null;try{br=newBufferedReader(newFileReader("C:/javadev/tools/eclipse-4.3/workspace/sandbox/src/main/java/fallout/enable1.txt"));Stringline=br.readLine();while(line!=null){line=br.readLine();strings.add(line);}}catch(IOExceptione){e.printStackTrace();}finally{br.close();}returnstrings;}privatestaticSet<String>extractRandomStrings(List<String>sameLengthStrings){Set<String>randomWords=newHashSet<String>();Randomrandom=newRandom();//Return between 5 and 15 wordsintsetSize=random.nextInt(10)+5;while(randomWords.size()!=setSize){randomWords.add(sameLengthStrings.get(random.nextInt(sameLengthStrings.size())));}returnrandomWords;}privatestaticList<String>getSameLengthStrings(intdifficulty,List<String>strings){List<String>sameLengthStrings=newArrayList<String>();for(Stringstring:strings){if(string!=null&&string.length()==difficulty*2+DIFFICULTY_MULTIPLIER){sameLengthStrings.add(string);}}returnsameLengthStrings;}}
Top comments (0)
Subscribe
We're a place where coders share, stay up-to-date and grow their careers.
Top comments (0)