Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //simple Hangman game
- import javax.swing.*;
- import java.util.*;
- import java.text.*;
- public class hangman {
- char[] correctChars;
- int letterCounter;
- String secretWord;
- int triesLeft = 10;
- final char BLANK = '-';
- ArrayList checkIfWon;
- int timesPlayed;
- public hangman() {
- timesPlayed = 1;
- }
- public static void main(String[] args) {
- hangman game = new hangman();
- game.play();
- }
- public void startup() {
- if (timesPlayed % 2 == 0) {
- secretWord = JOptionPane.showInputDialog("Player 2, enter a secret word:");
- } else {
- secretWord = JOptionPane.showInputDialog("Player 1, enter a secret word:");
- }
- correctChars = new char[secretWord.length()];
- letterCounter = 0;
- checkIfWon = new ArrayList();
- for (int i = 0; i < secretWord.length(); i++) {
- System.out.print("-");
- }
- System.out.println();
- }
- public void defaultCorrectChars() {
- for (int i = 0; i < correctChars.length; i++) {
- correctChars[i] = BLANK;
- }
- }
- public void play() {
- startup();
- defaultCorrectChars();
- int answer;
- String guess;
- while (true) {
- if (timesPlayed % 2 == 0) {
- guess = JOptionPane.showInputDialog("Player 1, guess a letter:");
- } else {
- guess = JOptionPane.showInputDialog("Player 2, guess a letter:");
- }
- for (int j = 0; j < secretWord.length(); j++) {
- if (secretWord.substring(j, j+1).equalsIgnoreCase(guess)) { // adds new guessed letter
- correctChars[j] = guess.charAt(0);
- System.out.print(guess);
- letterCounter++;
- } else if (correctChars[j] != BLANK) { // re-adds correctly guessed letters
- System.out.print(correctChars[j]);
- } else {
- System.out.print("-");
- }
- }
- if (letterCounter == 0) {
- System.out.println();
- System.out.println("Sorry there were no " +guess+"(s). You lost a try.");
- System.out.println();
- triesLeft--;
- if (triesLeft == 0) {
- JOptionPane.showMessageDialog(null, "You're all out of tries, better luck next time!\nThank you for playing.");
- System.exit(0);
- }
- } else {
- for (int b = 0; b < letterCounter; b++) {
- checkIfWon.add(new Boolean(true));
- }
- if (checkIfWon.size() == secretWord.length()) {
- JOptionPane.showMessageDialog(null, "Congratulations, you solved the secret word.");
- answer = Integer.parseInt(JOptionPane.showInputDialog("Would you like to play again? (0 for yes, 1 for no"));
- if (answer == 0) {
- timesPlayed++;
- play();
- } else {
- JOptionPane.showMessageDialog(null, "Thanks for playing!");
- System.exit(0);
- }
- }
- System.out.println();
- System.out.println("There were " + letterCounter + " " + guess + "(s)" + " in the secret word");
- System.out.println();
- }
- letterCounter = 0;
- }
- }
- }
Add Comment
Please, Sign In to add comment