0% found this document useful (0 votes)
19 views

Code

Uploaded by

dhaarmi.gala
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Code

Uploaded by

dhaarmi.gala
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

import javax.swing.

*; //gui

import java.awt.*; //gui + event handling

import java.awt.event.Ac onEvent; //event handling

import java.io.*; //file handling

import java.u l.*; //set and random

import java.u l.stream.Collectors; //streamlined data processing

public class SpellingBeeGameGUI extends JFrame {

sta c final int MISTAKES_ALLOWED = 5;

sta c final int[] POINTS = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 1, 2, 1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10};

sta c final String DICTIONARY_FILE = "C:\\Users\\Public\\Downloads\\dic onary.txt";

sta c Set<String> dic onary = new HashSet<>(); //set of valid words loaded from the dic onary
file to avoid duplicates

String le erSet;

char mustInclude;

StringBuilder currentWord = new StringBuilder(); //allows muta on of strings

int mistakes = 0;

int totalPoints = 0;

Set<String> usedWords = new HashSet<>(); //set to avoid duplicates

JLabel wordLabel;

JLabel scoreLabel;

JLabel mistakesLabel;

JTextArea usedWordsArea;

public SpellingBeeGameGUI() { //ini alize methods

displayInstruc ons();

loadDic onary();

setupGame();
setupGUI();

public sta c void main(String[] args) {

SwingU li es.invokeLater(SpellingBeeGameGUI::new); //EDT to allow safe mul threading, task


is queued up and invokes constructor

void displayInstruc ons() {

String instruc ons = """

How It Works:

1. The game generates 7 random le ers, with one le er being compulsory.

2. You can form words from the given le ers, but each word must include the compulsory
le er.

3. Words are checked against a dic onary, and points are awarded based on the Scrabble
point system.

4. A mistake occurs if you submit a word that:

- Doesn’t include the compulsory le er.

- Has already been entered before.

- Is less than 4 le ers long.

- Is not found in the dic onary.

""";

JOp onPane.showMessageDialog(this, instruc ons, "Game Instruc ons",


JOp onPane.INFORMATION_MESSAGE); //this for center

void loadDic onary() {

try (BufferedReader reader = new BufferedReader(new FileReader(DICTIONARY_FILE))) { //reads


text line by line

String line;

while ((line = reader.readLine()) != null) { //loop to read each line, one line= one word

dic onary.add(line.trim().toLowerCase()); //trim for whitespaces, adds to dic onary defined


earlier
}

} catch (IOExcep on e) { //excep on handling in case the file isnt found

JOp onPane.showMessageDialog(this, "Error loading dic onary: " + e.getMessage(), "Error",


JOp onPane.ERROR_MESSAGE); //error dialog box in case of excep on occurance

void setupGame() {

Set<Character> uniqueLe ers = generateUniqueRandomLe ers();

ArrayList<Character> le ersList = new ArrayList<>(uniqueLe ers); // Convert to a list for easy


indexing

Random random = new Random();

mustInclude = le ersList.get(random.nextInt(le ersList.size())); // Randomly select a le er as


compulsory

le ersList.remove(Character.valueOf(mustInclude)); // Remove the compulsory le er from the


list

le erSet = le ersList.stream() //creates a sequence of elements

.map(String::valueOf) //char to string, refers to string.valueOf()

.collect(Collectors.joining()); //requires strings not char, concatenates the strings into one to
easily display in le erSet

void setupGUI() {

setTitle("Spelling Bee Game");

setSize(400, 600);

setLayout(new BorderLayout());

setDefaultCloseOpera on(EXIT_ON_CLOSE);

getContentPane().setBackground(Color.BLACK); //retrieves the content pane of the frame to


allow modifica on

JPanel le ersPanel = new JPanel();

le ersPanel.setLayout(null);

le ersPanel.setPreferredSize(new Dimension(300, 300));


le ersPanel.setBackground(Color.BLACK);

add(le ersPanel, BorderLayout.CENTER);

wordLabel = new JLabel("Current Word: ");

scoreLabel = new JLabel("Score: 0");

mistakesLabel = new JLabel("Mistakes Remaining: " + (MISTAKES_ALLOWED - mistakes));

wordLabel.setForeground(Color.WHITE);

scoreLabel.setForeground(Color.WHITE);

mistakesLabel.setForeground(Color.WHITE);

JPanel infoPanel = new JPanel();

infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));

infoPanel.add(wordLabel);

infoPanel.add(scoreLabel);

infoPanel.add(mistakesLabel);

infoPanel.setBackground(Color.BLACK);

add(infoPanel, BorderLayout.NORTH);

int radius = 100;

int centerX = 150;

int centerY = 150;

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

char le er = Character.toUpperCase(le erSet.charAt(i));

JBu on bu on = createLe erBu on(le er, Color.WHITE);

double angle = 2 * Math.PI * i / le erSet.length(); //placement for circular layout

int x = (int) (centerX + radius * Math.cos(angle));

int y = (int) (centerY + radius * Math.sin(angle));


bu on.setBounds(x, y, 50, 50);

le ersPanel.add(bu on);

JBu on mustIncludeBu on = createLe erBu on(Character.toUpperCase(mustInclude),


Color.YELLOW);

mustIncludeBu on.setBounds(centerX - 0, centerY - 0, 50, 50); // Centering the compulsory


le er

le ersPanel.add(mustIncludeBu on);

JPanel bo omPanel = new JPanel();

bo omPanel.setBackground(Color.BLACK);

JBu on submitBu on = new JBu on("Submit Word");

submitBu on.addAc onListener(e -> submitWord());

JBu on deleteBu on = new JBu on("Delete Last Le er");

deleteBu on.addAc onListener(e -> deleteLastLe er());

bo omPanel.add(deleteBu on);

bo omPanel.add(submitBu on);

add(bo omPanel, BorderLayout.SOUTH);

usedWordsArea = new JTextArea(5, 20);

usedWordsArea.setEditable(false);

usedWordsArea.setBackground(Color.BLACK);

usedWordsArea.setForeground(Color.WHITE);

usedWordsArea.setText("Used Words:\n");

JScrollPane scrollPane = new JScrollPane(usedWordsArea);

scrollPane.setPreferredSize(new Dimension(300, 100));


add(scrollPane, BorderLayout.EAST);

setVisible(true);

JBu on createLe erBu on(char le er, Color color) {

JBu on bu on = new JBu on(String.valueOf(le er));

bu on.setBackground(color);

bu on.addAc onListener(e -> addLe erToWord(le er));

return bu on;

void addLe erToWord(char le er) {

currentWord.append(le er);

updateWordLabel();

void updateWordLabel() {

wordLabel.setText("Current Word: " + currentWord.toString());

void deleteLastLe er() {

if (currentWord.length() > 0) {

currentWord.deleteCharAt(currentWord.length() - 1);

updateWordLabel();

void submitWord() {

String word = currentWord.toString().toLowerCase();

if (usedWords.contains(word)) {
showError("You have already used that word.");

mistakes++; // Increment mistakes for duplicate word

} else if (word.length() < 4) {

showError("Word must be at least 4 le ers long.");

mistakes++;

} else if (!word.contains(String.valueOf(mustInclude))) {

showError("Word must include the le er " + mustInclude + ".");

mistakes++;

} else if (!isValidWord(word)) {

showError("Word is not in the dic onary.");

mistakes++;

} else {

int points = calculatePoints(word);

totalPoints += points;

usedWords.add(word);

JOp onPane.showMessageDialog(this, "Word accepted! You earned " + points + " points.");

updateUsedWords(word);

// Update score and mistakes labels

scoreLabel.setText("Score: " + totalPoints);

mistakesLabel.setText("Mistakes Remaining: " + (MISTAKES_ALLOWED - mistakes));

// Check for game over condi on

if (mistakes >= MISTAKES_ALLOWED) {

JOp onPane.showMessageDialog(this, "Game Over! Your final score is: " + totalPoints);

System.exit(0);

currentWord.setLength(0);

updateWordLabel();
}

boolean isWordInvalid(String word) {

if (usedWords.contains(word)) {

showError("You have already used that word.");

return true;

if (word.length() < 4) {

showError("Word must be at least 4 le ers long.");

mistakes++;

return true;

} else if (!word.contains(String.valueOf(mustInclude))) {

showError("Word must include the le er " + mustInclude + ".");

mistakes++;

return true;

} else if (!isValidWord(word)) {

showError("Word is not in the dic onary.");

mistakes++;

return true;

return false;

void endGame() {

JOp onPane.showMessageDialog(this, "Game Over! Your final score is: " + totalPoints);

System.exit(0);

void updateUsedWords(String word) {


usedWordsArea.append(word.toUpperCase() + "\n"); // Display word in uppercase

boolean isValidWord(String word) {

return dic onary.contains(word);

int calculatePoints(String word) {

return word.chars().map(ch -> {

if (ch >= 'a' && ch <= 'z') {

return POINTS[ch - 'a'];

return 0;

}).sum();

Set<Character> generateUniqueRandomLe ers() {

Random random = new Random();

Set<Character> le ers = new HashSet<>();

Set<Character> vowels = Set.of('a', 'e', 'i', 'o', 'u');

int vowelCount = 0;

// Ensure at least two vowels

while (vowelCount < 2) {

char le er = (char) ('a' + random.nextInt(26));

if (vowels.contains(le er) && !le ers.contains(le er)) {

le ers.add(le er);

vowelCount++;

}
// Fill the rest with random le ers

while (le ers.size() < 7) {

char le er = (char) ('a' + random.nextInt(26));

le ers.add(le er);

return le ers;

void showError(String message) {

JOp onPane.showMessageDialog(this, message, "Error", JOp onPane.ERROR_MESSAGE);

You might also like