简体   繁体   English

围绕超类创建GUI

[英]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. 对于这个我正在做的项目,我想利用高低纸牌游戏类并围绕它创建一个GUI。 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. 我熟悉制作GUI并理解它,但是问题不是很确定如何实现超类方法(例如play方法)以出现在文本区域中。 When i call the Play(); 当我调用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: 这是原始的HighLow类:

/**
 * 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. 这需要一个适合我的卡和套牌类,请帮助我弄清楚在家里实现HighLow类并在其周围包装一个GUI而不重新创建GHighLow类的机制。

thank you, Dave 谢谢戴夫

You may want to start by separating game logic from GUI code. 您可能首先需要将游戏逻辑与GUI代码分开。 One of the biggest reasons for creating a subclass like this is to add functionality (like a GUI) without rewriting all the code. 创建这样的子类的最大原因之一是在不重写所有代码的情况下添加功能(如GUI)。 The point of the GHighLow class in this case is to add a GUI to the existing game logic that is implemented by HighLow . 在这种情况下, GHighLow类的GHighLow是将GUI添加到由HighLow实现的现有游戏逻辑中。

The game mechanics would be the code that makes the game work. 游戏机制就是使游戏正常运行的代码。 The Play() function is an example of game mechanics. Play()函数是游戏机制的一个示例。 The GUI would be the window designed for users to interact with to play the game. GUI将是供用户交互以玩游戏的窗口。 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() . 基本上,您希望将代码分解为函数,以便GUI函数与游戏机制函数分开,就像您对Play()PlayAgainPrompt()所做的那样。 Play() is game mechanics, but it calls a GUI function ( PlayAgainPrompt() ). Play()是游戏机制,但是它调用GUI函数( PlayAgainPrompt() )。 PlayAgainPrompt() uses the terminal to ask a user if they want to proceed, but what if you want a dialog box? PlayAgainPrompt()使用终端询问用户是否要继续,但是如果要对话框怎么办? 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. 对于GUI应该处理的每一位代码,都应将其放在可以重写的函数中。 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概念的一部分,或者不要重复自己 DRY code is good code; DRY代码是好的代码; 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. 这个问题的更多信息DRY。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM