davedno
davedno

Reputation: 349

creating a GUI around super class

For this project that im doing, i am suppose to utilize a High Low card game class and create a gui around it. I am familiar with making the GUI and understand it, but the problem is im not quite sure how to implement the superclass methods (ex: the play method) to appear in a text area. When i call the Play(); method it results in terminal output and im wondering how to make it so the text area receives the text from the methods.

Here is the original HighLow Class:

/**
 * Simulates a card game called High/Low using the classes Card, and Deck.
 * 
 * @author (Prof R) 
 * @version (v1.0 11/01/2014)
 */

import java.util.Scanner;
public class HighLow
{
private int     m_gamesPlayed;
private int     m_sumOfScores;

// Constructor to initialize all the data members
HighLow() 
{
    m_gamesPlayed  = 0;
    m_sumOfScores  = 0;
}

     /////////////////////////////////////////////////////////////////////////////////////////////////////
//
// This is the main loop of the of the game.  It calls the method to play a round of High-Low,
// and calls the methos to display the result when the round is over. It then will prompt the user to check
// if they want to continue. When the user stops playing it calls the method to display the final stats
//
// parameters: None
// return:     None
//
/////////////////////////////////////////////////////////////////////////////////////////////////////

public void Play() 
{
    boolean playAgain = true;                    // local variable representing status of "continue to play"

    while (playAgain) {
        int scoreThisGame;                // Score for one game.
        scoreThisGame = PlayARound();     // Play a round and get the score.
        m_sumOfScores += scoreThisGame;   // Sum up scores
        m_gamesPlayed++;                  // Sum up rounds played
        char c = PlayAgainPrompt();       // Prompt user to see if they want to continue

        if (c == 'Y') {
            playAgain = true;
        }
        else {
            playAgain = false;
        }
    }
    DisplayFinalStats();
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Prompts the user for fot Y/y or N/y with prompt "Do you want to play again?". 
//
// Paramters; none.
// return: char where Y is play again, or N is stop playing
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

protected char PlayAgainPrompt()
{
    Scanner in = new Scanner(System.in); 
    char c;
    do {
        System.out.println("Play again? ");
        String buffer;
        buffer = in.nextLine();
        c = buffer.charAt(0);
        c = Character.toUpperCase(c);
    } while (c != 'Y' && c != 'N');

    return c;
}

// Lets the user play a round HighLow, and returns the user's score in the game.
//
// Parameter: none
// return: an in reprsenting the number of correct guesses

private int PlayARound()
{     
    Scanner in = new Scanner(System.in); 

    Deck deck = new Deck();              // Get a new deck of cards
    Card currentCard;                    // The current card, which the user bases his guess off
    Card nextCard;                       // The next card in the deck, whic will determine outcome of user's guess
    int correctGuesses ;                 // variable for sum of correct guess
    char guess;                          // The user's guess.  'H/h' -higher, 'L/l' lower

    deck.Shuffle();                      // Shuffle the deck
    correctGuesses = 0;
    currentCard = deck.DealACard();      // Get a card from the top of the deck
    boolean correct = true;              // Loop will continue until this is false

    while (correct) {  // Loop ends when user's prediction is wrong.
        DisplayCurrentCard(currentCard);  // Call methos to display current card
        guess = GuessPrompt();            // Get the user's predition, 'H' or 'L'. 
        nextCard = deck.DealACard();      // Get next card from the deck
        DisplayNextCard(nextCard);        // Display the next card

        // Check the user's prediction. *

        if (nextCard.GetValue() == currentCard.GetValue()) {        // A tie
            DisplayResult("You lose on ties.  Sorry!");
            correct = false;                                         // End the round
        }
        else if (nextCard.GetValue() > currentCard.GetValue()) {    // Next card is higher
            if (guess == 'H') {
                DisplayResult("Your prediction was correct.");
                correctGuesses++;
            }
            else {
                DisplayResult("Your prediction was incorrect.");
                correct = false;                                     // End the round
            }
        }
        else {                                                      // nextCards is lower
            if (guess == 'L') {
                DisplayResult("Your prediction was correct.");
                correctGuesses++;
            }
            else {
                DisplayResult("Your prediction was incorrect.");
                correct = false;                                      // End round
            }
        }

        currentCard = nextCard;
        //System.out.println();
    } 
    DisplayStats(correctGuesses);

    return correctGuesses;
}

///////////////////////////////////////////////////////////////////////////////////////////////
//
// Display stats of a round of High/Low
//
// parameters: int correctGuesses - represents the number of corrects guesses for this round
// return: none.
//
////////////////////////////////////////////////////////////////////////////////////////////////

protected void DisplayStats(int correctGuesses)
{
    System.out.println();
    System.out.println("The game is over.");
    System.out.println("You made " + correctGuesses + " correct predictions.");
    System.out.println();

} 

//////////////////////////////////////////////////////////////////////////////////////////////
//
// Prompt the user for a guess with choices being H (next card will be higher), or 
// L (next card will be lower.  Displays prompt messages, and then gets the input from a scanner.
// The function will not return until the user inputs an H/h, or a L/l.
//
// parameters: none
// 
// return: a Char representing the user's guess.    

protected char GuessPrompt()
{
    Scanner in = new Scanner(System.in); 
    char guess;
    System.out.println("Will the next card be higher (H) or lower (L)?  ");
    do {
        String buffer;
        buffer = in.nextLine();
        guess = buffer.charAt(0);
        guess = Character.toUpperCase(guess);
        if (guess != 'H' && guess != 'L') {
            System.out.println("Please respond with H or L:  ");
        } 
    } while (guess != 'H' && guess != 'L');

    return guess;
}

///////////////////////////////////////////////////////////////////////////////////////////////
//
// Displays the current card that the user will base the guess of high or low from.
//
// parameters: card of type Card representing the last card dealt from the deck. The user
//             will guess if the next card delat is higher or lower than this.
// return: none
//
/////////////////////////////////////////////////////////////////////////////////////////////////

protected void DisplayCurrentCard(Card card) {
    System.out.println("The current card is " + card);    
}

///////////////////////////////////////////////////////////////////////////////////////////////
//
// Displays the next card dealt from the deck after the user's guess. This card will be capared to see if
// it is higher or lower than the last card dealt. 
//
// parameters: card of type Card representing the last card dealt from the deck. This card will be compared
// to the last card dealt, along with the user's guess to determine a right or wrong guess.
//
//////////////////////////////////////////////////////////////////////////////////////////////////////

protected void DisplayNextCard(Card card) {
    System.out.println("The next card is " + card);    
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Display result of a round of High/Low
//
// parameters: result of type String indicating whether the use won or lost based on the last card dealt,
//             the user guess.
// return: None
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

protected void DisplayResult(String result)
{
    System.out.println(result);
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Displays the finals stats of all the rounds of Hi/Low played (displays the average score) It computes
// the average score using the data members m_gamesPlayed, and m_sumOfScores.
//
// parameters: none.
// return type none.
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////

protected void DisplayFinalStats()
{
    double averageScore = m_sumOfScores / (double)m_gamesPlayed;
    System.out.println("Average score of " + averageScore + " for " + m_gamesPlayed + " rounds played. ");
}
}

Heres the Graphic High Low i have so far for reference, i know the code i have now does not work but i was hoping somebody would point me in the correct direction.

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GHighLow extends HighLow
{
private JFrame m_frame;
private JButton m_play;
private JButton m_exit;
private JButton m_high;
private JButton m_low;
private char m_k;
private JTextArea m_card1;
private JTextArea m_card2;
private JTextField m_input;

/**
 * Constructor for objects of class GHighLow
 */
public GHighLow()
{
    // constructs highlow
    super();

    // create inital frame
    m_frame = new JFrame();

    m_frame.setSize(400,400);   
    m_frame.setVisible(true);
    m_frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

    // inital button to play
    m_play = new JButton("Play!");

    // action listener from listener class
    m_play.addActionListener(new Listener());

    // button the recieve the players input
    m_high = new JButton("High");
    m_high.addActionListener(new Listener());

    m_low = new JButton("Low");
    m_low.addActionListener(new Listener());

    JPanel m_bottom = new JPanel();
    m_bottom.add(m_play);
    m_bottom.add(m_high);
    m_bottom.add(m_low);
    m_bottom.setBackground(Color.GREEN);
    m_frame.add(m_bottom, BorderLayout.SOUTH);

    // creates two graphic cards
    m_card1 = new JTextArea(10,10);
    m_card2 = new JTextArea(10,10);
    m_card1.setBackground(Color.BLUE);
    m_card2.setBackground(Color.BLUE);

    JPanel m_center = new JPanel();
    m_center.setBackground(Color.GREEN);
    m_center.add(m_card1);
    m_center.add(m_card2);

    m_frame.add(m_center, BorderLayout.CENTER);
    // instruction pane
    JOptionPane.showMessageDialog(null," *INSTRUCTIONS*" 
        + " The object of the High Low game is simple. The computer will present you a card" 
        + " All you have to do is guess if the next card is higher or lower, enjoy!");
}
public class Listener extends HighLow implements ActionListener {
    public void actionPerformed (ActionEvent e)

    {

        Object obj = e.getSource();

        if(obj == m_play){
            this.Play();

        }
        else if(obj == m_high) {
            m_k = 'H';

        }
        else if(obj == m_low){
            m_k = 'L';

        }
        else if(obj == m_exit){
            m_k = 'N';
        }
    }
}
public void Play(){

    super.Play();
}
}

this requires a card and deck class that are working properly for me, please help me figure out home to implement the HighLow class and wrap a GUI around it without recreating the mechanics in the GHighLow class.

thank you, Dave

Upvotes: 0

Views: 763

Answers (1)

James Westman
James Westman

Reputation: 2690

You may want to start by separating game logic from GUI code. One of the biggest reasons for creating a subclass like this is to add functionality (like a GUI) without rewriting all the code. The point of the GHighLow class in this case is to add a GUI to the existing game logic that is implemented by HighLow.

The game mechanics would be the code that makes the game work. The Play() function is an example of game mechanics. The GUI would be the window designed for users to interact with to play the game. Basically, you want to break your code up into functions so that GUI functions are separate from game mechanics functions, like you did with Play() and PlayAgainPrompt(). Play() is game mechanics, but it calls a GUI function (PlayAgainPrompt()). PlayAgainPrompt() uses the terminal to ask a user if they want to proceed, but what if you want a dialog box? You would override the function and use a dialog box instead. For each bit of code that should be handled by the GUI, you should put it in a function that can be overridden to do so. For each bit of code that is part of the game mechanics, it should be in its own function so it doesn't have to be rewritten in the subclass.

All this stuff is part of a concept called DRY, or don't repeat yourself. DRY code is good code; if you repeat code, then later need to change it, it is extremely annoying to go back and fix it all. Bugs can then be introduced if you don't fix it all. This is one reason why subclasses are so useful. See this question for more about DRY.

Upvotes: 0

Related Questions