2014-11-28 4 views
0

Для этого проекта, который я делаю, я предполагаю использовать класс карты High Low и создать вокруг него gui. Я знаком с графическим интерфейсом и понимаю его, но проблема в том, что я не совсем уверен, как реализовать методы суперкласса (например: метод воспроизведения), чтобы появиться в текстовой области. Когда я вызываю Play(); метод приводит к выводу терминала и им интересно, как сделать так, чтобы текстовая область получала текст из методов.создание графического интерфейса вокруг суперкласса

Вот оригинальный 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 Графический Высокий Низкий я до сих пор для справки, я знаю код я сейчас не работает, но я надеялся, что кто-то мне точку в правильное направление.

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(); 
} 
} 

это требует карты и палубы класс, который правильно работает для меня, пожалуйста, помогите мне понять, домой, чтобы реализовать класс HighLow и обернуть GUI вокруг него, не воссоздавать механики в классе GHighLow.

спасибо, Dave

ответ

0

Вы можете начать с разделения игровой логики от GUI кода. Одной из главных причин создания такого подкласса является добавление функциональности (например, GUI) без перезаписи всего кода. В этом случае точкой класса GHighLow является добавление графического интерфейса к существующей игровой логике, которая реализуется HighLow.

Игровой механик будет кодом, который заставляет игру работать. Функция Play() является примером игровой механики. GUI - это окно, предназначенное для взаимодействия пользователей с игроками. В принципе, вы хотите разбить свой код на функции, чтобы функции графического интерфейса были отделены от функций игровой механики, как вы делали с Play() и PlayAgainPrompt(). Play() - игровая механика, но она вызывает функцию GUI (PlayAgainPrompt()). PlayAgainPrompt() использует терминал, чтобы спросить пользователя, хотят ли они продолжить, но что, если вы хотите диалоговое окно? Вы бы переопределили функцию и вместо этого использовали диалоговое окно. Для каждого бит кода, который должен обрабатываться графическим интерфейсом, вы должны поместить его в функцию, которая может быть переопределена для этого. Для каждого бита кода, который является частью игровой механики, он должен быть в своей собственной функции, поэтому его не нужно переписывать в подклассе.

Весь этот материал является частью концепции DRY, или не повторяйте себя. Код DRY - хороший код; если вы повторяете код, то позже его нужно изменить, крайне неприятно возвращаться и исправлять все это. Затем ошибки могут быть введены, если вы не исправите все это. Это одна из причин, почему подклассы настолько полезны. См. Вопрос this для получения дополнительной информации о DRY.

+0

Спасибо за ваш ответ, я понимаю функциональность высокого низкого класса, но я не уверен, как получить предварительно написанную механику для работы с gui –

+0

@DaveDiienno Я добавил больше информации об этом, надеюсь помогает. – FlyingPiMonster

+0

Огромное вам спасибо за то, что вы меня поняли логику, чтобы сделать это более понятным для меня –

Смежные вопросы