Switching to GUI

posted in Event-driven engine for project Hangman
Published July 26, 2021
Advertisement

In the last post, I introduced the need of abstracting the input/output (and other dependencies) and how it would let us easily change the input/output without change our game.

We have replaced the console input/output by an AWT window and the code is almost the same.

Now, we request a canvas AWT for input and output that implements our interfaces.

package manager;

import gateways.IOFactory;
import hangman.Play;

public class Main {

	public static void main(String[] args) {

		IIOFactory factory = new IOFactory();
		//IInput in = factory.makeConsoleInput();
		IInput in = factory.makeCanvasAWTInput();
		//IOutput out = factory.makeConsoleOutput();
		IOutput out = factory.makeCanvasAWTOutput();
		
		out.printLine("HANGMAN. New Play.");
		
		int attempts = 7;
		Play hangman = new Play(attempts);
		
		String word = hangman.GetCurrentRevealedWord('_');		
		out.printLine(">>> " + word + " <<<");
		
		// 2. Game loop
		boolean success = false;
		while (attempts > 0 && !success) {
			
			// 2.1 User input
			char mchar = in.readChar();
			
			// 2.2 Logic check
			boolean result = hangman.Try(mchar);
			
			// 2.3 Win/Lose check
			success = hangman.isWordCompleatedRevealed();
			
			// 2.4 Output
			if ( true == result ) {
				word = hangman.GetCurrentRevealedWord('_');
				out.printLine(">>> " + word + " <<<");
				if ( success ) {
					out.printLine("YOU WIN");
				}
			} else {
				attempts--;
				if ( attempts > 0 ) {
					out.printLine("no " + mchar + ", try again. " + attempts + " left.");
				} else {					
					out.printLine("You lose. It was " + hangman.GetSecretWord());
				}
			}
		}
		
		// 3. Game close
		// extra key read to avoid windows closure
		in.readChar();
		System.exit(0);
		
	}
}

Here you can see some screenshoots of the game.

0 likes 0 comments

Comments

Nobody has left a comment. You can be the first!
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!
Profile
Author
Advertisement
Advertisement