Question

This task involves constructing a Java program that supports interaction via a graphical user interface.The object...

This task involves constructing a Java program that supports interaction via a graphical user interface.The object is to implement a Scrabble graphical game. The basis for the game is quite simple. Presented with a 6x6 grid of Scrabble tiles, the challenge is for the player(s) to form as many high scoring words as possible.


 Words may only be formed from sequences of adjacent tiles.
 Two tiles are adjacent if their edges or corners meet.
 A tile may be used in at most one word.
-one letter words accepted too.


Beyond these simple rules, there are no limits to the form of the game.
 It could be played by one or more people.
 There could be a time limit.
 There are a variety of ways in which scores can be calculated.
 When a tile is used, ‘consumed’ even, it could be replaced with a fresh tile.
Any form of the game that is desired may be implemented.
 The baseline is a single player game where the player simply seeks to get a good score.
 Creativity is highly recommended.

Resources
Tile class

public class Tile {

private char letter;
private int value;

/**
* Create a Tile for the given letter and value.
*/
public Tile(char letter, int value) {
this.letter = letter;
this.value = value;
}

/**
* Obtain the letter on this tile.
*/
public char letter() { return letter;}
  
/**
* Obtain the value of this letter tile.
*/
public int value() { return value;}

/**
* Obtain a String representation of this tile.
*/
public String toString() {
return "("+letter+", "+value+")";
}
}

TileCollection class

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.Random;

public class TileCollection {

private static int totalTiles() {
int total = 0;
for (int tileNumber=0; tileNumber<FREQUENCY.length; tileNumber++) {

total=total+FREQUENCY[tileNumber];
}
return total;
}

private final static char[] LETTER = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H','I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T','U', 'V', 'W', 'X', 'Y','Z'};
private final static int[] FREQUENCY = {9, 2, 2, 4, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1};
private final static int[] VALUE = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};

private static Tile[] makeTileArray() {

Tile[] tiles = new Tile[totalTiles()];
int instanceIndex = 0;
  
for (int tileNumber=0; tileNumber<LETTER.length; tileNumber++) {
char tileLetter = LETTER[tileNumber];
int tileValue = VALUE[tileNumber];
  
for (int instances=0; instances<FREQUENCY[tileNumber]; instances++) {
tiles[instanceIndex] = new Tile(tileLetter, tileValue);
instanceIndex++;
}
}
return tiles;
}

private static void shuffleTiles(Tile[] tileArray) {

Random random = new Random();
int numberOfRuns = tileArray.length;

while (numberOfRuns>0) {

numberOfRuns--;

for (int index=0; index<tileArray.length-1; index++) {
  
int destination = random.nextInt(tileArray.length);

Tile tile = tileArray[destination];
tileArray[destination] = tileArray[index];
tileArray[index]=tile;
}
}
}

/* **************** Instance variables and methods *************** */
private List<Tile> collection;
  
/**
* Create a new collection of scrabble tiles.
*/
public TileCollection() {

Tile[] tileArray = makeTileArray();
shuffleTiles(tileArray);
this.collection = new ArrayList<Tile>(Arrays.asList(tileArray));
}

/**
* Remove a randomly chosen tile from the collection.
* @throws NoSuchElementException if the collection is empty.
*/
public Tile removeOne() {

if (this.size()==0) {
throw new NoSuchElementException("TileCollection:removeOne(): collection is empty");
}
else {
return collection.remove(0);
}
}

/**
* Obtain the number of tiles remaining in the collection.
*/
public int size() {
return collection.size();
}
}

TileGUI class

import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Container;

public class TileGUI extends JButton {

private Tile model;

/**
* Create a TileGUI object that provides a graphical representation for the given Tile.
*/
public TileGUI(Tile tile) {
super();
model = tile;
setText(makeHTML(super.getForeground(), tile));
this.setContentAreaFilled(true);
}

private static String setTwoDigits(String string) {
if (string.length()==1) {
return "0"+string;
}
else if (string.length()==2) {
return string;
}
else {
throw new IllegalArgumentException("TileGUI:setTwoDigits("+string+"): more than two digits");
}
}

private static String makeHTML(Color colour, Tile tile) {

String redString = Integer.toHexString(colour.getRed());
String greenString = Integer.toHexString(colour.getGreen());
String blueString = Integer.toHexString(colour.getBlue());
redString = setTwoDigits(redString);
greenString = setTwoDigits(greenString);
blueString = setTwoDigits(blueString);

StringBuffer result = new StringBuffer();
result.append("<html><font color=\"#");
result.append(redString);
result.append(greenString);
result.append(blueString);
result.append("\" size=\"+5\">"+tile.letter()+"</font><sub>"+tile.value()+"</sub>");
return result.toString();
}

/**
* Set the foreground colour for this graphical component.
*/
public void setForeground(Color colour) {
super.setForeground(colour);
if (model!=null) {
this.setText(makeHTML(colour, model));
}
}

/**
* Obtain the Tile object graphically represented by this TileGUI object.
*/
public Tile getTile() { return model; }

/**
* Test program for TileGUI.
*
* Creates a JFrame with a TileGUI within it. The tile displayed is an 'A'
* with value 2. The foreground colour is yellow.
*
*/
public static void main(String[] args) {
JFrame frame = new JFrame("Test Script for TileGUI");
TileGUI gui = new TileGUI(new Tile('A', 2));
gui.setForeground(Color.yellow);
frame.getContentPane().add(gui);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}


 A Tile object represents a Scrabble tile.
 A TileCollection represents a bag of Scrabble tiles.
 A TileGUI object may be used to provide a graphical representation of a Tile.

FileToArray

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileToArray {


private final static String START_LABEL = "START";

/**
* Constructs a word list from the named file. The file should be
* organized such that there is a single word per line.
*
* The file is assumed to contain a preamble such as a copyright notice.
* The beginning of the data should be marked by a line containing
* the single word "START".
*
* @throws FileNotFoundException if unable to open the named file.
* @throws IOException if some error occurs during reading of the file (uncommon).
*/
public static String[] read(String filename) throws IOException, FileNotFoundException {
BufferedReader buffer = new BufferedReader(new FileReader(filename));

String line = buffer.readLine();
while (! line.equals(START_LABEL) ) {
line = buffer.readLine();
}

List<String> words = new ArrayList<String>();
line = buffer.readLine();
  
while (line !=null) {
words.add(line.trim());
line = buffer.readLine();
}
buffer.close();
String[] arrayResult = new String[words.size()];
arrayResult = words.toArray(arrayResult);
return arrayResult;
}

/**
* Test harness for the read method.
*/
public static void main(String[] args) {
// File name in args[0].
try {
String[] results = FileToArray.read(args[0]);
for (String word : results) {
System.out.println(word);
}
}
catch (Exception exception) {
System.out.println("Whoops, file error:");
System.out.println(exception);
}
}
}


-The game requires a lexicon of words with which to check a player’s selection. Make sure that the there is a use of a any given text file given e.g. 'SpanishWords.txt' or ‘EnglishWords.txt’.
The class contains a static class method called “read’. Use it like:
String[] words = FileToArray.read(“SpanishWords.txt”);
-Provide an exception handling when error occurs.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

scrabble game:

I have implemented it using array list

public class Scrabble {

public static ArrayList<String> numbers = new ArrayList<String>();
public static ArrayList<String> numbers2 = new ArrayList<String>() {
};

public static void main(String[] args) {
Scanner dict = null;

try {
dict = new Scanner(new File("SpanishWords.txt"));
} catch (FileNotFoundException ex) {
}

while (dict.hasNextLine()) {

numbers.add(dict.nextLine());
}

String n = "gojy";//random text here

rearrange("", n);
LinkedHashSet<String> listToSet = new LinkedHashSet<String>(numbers2);
ArrayList<String> listWithoutDuplicates = new ArrayList<String>(listToSet);
for (int i = 0; i < listWithoutDuplicates.size(); i++) {

if (numbers.contains(listWithoutDuplicates.get(i))) {
System.out.println(listWithoutDuplicates.get(i));
}
}

}

public static void rearrange(
String q, String w) {
if (w.length() <= 1) {
String k = q + w;
numbers2.add(k);//full word
numbers2.add(q);//smaller combination to get words with less letters. doesn't work too well
} else {

for (int i = 0; i < w.length(); i++) {

String c = w.substring(0, i)
+ w.substring(i + 1);

rearrange(q
+ w.charAt(i), c);

}
}
}
}

Add a comment
Know the answer?
Add Answer to:
This task involves constructing a Java program that supports interaction via a graphical user interface.The object...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I've previously completed a Java assignment where I wrote a program that reads a given text...

    I've previously completed a Java assignment where I wrote a program that reads a given text file and creates an index that stores the line numbers for where individual words occur. I've been given a new assignment where I need to modify some of my old code. I need to replace the indexer in my Index class with a NavigableMap<String, Word> and update my Word class with NavigableSet<Integer> lines. The instantiated objects should be TreeMap() and TreeSet(). I have below...

  • Original question IN JAVA Show the user a number of blank spaces equal to the number...

    Original question IN JAVA Show the user a number of blank spaces equal to the number of letters in the word For cat, you would show _ _ _. Prompt a user to guess a letter until they have run out of guesses or guessed the full word By default, the user should be able to make 7 failed guesses before they lose the game. If the user guesses a letter that is in the target word, it does not...

  • Java programming How do i change this program to scan data from file and find the...

    Java programming How do i change this program to scan data from file and find the sum of the valid entry and count vaild and invalid entries The provided data file contains entries in the form ABCDE BB That is - a value ABCDE, followed by the base BB. Process this file, convert each to decimal (base 10) and determine the sum of the decimal (base 10) values. Reject any entry that is invalid. Report the sum of the values...

  • In this practice program you are going to practice creating graphical user interface controls and placing...

    In this practice program you are going to practice creating graphical user interface controls and placing them on a form. You are given a working NetBeans project shell to start that works with a given Invoice object that keeps track of a product name, quantity of the product to be ordered and the cost of each item. You will then create the necessary controls to extract the user input and display the results of the invoice. If you have any...

  • Write a program in Java that prompts a user for Name and id number. and then...

    Write a program in Java that prompts a user for Name and id number. and then the program outputs students GPA MAIN import java.util.StringTokenizer; import javax.swing.JOptionPane; public class Main {    public static void main(String[] args) {                       String thedata = JOptionPane.showInputDialog(null, "Please type in Student Name. ", "Student OOP Program", JOptionPane.INFORMATION_MESSAGE);        String name = thedata;        Student pupil = new Student(name);                   //add code here       ...

  • Help! Not sure how to create this java program to run efficiently. Current code and assignment...

    Help! Not sure how to create this java program to run efficiently. Current code and assignment attached. Assignment :Write a class Movies.java that reads in a movie list file (movies.txt). The file must contain the following fields: name, genre, and time. Provide the user with the options to sort on each field. Allow the user to continue to sort the list until they enter the exit option. ---------------------------------------------------------- import java.util.*; import java.io.*; public class Movies { String movieTitle; String movieGenre;...

  • FOR JAVA: Summary: Create a program that adds students to the class list (see below). The...

    FOR JAVA: Summary: Create a program that adds students to the class list (see below). The solution should be named Roster402_v2.java. Allow the user to control the number of students added to the roster. Ask if the user would like to see their new roster to confirm additions. If yes, then display contents of the file, if no, end the program. ------------------------------------------------------------------------------------- List of student names and IDs for class (this will be your separate text file): Jones, Jim,45 Hicks,...

  • Make a FLOWCHART for the following JAVA Prime Number Guessing Game. import java.util.Random; import java.util.Scanner; public...

    Make a FLOWCHART for the following JAVA Prime Number Guessing Game. import java.util.Random; import java.util.Scanner; public class Project2 { //Creating an random class object static Random r = new Random(); public static void main(String[] args) {    char compAns,userAns,ans; int cntUser=0,cntComp=0; /* * Creating an Scanner class object which is used to get the inputs * entered by the user */ Scanner sc = new Scanner(System.in);       System.out.println("*************************************"); System.out.println("Prime Number Guessing Game"); System.out.println("Y = Yes , N = No...

  • Modify the program that you wrote for the last exercise in a file named Baseball9.java that...

    Modify the program that you wrote for the last exercise in a file named Baseball9.java that uses the Player class stored within an array. The program should read data from the file baseball.txt for input. The Player class should once again be stored in a file named Player.java, however Baseball9.java is the only file that you need to modify for this assignment. Once all of the input data from the file is stored in the array, code and invoke a...

  • Lab Description Sort all words by comparing the length of each word. The word with the...

    Lab Description Sort all words by comparing the length of each word. The word with the smallest length would come first. If you have more than one word with the same length, that group would be sorted alphabetically Input: The data file contains a list of words. The first line in the data file is an integer that represents the number of data sets to follow Output: Output the complete list of words in order by length. Sample Data 10...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT