Write a program in java to play a word-guessing game like Hangman. Also please p
ID: 3692603 • Letter: W
Question
Write a program in java to play a word-guessing game like Hangman. Also please provide a output for this program it's the only way I can know for certain the program works.
Requirements:
It must randomly choose a word from a list of words. All words must be read from a data text file which contains at least 15 words. Each word includes at least 8 letters because it’s relatively easier to guess.
It must stop when all the letters are guessed. Program will ask player whether to keep going or quit.
It must give them limited tries and stop after they run out. (20 tries limitation)
It must display letters they have already guessed (either only the incorrect guesses or all guesses).
It must record player’s score and write the score into the score text file before user quit the game if the score belongs to the top 5 scores. That means the score file will store the 5 highest scores and the irrelative player names. At the beginning of the game, the top 5 scores list will be shown on the screen.
Score rules: 3 points for no missed letter,
2 points for 4 or less than 4 missed letters,
1 point for equal to or less than 7 tries.
Strategy:
(1) Define some array variables (or use ArrayList better) to contain word list, top five scores, and top five names.
(2) Define some String variables to contain guessed letters. Use string methods to print out every step guess.
(3) Define a variable to contain the score.
(4) At the beginning, program will read data file and score file and show score file content on the screen.
(5) Before program quits, it will compare the score player got to the top 5 scores. If the score is bigger than the fifth highest record, the top 5 records will be updated and the score file will be updated as well.
Hint:You may need to compare two string, but if they are not same type, a compare function can be created, in which program can compare each element and return a boolean value.
Hint: For input, Scanner can be used, but when program needs to read data from file, and when to read data from keyboard, the parameters are different. For example: Read data from file: File dataFile = new File(“data.txt”); Scanner input = new Scanner(dataFile); Read data from keyboard: Scanner input = new Scanner(System.in);
Hint: For output, Form atter can be used. For example: Formatter output = new Formatter(“score.txt”); output.format(“%d%d%s ", i+1, top5ScoreList.get(i),top5NameList.get(i)); System.out.printf(“%d%d%s ", i+1, top5ScoreList.get(i),top5NameList.get(i));
Output looks like the following:
This output is just an example. You may make it better.
Hint: To insert one value into an array, you may use ArrayList<> type and use add(index, name) method. For example:List<String> top5NameList = new ArrayList<String>(); top5NameList.add(index, name);
Word:-- eciicati Guess: n Word:__ Misses: Guess: Word:- eci_icatio Miasess Guess: P Word PeC cation Miosea: Gueas: u peciication Miasest 1u Guess: Word: PeCi ication Guesn:Explanation / Answer
Solution: See the code below:
---------------------------------------------------------
/**
*
*/
package wordguess;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import java.util.Scanner;
/**
* WordGuessDemo class
*
*/
public class WordGuessDemo {
ArrayList<String> wordList; // list of words
ArrayList<Integer> topScores; // top 5 scores
ArrayList<String> topNames; // Names of top 5 scorers
ArrayList<Character> guessedLetters; // guessed letter
String wordToGuess; // word to guess
int maxTries; // maximum no. of tries
int pointsEarned; // points earned, while guessing a word
// function to pick a word to guess
private String pickAWordToGuess() {
String word = null;
Random random = new Random(); // creates a random object
int wordIndex = random.nextInt(wordList.size());
word = (String) wordList.get(wordIndex);
return word;
}
// returns points earned
public int getPointsEarned() {
return pointsEarned;
}
// default constructor
public WordGuessDemo() {
// TODO Auto-generated constructor stub
wordList = new ArrayList<String>();
topScores = new ArrayList<Integer>();
topNames = new ArrayList<String>();
guessedLetters = new ArrayList<Character>();
wordToGuess = null;
maxTries = 20;
pointsEarned = 0;
}
// load words from data file
public void loadWords(String wordListFileName) {
try (BufferedReader br = new BufferedReader(new FileReader(wordListFileName))) {
String line = br.readLine();
while (line != null) {
wordList.add(line);
line = br.readLine();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// load top scores and names from score file
public void loadScoresAndNames(String scoresFileName) {
try (BufferedReader br = new BufferedReader(new FileReader(scoresFileName))) {
String line = br.readLine();
while (line != null) {
String[] tokens = line.split(" ");
String score = tokens[0];
String name = tokens[1];
topScores.add(Integer.parseInt(score));
topNames.add(name);
line = br.readLine();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// function to show top scores
public void showTopScores() {
Iterator<Integer> iterator = topScores.iterator();
while (iterator.hasNext()) {
int score = (int) iterator.next();
System.out.println(score);
}
}
// function to show top scores
public void showTopNames() {
Iterator<String> iterator = topNames.iterator();
while (iterator.hasNext()) {
String name = (String) iterator.next();
System.out.println(name);
}
}
// function to play the game
public void startWordGuessGame() {
wordToGuess = pickAWordToGuess();
int characters = wordToGuess.length();
int[] positionsToGuess = new int[characters];
int numOfPositionsToGuess = 0;
int numTries = 0, lettersMissed = 0;
boolean guessedRight = false;
System.out.println("Word to guess:");
Random random = new Random(); // creates a random object
for (int i = 0; i < characters; i++) {
int pos = random.nextInt(i + 1);
// System.out.println("pos:"+pos);
if (pos == i) {
System.out.print(" _ ");
positionsToGuess[numOfPositionsToGuess] = i;
numOfPositionsToGuess++;
} else {
System.out.print(" " + wordToGuess.charAt(i) + " ");
}
}
System.out.println(" Now start entering your guesses one by one. Max. tries=20");
Scanner input = new Scanner(System.in);
for (int i = 0; i < numOfPositionsToGuess; i++) {
System.out.print("Guess for pos " + (positionsToGuess[i] + 1) + ":");
char letter = input.next().charAt(0);
if (letter == wordToGuess.charAt(positionsToGuess[i])) {
System.out.println("You guessed right.");
guessedRight = true;
} else {
System.out.println("You guessed wrong.");
guessedRight = false;
lettersMissed++;
}
if (!guessedRight)
i--;
if (numTries >= maxTries) {
System.out.println("You exhausted all your tries. Stopping...");
break;
} else
numTries++;
}
// calculation of score
if (lettersMissed == 0)
pointsEarned += 3;
else if (lettersMissed <= 4)
pointsEarned += 2;
if (numTries <= 7)
pointsEarned += 1;
}
/**
* main function
*
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String dataFilePath = "./src/wordguess/data.txt";
String scoresFilePath = "./src/wordguess/scores.txt";
WordGuessDemo demo = new WordGuessDemo();
demo.loadWords(dataFilePath);
demo.loadScoresAndNames(scoresFilePath);
System.out.println("Top scores:");
demo.showTopScores();
System.out.println("Top names:");
demo.showTopNames();
// System.out.println("Word to guess:"+demo.pickAWordToGuess());
// loop for playing game
Scanner input = new Scanner(System.in);
while (true) {
System.out.println(" Press 1 to start/continue the game or 2 to quit.");
System.out.print("Choice:");
int choice = input.nextInt();
if (choice == 1) {
demo.startWordGuessGame();
} else if (choice == 2) {
input.close();
System.out.println("Your total score for this session:" + demo.getPointsEarned());
System.exit(0);
}
}
}
}
-----------------------------------------------------------
Data.txt:
elephant
umbrella
buzzword
dizzying
solution
oxymoron
hyperbole
accommodation
approximate
behaviour
neighbour
microsoft
skyrocket
particular
information
scores.txt:
20 John
19 Martin
18 James
17 Bruce
16 King
Note: This program doesn't compare the player's score with the top 5 scores on quitting. It just reports the score earned for the session. You will need to update the path of data.txt and scores.txt in the code as per your path.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.