过去几天我一直在为我的boggle游戏做最后的工作,我的大部分功能都在运行。不幸的是,尽管存在所述功能的代码,但仍有一些区域无法正常工作。无论我玩多少次游戏,程序都无法通知用户计算机找到多少单词,敲击随机选择的单词,并根据匹配的单词减少玩家的分数。
Boogle用户界面代码:
package userInterface;
/**
*
* @author Zac
*/
import core.Board;
import core.Die;
import java.util.Random;
import javax.swing.*;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
public final class BoggleUi {
private Board board;
private JFrame jframe;
//MenuBar
private JMenuBar menubar;
private JMenu boggle;
private JMenuItem game;
private JMenuItem exit;
//Boggle Panel
private Board boggleBoard;
private JPanel bogglePanel;
private ArrayList dictionaryData;//arraylist for dictionary
private ArrayList diceButtons;//arratlist for dicebuttons
ArrayList <String> wordsFoundbyPlayer = new ArrayList();
ArrayList <String> computersWords = new ArrayList();
private JButton[][] dieButton;
//Words Panel
private JPanel wordsPanel;
private JTextArea textArea;
private JScrollPane scrollPane;
private JLabel timerLabel;
private JButton Shakedice;
//InputPanel
private JPanel inputPanel;
private JLabel currentWord;
private JButton submitWord;
private JLabel currentScore;
int score = 0;
//Timer
private int seconds = 59;
private int minutes = 2;
Timer timeCounter;
//Current Word
String currentLetter = "";
String Letters = "";
int rows;
int cols;
private boolean[][] diceButtonCheck;
//style variables
JTextPane wordsArea;
BoggleStyleDoc document;
ArrayList <String> computerWords = new ArrayList();
boolean Randomwords[];
public BoggleUi(Board inBoard, ArrayList readDictionary)
{
diceButtons = new ArrayList();
board = inBoard;
System.out.println(readDictionary.size());
dictionaryData = readDictionary;
initComponents();
}
public void initComponents() {
jframe = new JFrame("Boggle");
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setSize(600, 500);
jframe.setMinimumSize(new Dimension(600 , 500));
menubar = new JMenuBar();
document = new BoggleStyleDoc();
//Menu
createMenu();
//Panels
BogglePanel();
WordPanel();
InputPanel();
//Adds Panels to Layout Manager(BorderLayout)
jframe.setJMenuBar( menubar);
jframe.add(bogglePanel, BorderLayout.WEST);
jframe.add(wordsPanel, BorderLayout.CENTER);
jframe.add(inputPanel, BorderLayout.SOUTH);
jframe.setVisible(true);
timeCounter= new Timer(1000, new TimeListener());
}
//Menu Bar
private void createMenu(){
menubar = new JMenuBar();
boggle = new JMenu("Boggle");
game = new JMenuItem("New Game");
game.addActionListener(new GameListener());
exit = new JMenuItem("Exit");
exit.addActionListener(new ExitListener());
boggle.add(game);
boggle.add(exit);
menubar.add(boggle);
}
//Boggle Panel
private void BogglePanel(){
bogglePanel = new JPanel(new GridLayout(4, 4));
bogglePanel.setMinimumSize(new Dimension(400, 400));
bogglePanel.setPreferredSize(new Dimension(400, 400));
bogglePanel.setBorder(BorderFactory.createTitledBorder("Boggle Board"));
ArrayList<Die> dice = board.shakeDice();//array list for dice
dieButton = new JButton[4][4];
diceButtonCheck= new boolean[4][4];
//dieButton.setFont(new Font("Arial", Font.PLAIN, 48));
for(int i=0; i<4; i++){//nested loop for 2d array
for(int j=0; j<4; j++){
String dieLetter = dice.get(4*i +j).getLetter();
dieButton[i][j] = new JButton(dieLetter);
dieButton[i][j].setFont(new Font("Arial", Font.PLAIN, 40));
bogglePanel.add(dieButton[i][j]);
dieButton[i][j].addActionListener(new DiceListener());
dieButton[i][j].setEnabled(false);
diceButtonCheck[i][j] = false;
}
}
}
//Word Panel
private void WordPanel(){
wordsPanel = new JPanel();
wordsPanel.setLayout(new BoxLayout(wordsPanel, BoxLayout.Y_AXIS));
wordsPanel.setBorder(BorderFactory.createTitledBorder("Enter Words Found"));
JPanel noWrapPanel = new JPanel();//new Jpanel for no wrap panel
wordsArea = new JTextPane();
//noWrapPanel.add(wordsArea);//adds the wordsarea to the no wrap panel
wordsArea.setEnabled(false);
scrollPane = new JScrollPane(wordsArea);
scrollPane.add(noWrapPanel);//adds no wrap panel to scroll pane
scrollPane.setPreferredSize(new Dimension(180, 330));
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
timerLabel = new JLabel("3:00");
timerLabel.setHorizontalAlignment(SwingConstants.CENTER);
timerLabel.setFont(new Font("Arial", Font.PLAIN, 45));
timerLabel.setPreferredSize(new Dimension(175, 75));
timerLabel.setMinimumSize(new Dimension(175, 75));
timerLabel.setMaximumSize(new Dimension(175, 75));
timerLabel.setBorder(BorderFactory.createTitledBorder("Time Left"));
Shakedice = new JButton("Shake Dice");
Shakedice.setPreferredSize(new Dimension(175, 50));
Shakedice.setMinimumSize(new Dimension(175, 50));
Shakedice.setMaximumSize(new Dimension(175, 50));
Shakedice.addActionListener(new ShakeListener());
Shakedice.setFont(new Font("Arial", Font.PLAIN, 20));
Shakedice.setEnabled(true);
wordsPanel.add(scrollPane);
wordsPanel.add(timerLabel);
wordsPanel.add(Shakedice);
}
//Input Panel
private void InputPanel(){
//setup input panel
inputPanel = new JPanel();
inputPanel.setLayout(new FlowLayout());
inputPanel.setBorder(BorderFactory.createTitledBorder("Current Word"));
currentWord = new JLabel();
currentWord.setPreferredSize(new Dimension(240, 50));
currentWord.setMinimumSize(new Dimension(240, 50));
currentWord.setMaximumSize(new Dimension(240, 50));
currentWord.setBorder(BorderFactory.createTitledBorder("Current Word"));
//set up submit word button
submitWord = new JButton("Submit Word");
submitWord.setPreferredSize(new Dimension(175, 50));
submitWord.setMinimumSize(new Dimension(175, 50));
submitWord.setMaximumSize(new Dimension(175, 50));
submitWord.addActionListener(new WordListener());
submitWord.setFont(new Font("Arial", Font.PLAIN, 20));
submitWord.setEnabled(false);
//setup score
currentScore = new JLabel();
currentScore.setPreferredSize(new Dimension(100, 50));
currentScore.setMinimumSize(new Dimension(100, 50));
currentScore.setMaximumSize(new Dimension(100, 50));
currentScore.setBorder(BorderFactory.createTitledBorder("Score"));
//adds current word, submit word and current score to the input panel
inputPanel.add(currentWord);
inputPanel.add(submitWord);
inputPanel.add(currentScore);
}
//Exit's the program
private class ExitListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e){
int response = JOptionPane.showConfirmDialog(null, "Confirm to exit Boggle?",
"Exit?", JOptionPane.YES_NO_OPTION);
if (response == JOptionPane.YES_OPTION)
System.exit(0);
}
}
//New Game( resets JTextArea, time to 3:00 on JLabel, and reenables shake dice button)
private class GameListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e){
wordsArea.setText("");
Shakedice.setEnabled(true);
submitWord.setEnabled(false);
wordsFoundbyPlayer.clear();
timerLabel.setText("3:00");
minutes=2;
seconds = 59;
timeCounter.stop();
//nested loop to disable the die button
for(int i = 0; i<4; i++ ){
for(int j = 0; j<4; j++){
dieButton[i][j].setEnabled(false);
diceButtonCheck[i][j] = false;
}
}
}
}
//Shakes Dice( shakes dice, starts the timer,
private class ShakeListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e){
ArrayList<Die> dice = board.shakeDice();
bogglePanel.removeAll();
bogglePanel.revalidate();
Shakedice.setEnabled(false);
submitWord.setEnabled(true);
timeCounter.start();
score = 0;
currentScore.setText(""+ score);
currentLetter = "";
currentWord.setText(currentLetter);
Collections.shuffle(dice);
dieButton = new JButton[4][4];
diceButtonCheck= new boolean[4][4];
for(int i=0; i<4; i++){
for(int j=0; j<4; j++){
String dieLetter = dice.get(4*i +j).getLetter();
dieButton[i][j] = new JButton(dieLetter);
dieButton[i][j].setFont(new Font("Arial", Font.PLAIN, 40));
bogglePanel.add(dieButton[i][j]);
dieButton[i][j].addActionListener(new DiceListener());
dieButton[i][j].setEnabled(true);
diceButtonCheck[i][j] = false;
}
}
}
}
//word listener
private class WordListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e){
int flag = 0; //flag varible
boolean validateWord = false;// variable to validate a word
for(int n = 0; n < wordsFoundbyPlayer.size(); n++){
if(wordsFoundbyPlayer.get(n).compareTo(currentLetter) == 0){
validateWord = true;
}
}
wordsArea.setDocument(document);
if(validateWord == false){
wordsFoundbyPlayer.add(currentLetter);
for(int i=0; i< dictionaryData.size(); i++){
if(currentLetter.equalsIgnoreCase(dictionaryData.get(i).toString())){
flag = 1;
int wordLength = currentLetter.length();
if(wordLength <= 2){
try {
document.insertString(0,"Word is too short!\n",null);
//internal try catch block
} catch (BadLocationException ex) {
Logger.getLogger(BoggleUi.class.getName()).log(Level.SEVERE, null, ex);
}
}
else if(wordLength <= 4){
try {
score += 1;
document.insertString(0,currentLetter+"\n",null);
} catch (BadLocationException ex) {
Logger.getLogger(BoggleUi.class.getName()).log(Level.SEVERE, null, ex);
}
}
else if(wordLength == 5){
try {
score += 2;
document.insertString(0,currentLetter+"\n",null);
} catch (BadLocationException ex) {
Logger.getLogger(BoggleUi.class.getName()).log(Level.SEVERE, null, ex);
}
}
else if(wordLength == 6){
try {
score += 3;
document.insertString(0,currentLetter+"\n",null);
} catch (BadLocationException ex) {
Logger.getLogger(BoggleUi.class.getName()).log(Level.SEVERE, null, ex);
}
}
else if(wordLength == 7){
try {
score += 5;
document.insertString(0,currentLetter+"\n",null);
} catch (BadLocationException ex) {
Logger.getLogger(BoggleUi.class.getName()).log(Level.SEVERE, null, ex);
}
}
else if(wordLength >= 8){
try {
score += 11;
document.insertString(0,currentLetter+"\n",null);
} catch (BadLocationException ex) {
Logger.getLogger(BoggleUi.class.getName()).log(Level.SEVERE, null, ex);
}
}
break;
}
}
//check if the word entered is vaild or not
if(flag == 0){
//surrounding try catch statement
try {
document.insertString(0,"Word is invalid!\n", null);
} catch (BadLocationException ex) {
Logger.getLogger(BoggleUi.class.getName()).log(Level.SEVERE, null, ex);
}
}
//for loop to caluate score based on length
for(int i = 0; i<4; i++ ){
for(int j = 0; j<4; j++){
dieButton[i][j].setEnabled(true);
diceButtonCheck[i][j] = false;
}
}
}
if(validateWord == true){
JOptionPane.showMessageDialog(null, "Word is a repeat!");
}
currentLetter = "";
currentWord.setText(currentLetter);
currentScore.setText(""+score);
}
}
//dice listener
private class DiceListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e){
JButton b;
Letters = e.getActionCommand();
b = (JButton)e.getSource();
currentLetter += Letters;
currentWord.setText(currentLetter);
for(int i = 0; i<4; i++ ){//nested loop for validation
for(int j = 0; j<4; j++){
dieButton[i][j].setEnabled(false);
if(b == dieButton[i][j]){
rows = i;
cols = j;
diceButtonCheck[i][j] = true;
}
}
}
for(int i = rows -1; i <= rows +1; i++ ){//nested loop to enable or disable the die button
for(int j = cols -1; j <= cols +1; j++ ){
if( i>=0 && i<4 && j>=0 && j<4) {
dieButton[i][j].setEnabled(true);
if(diceButtonCheck[i][j])
dieButton[i][j].setEnabled(false);
}
}
}
}
}
//Actionlistener for the timer
private class TimeListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e){
String s = String.format(" "+minutes+ ":" + "%02d", seconds);//concatenate minutes and seconds
timerLabel.setText(s);
seconds -=1;
if(seconds < 0){
seconds=59;
if(minutes == 0){
timeCounter.stop();
submitWord.setEnabled(false);//sets button to false
JOptionPane.showMessageDialog(null, "Game Over");//option pane for game over
JOptionPane.showMessageDialog(null, "The Computer will now compare its words to yours");
for(int i = 0; i<4; i++ ){
for(int j = 0; j<4; j++){
dieButton[i][j].setEnabled(false);
diceButtonCheck[i][j] = false;
}
}
return;
}
minutes--;
}
}
}
//method for random word selection
private void randomWordselect(){
Random randomWord = new Random();
int randWord = randomWord.nextInt(wordsFoundbyPlayer.size());
if(Randomwords[randWord] != true){
Randomwords[randWord] = true;
}
else{
randomWordselect();
}
}
//method for comparing the computer's words against the player's
private void ComputerCompare(){
Random rand = new Random();
int numAIWords = rand.nextInt(wordsFoundbyPlayer.size());
Randomwords = new boolean[wordsFoundbyPlayer.size()];
for(int j = 0; j < numAIWords; j++){
randomWordselect();
}
//for loop to set up strike through
for(int i = 0; i < wordsFoundbyPlayer.size(); i++ ){
StyleConstants.setStrikeThrough(document.getterStyle(), true);
wordsArea.setDocument(document);
}
//for loop with the switch case statement to decrement the player's score
for(int n = 0; n < wordsFoundbyPlayer.size(); n++){
if(Randomwords[n] == true){
System.out.println( "Word" + n + "of the Player's words were found");
StyleConstants.setStrikeThrough(document.getterStyle(), true);
wordsArea.setDocument(document);
int deduction = wordsFoundbyPlayer.get(n).length();
switch(deduction){
case 0:
case 1:
case 2:
score -=0;
break;
case 3:
case 4:
score -= 1;
break;
case 5:
score -= 2;
break;
case 6:
score -= 3;
break;
case 7:
score -= 5;
break;
default:
score -= 11;
break;
}
currentScore.setText(String.valueOf(score));
System.out.println("Your total score is" + score);
}
else{
StyleConstants.setStrikeThrough(document.getterStyle(),false);
wordsArea.setDocument(document);
}
try{//try catch for location
document.insertString(document.getLength(),wordsFoundbyPlayer.get(n) + "\n", null) ;
}
catch(Exception ex){
System.out.println("Bad Location");
}
}
}
// external private class for the default styled document
private class BoggleStyleDoc extends DefaultStyledDocument{
private Style primaryStyle;
public BoggleStyleDoc(){
super();
primaryStyle = this.addStyle("primary", null);
}
public Style getterStyle() {
return primaryStyle;
}
@Override
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException{
super.insertString(offs, str, primaryStyle);
}
}
}
你可以说一切看起来应该是正确的,但我仍然有问题。我相信错误是在wordsArea的一个实现中的某个地方,但我无法确定我需要在哪里进行修复。有人可以展示或告诉我如何解决问题吗?