Question

Problem Description: (Game: hangman) Write a JavaFX program that lets a user play the hangman game. The user guesses a word b
javafx assisantance confused on where to start
0 0
Add a comment Improve this question Transcribed image text
Answer #1

`Hey,

Note: If you have any queries related the answer please do comment. I would be very happy to resolve all your queries.

import javafx.animation.PathTransition;
import javafx.animation.Transition;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Arc;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.util.ArrayList;
public class Exercise_07 extends Application {

@Override
public void start(Stage primaryStage) throws Exception {

HangmanPane pane = new HangmanPane();

Scene scene = new Scene(pane, 400, 400);
scene.setOnKeyPressed(e-> {
pane.sendKeyCode(e.getCode());
});

primaryStage.setScene(scene);
primaryStage.setTitle("Hangman");
primaryStage.show();
}

private class HangmanPane extends Pane {

// List of words
private String[] words = {"Programming", "Computer", "Mac"};

private double w = 400;
private double h = 400;
private final int THRESHOLD = 7;

// Hanger
Line uL;
Line rL;
Line dL;

// Hangman
Circle head;
Line leftArm;
Line rightArm;
Line body;
Line leftLeg;
Line rightLeg;

String word;
ArrayList<Character> guessedLetters = new ArrayList<>();
ArrayList<Character> incorrectGuess = new ArrayList<>();

Label lblHiddenWord = new Label();
Label lblMissedLetters = new Label();
Label lblMessage = new Label();

boolean isPlaying = true;

PathTransition path;

HangmanPane() {
startGame();
}

private void startGame() {

getChildren().clear();
guessedLetters.clear();
incorrectGuess.clear();

if (path != null) {
path.stop();
}

word = getRandomWord();

lblHiddenWord.setText(getHiddenWord());
lblMissedLetters.setText("Missed letters: \n ");
lblMessage.setText("New Game: Make a guess!");

double x = w * 0.4;
double y = h * 0.8;
lblHiddenWord.setLayoutX(x);
lblHiddenWord.setLayoutY(y);

lblMissedLetters.setLayoutX(x);
lblMissedLetters.setLayoutY(y * 1.05);

lblMessage.setLayoutX(x);
lblMessage.setLayoutY(y * 1.15);

getChildren().addAll(lblHiddenWord, lblMissedLetters, lblMessage);
draw();
}

private void draw() {
// Bottom arc
Arc arc = new Arc(w * 0.2, h * 0.9, w * 0.15, h * 0.15, 0, 180);
arc.setFill(Color.TRANSPARENT);
arc.setStroke(Color.BLACK);

// Upward line
uL = new Line(arc.getCenterX(), arc.getCenterY() - arc.getRadiusY(), arc.getCenterX(), h * 0.05);
// Rightward line
rL = new Line(uL.getEndX(), uL.getEndY(), w * 0.6, uL.getEndY());
// Downward line
dL = new Line(rL.getEndX(), rL.getEndY(), rL.getEndX(), rL.getEndY() + h * 0.1);

getChildren().addAll(arc, uL, rL, dL);

for (int i = 1; i <= guessedLetters.size(); i++) {
drawHangman(i);
}
}

private void drawHangman(int guesses) {
switch (guesses) {
case 1: drawHead(); break;
case 2: drawBody(); break;
case 3: drawLeftArm(); break;
case 4: drawRightArm(); break;
case 5: drawLeftLeg(); break;
case 6: drawRightLeg(); break;
case 7: animateHang(); break;
}
}

private void animateHang() {

head.translateXProperty().addListener((observable, oldValue, newValue) -> {
body.setTranslateX(newValue.doubleValue());
leftArm.setTranslateX(newValue.doubleValue());
rightArm.setTranslateX(newValue.doubleValue());
leftLeg.setTranslateX(newValue.doubleValue());
rightLeg.setTranslateX(newValue.doubleValue());
});

head.translateYProperty().addListener((observable, oldValue, newValue) -> {
body.setTranslateY(newValue.doubleValue());
leftArm.setTranslateY(newValue.doubleValue());
rightArm.setTranslateY(newValue.doubleValue());
leftLeg.setTranslateY(newValue.doubleValue());
rightLeg.setTranslateY(newValue.doubleValue());
});


Arc arc = new Arc(dL.getEndX(), dL.getEndY() + head.getRadius() - 10, 20, 10, 220, 85);
arc.setFill(Color.TRANSPARENT);
arc.setStroke(Color.BLACK);
path = new PathTransition(Duration.seconds(3), arc, head);
path.setCycleCount(Transition.INDEFINITE);
path.setAutoReverse(true);
path.setOrientation(PathTransition.OrientationType.ORTHOGONAL_TO_TANGENT);
path.play();
}

private void drawHead() {
double radius = w * 0.1;
head = new Circle(dL.getEndX(), dL.getEndY() + radius, radius, Color.TRANSPARENT);
head.setStroke(Color.BLACK);
getChildren().add(head);
}

private void drawBody() {
double startY = head.getCenterY() + head.getRadius();
double x = head.getCenterX();
body = new Line(x, startY, x, startY + h * 0.25);
this.getChildren().add(body);
}

private void drawLeftArm() {
leftArm = createArm(-1, 225);
this.getChildren().add(leftArm);
}

private void drawRightArm() {
rightArm = createArm(1, 315);
this.getChildren().add(rightArm);
}

private void drawLeftLeg() {
leftLeg = createLeg(-1);
this.getChildren().add(leftLeg);
}

private void drawRightLeg() {
rightLeg = createLeg(1);
this.getChildren().add(rightLeg);
}

private Line createLeg(int dX) {
double x = body.getEndX();
double y = body.getEndY();
return new Line(x, y, x + head.getRadius() * dX, y + w * 0.2);
}

private Line createArm(int dX, double angle) {
double radius = head.getRadius();
double x = head.getCenterX() + radius * Math.cos(Math.toRadians(angle));
double y = head.getCenterY() - radius * Math.sin(Math.toRadians(angle));
return new Line(x, y, x + radius * dX, y + radius * 1.5);
}

private boolean makeGuess(char ch) {

if (!isPlaying) return false;

// Check if guess has been used
if (isRepeatedGuess(ch)) {
lblMessage.setText(ch + " has already been used! Try again.");
return false; // return false on repeated guesses
}

// Add letter to guess history
guessedLetters.add(ch);

String newWord = getHiddenWord(); // retrieve new word
// Check if guess is correct
// if newWord == hidden word then guess was incorrect
if (newWord.equalsIgnoreCase(lblHiddenWord.getText())) {

incorrectGuess.add(ch); // keep track of incorrect guesses

if ((incorrectGuess.size() == THRESHOLD)) { // Player dies IN REAL LIFE jk jk lolol
lblMessage.setText("You lost! Press enter to try again.");
isPlaying = false; // Player can't make a guess until he presses enter
} else {
lblMessage.setText(ch + " is incorrect guess! \nYou have " + (THRESHOLD - incorrectGuess.size()) + " lives left.");
}
lblMissedLetters.setText(lblMissedLetters.getText() + Character.toLowerCase(ch));
drawHangman(incorrectGuess.size()); // draw hangman
return false; // return false on incorrect guess
} else {
// Code reaches here if guess is correct
lblHiddenWord.setText(newWord);
String s = "Correct!";
// Check if user won the game
if (newWord.equalsIgnoreCase(word)) {
s += " You won the game! \n Press Enter to continue";
isPlaying = false;
}
lblMessage.setText(s);
}
return true;
}

public void sendKeyCode(KeyCode key) {
if (key == KeyCode.ENTER && !isPlaying) {
isPlaying = true;
startGame();
} else if (key.isLetterKey()) {
makeGuess(key.getName().charAt(0));
}
}

private boolean isRepeatedGuess(char ch) {
ch = Character.toUpperCase(ch);
for (char letter : guessedLetters) {
if (letter == ch) {
return true;
}
}
return false;
}

private String getHiddenWord() {

String s = "";
for (int i = 0; i < word.length(); i++) {
boolean isMatched = false;
for (char ch : guessedLetters) {
if (Character.toLowerCase(ch) == Character.toLowerCase(word.charAt(i))) {
s += word.charAt(i);
isMatched = true;
break;
}
}
if (!isMatched) {
s += "*";
}
}
return s;
}

private String getRandomWord() {
return words[(int) (Math.random() * words.length)];
}
}

public static void main(String[] args) {
Application.launch(args);
}

}

M Inbox - gurkaranpreet.singh.me x C Javafx Assisantance Confused On X <> Online Java Compiler - Online Ja x C My Q&A | Chegg

Kindly revert for any queries

Thanks.

Add a comment
Know the answer?
Add Answer to:
javafx assisantance confused on where to start Problem Description: (Game: hangman) Write a JavaFX program that...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • JAVA PROGRAMMING (Game: hangman) Write a hangman game that randomly generates a word and prompts the...

    JAVA PROGRAMMING (Game: hangman) Write a hangman game that randomly generates a word and prompts the user to guess one letter at a time, as shown in the sample run. Each letter in the word is displayed as an asterisk. When the user makes a correct guess, the actual letter is then displayed. When the user finishes a word, display the number of misses and ask the user whether to continue to play with another word. Declare an array to...

  • C++ Hangman (game) In this project, you are required to implement a program that can play...

    C++ Hangman (game) In this project, you are required to implement a program that can play the hangman game with the user. The hangman game is described in https://en.wikipedia.org/wiki/Hangman_(game) . Your program should support the following functionality: - Randomly select a word from a dictionary -- this dictionary should be stored in an ASCII text file (the format is up to you). The program then provides the information about the number of letters in this word for the user to...

  • Overview In this exercise you are going to recreate the classic game of hangman. Your program...

    Overview In this exercise you are going to recreate the classic game of hangman. Your program will randomly pick from a pool of words for the user who will guess letters in order to figure out the word. The user will have a limited number of wrong guesses to complete the puzzle or lose the round. Though if the user answers before running out of wrong answers, they win. Requirements Rules The program will use 10 to 15 words as...

  • For a C program hangman game: Create the function int play_game [play_game ( Game *g )]...

    For a C program hangman game: Create the function int play_game [play_game ( Game *g )] for a C program hangman game. (The existing code for other functions and the program is below, along with what the function needs to do) (Also the link to program files (hangman.h and library file) is below the existing code section. You can use that to check if the code works) What int play_game needs to do mostly involves calling other functions you've already...

  • Create the game hangman using c code: Program description In the game of hangman, one player...

    Create the game hangman using c code: Program description In the game of hangman, one player picks a word, and the other player has to try to guess what the word is by selecting one letter at a time. If they select a correct letter, all occurrences of the letter are shown. If no letter shows up, they use up one of their turns. The player is allowed to use no more than 10 incorrect turns to guess what the...

  • Write a MATLAB code for the hangman game below you might break the problem down into:...

    Write a MATLAB code for the hangman game below you might break the problem down into: Selecting a word from a dictionary. ‘aardvark’ Reading a single letter from the user like ‘a’ Building a character array showing the letters matched so far like ‘aa---a--’ Keeping count of the number of guessed letters so far. Keeping count of the number of guesses so far. Writing conditional logic to see whether the game is finished or not.

  • Help please, write code in c++. The assignment is about making a hangman game. Instructions: This...

    Help please, write code in c++. The assignment is about making a hangman game. Instructions: This program is part 1 of a larger program. Eventually, it will be a complete Hangman game. For this part, the program will Prompt the user for a game number, Read a specific word from a file, Loop through and display each stage of the hangman character I recommend using a counter while loop and letting the counter be the number of wrong guesses. This...

  • Hangman is a game for two or more players. One player thinks of a word, phrase...

    Hangman is a game for two or more players. One player thinks of a word, phrase or sentence and the other tries to guess it by suggesting letters or numbers, within a certain number of guesses. You have to implement this game for Single Player, Where Computer (Your Program) will display a word with all characters hidden, which the player needed to be guessed. You have to maintain a dictionary of Words. One word will be selected by your program....

  • hey dear i just need help with update my code i have the hangman program i...

    hey dear i just need help with update my code i have the hangman program i just want to draw the body of hang man when the player lose every attempt program is going to draw the body of hang man until the player lose all his/her all attempts and hangman be hanged and show in the display you can write the program in java language: this is the code bellow: import java.util.Random; import java.util.Scanner; public class Hangmann { //...

  • JAVA Hangman Your game should have a list of at least ten phrases of your choosing.The...

    JAVA Hangman Your game should have a list of at least ten phrases of your choosing.The game chooses a random phrase from the list. This is the phrase the player tries to guess. The phrase is hidden-- all letters are replaced with asterisks. Spaces and punctuation are left unhidden. So if the phrase is "Joe Programmer", the initial partially hidden phrase is: *** ********** The user guesses a letter. All occurrences of the letter in the phrase are replaced in...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT