对于我正在做的这个项目,我想要利用一个High Low牌游戏类并围绕它创建一个gui。我熟悉制作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. ");
}
}
图片高低我到目前为止参考,我知道我现在的代码不起作用,但我希望有人会指出我正确的方向。
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类中的机制。
谢谢你, 戴夫答案 0 :(得分:0)
您可能希望从游戏逻辑与GUI代码分离开始。创建这样的子类的最大原因之一是添加功能(如GUI)而不重写所有代码。在这种情况下,GHighLow
类的要点是将GUI添加到HighLow
实现的现有游戏逻辑中。
游戏机制将是使游戏运作的代码。 Play()
函数是游戏机制的一个例子。 GUI将是为用户进行交互以玩游戏而设计的窗口。基本上,您希望将代码分解为函数,以便GUI函数与游戏机制函数分开,就像您使用Play()
和PlayAgainPrompt()
一样。 Play()
是游戏机制,但它调用GUI函数(PlayAgainPrompt()
)。 PlayAgainPrompt()
使用终端询问用户是否要继续,但如果您想要一个对话框怎么办?您将覆盖该函数并改为使用对话框。对于应由GUI处理的每一段代码,您应该将其放在一个可以重写的函数中。对于作为游戏机制一部分的每一段代码,它应该在它自己的函数中,因此不必在子类中重写。
所有这些都是DRY概念的一部分,或者不要重复。 DRY代码是很好的代码;如果你重复代码,然后需要改变它,回去修复它是非常烦人的。如果你不解决所有错误,那么就可以引入错误。这是子类如此有用的一个原因。有关DRY的更多信息,请参阅this问题。