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

CS project doubt

The document outlines a project to create an interactive word-guessing game called 'Pigs&Hogs', where players guess a hidden 5-letter word based on feedback about correct letter positions (hogs) and correct letters in wrong positions (pigs). It addresses challenges such as validating player input, tracking performance metrics, and ensuring replayability through a large word bank and two game modes. The project includes detailed algorithms and code snippets for implementing game mechanics, input validation, and user feedback.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

CS project doubt

The document outlines a project to create an interactive word-guessing game called 'Pigs&Hogs', where players guess a hidden 5-letter word based on feedback about correct letter positions (hogs) and correct letters in wrong positions (pigs). It addresses challenges such as validating player input, tracking performance metrics, and ensuring replayability through a large word bank and two game modes. The project includes detailed algorithms and code snippets for implementing game mechanics, input validation, and user feedback.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

CS Project

I. Objective:

The objective of this project is to create an interactive word-guessing game


("Pigs&Hogs") where players try to guess a hidden 5-letter word using
information on l correct letter positions (hogs) and correct letters in wrong
positions (pigs). The game supports two modes: unlimited guesses or a user-
defined limited number of attempts.

II. Problem:
1. Validating Player Input
Problem: Players might enter invalid guesses (e.g., words with incorrect length,
non-alphabetic characters, or repeated letters).
Solution:

Created the isValidGuess method to enforce rules:

Checks if the guess is exactly 5 letters long.

Verifies all characters are letters using Character.isLetter().

Uses a HashSet to ensure no duplicate characters.

Invalid guesses trigger clear error messages (e.g., "Invalid guess: Use 5
unique letters!")

2. Tracking Performance Metrics


Problem: Players need transparency about their progress (e.g., attempts, time).
Solution:

Tracked GuessCount to tally total attempts.

Used Java’s Instant and Duration classes to calculate time elapsed during
gameplay.

Displayed stats at the end (e.g., "Solved in 5 guesses and 2 minutes!").

3. Ensuring Replayability

CS Project 1
Problem: Repetitive gameplay reduces engagement.
Solution:

Stored 200+ words in a String[] dictionary array.

Used Random to randomly select a new secret word for each game
session.

III. Project Prompt:


This Java project is challenging word-guessing game with these key features:

1. Word Bank: it has a large collection of 200+ five-letter words for longer or
repeated gameplay.

2. Game Modes: Two player options: endless guessing or a limited-attempts


challenge .

3. Hints System: Feedback after each guess showing the number of hogs
(correct letters in correct spots) and pigs (correct letters in wrong spots).

4. User-Friendly: Clear instructions, error handling and end-game statistics


(including time taken and number of guesses) to help grade your level in
the game.

The game should encourage the user to come and play again as it not only
recreational but also an educational game that helps you build your vocabulary
as well as your logical reasoning skills.

IV. Algorithm:
0. Run the program.

1. Display game instructions.

2. Load a dictionary of valid 5-letter words and randomly select a secret word.

3. Prompt the player to choose between unlimited or limited guesses.

4. If limited guesses, ask for the maximum number of attempts and validate
input.

5. Start a timer and initialize variables (GuessCount, wordGuessed).

6. Enter the guessing loop:

CS Project 2
Get the player’s guess and validate it (5 letters, unique characters).

Compare the guess to the secret word:

Count hogs (correct letters in correct positions).

Count pigs (correct letters in incorrect positions).

Display the number of pigs and hogs.

Increment the guess count.

Break the loop if the word is guessed or max guesses are exceeded.

7. Stop the timer and display the result:

If guessed correctly, congratulate and show stats (word, attempts,


time).

If not, reveal the secret word and encourage trying again.

VI. Code:
import java.util.**;
import java.time.**;

public class CowsnBullz {


public static boolean isValidGuess(String input) {
if (input.length() != 5) { // Checks whether the guess i
s a 5-letter word
return false;
}
HashSet<Character> uniqueChar = new HashSet<>();
for (char c : input.toCharArray()) { /* Check whether it i
s a letter and the letters are unique*/
if (!Character.isLetter(c) || uniqueChar.contains(c)) {
return false;
}
uniqueChar.add(c);
}
return true;
}

public static int[] pigznhogzcalc(String input, String Secr

CS Project 3
etWord) {
/* Calculates the number of pigs and hogs for a given g
uess and puts it in an array */
int pigs = 0;
int hogs = 0;

for (int i = 0; i < 5; i++) {


if (input.charAt(i) == SecretWord.charAt(i)) {
hogs++; // Hogs: correct letter in the correct
position
} else if (SecretWord.contains(Character.toString(i
nput.charAt(i)))) {
pigs++; // Pigs: correct letter but in the wron
g position
}
}
return new int[]{pigs, hogs};
}

public static void main(String[] args) {


System.out.println("Welcome to Pigs&Hogs, a word game i
n which you have to guess the unknown word.");
System.out.println("If a letter in your guess is in the
correct position, you will get a hog.");
System.out.println("If a letter in your guess is in the
unknown word but not in the correct position, you will get
a pig.");
System.out.println("Try to guess the unknown word with
the least number of guesses. Good luck!");

String[] dictionary = {
"about", "adorn", "amber", "angel", "angle", "appl
e", "arise", "atlas", "awake",
"badge", "balmy", "basin", "beach", "beast", "blots", "blus
h", "boast", "brace", "brave",
"bride", "brisk", "broad", "brush", "camel", "candy", "catc
h", "charm", "chill", "chime",
"clean", "climb", "clamp", "cloth", "cloud", "crane", "craf

CS Project 4
t", "crisp", "dance", "daisy",
"delta", "diver", "donor", "draft", "drain", "drift", "drow
n", "eagle", "early", "earth",
"elbow", "elite", "epoch", "equip", "erase", "event", "fair
y", "false", "fancy", "farce",
"fault", "feast", "flare", "flame", "flank", "flora", "flut
e", "frame", "fresh",
"frost", "fruit", "gamer", "giant", "glare", "glide", "glob
e", "glory", "grace", "grain",
"grand", "grape", "grill", "grind", "grove", "guest", "guil
t", "haiku", "hatch", "heart",
"hoist", "honey", "horse", "house", "hover", "human", "humo
r", "index", "inlet", "ionic",
"irate", "irony", "ivory", "jewel", "joker", "jolly", "jump
s", "jumbo", "kayak", "karma",
"kayak", "kneel", "knack", "knave", "knife", "knock", "latc
h", "laugh", "lemon", "liver",
"logic", "loyal", "lodge", "lunar", "lumen", "magic", "majo
r", "march", "marsh", "medal",
"minor", "mirth", "moist", "molar", "mover", "music", "naiv
e", "noble", "north", "novel",
"nudge", "nylon", "oasis", "ocean", "octal", "omega", "oper
a", "optic", "orbit", "ounce",
"parka", "pearl", "petal", "phase", "phone", "pivot", "plan
t", "plaza", "plead", "plume",
"plush", "poise", "pouch", "pride", "prism", "proud", "puls
e", "quack", "quail", "quake",
"queen", "quiet", "quirk", "quota", "quote", "radar", "ranc
h", "raise", "raven", "razor",
"reach", "relay", "ridge", "rider", "river", "robot", "rogu
e", "rough", "route", "royal",
"scale", "scary", "scene", "scent", "shear", "shine", "shoc
k", "shore", "short", "shout",
"slice", "solar", "sound", "space", "spice", "spike", "squa
d", "stack", "stage", "stain",
"stand", "stare", "storm", "stout", "strip", "table", "talo
n", "teach", "thorn", "tiger",
"tough", "trail", "trend", "tribe", "trial", "tulip", "ulce

CS Project 5
r", "ultra", "uncle", "under",
"unity", "urban", "valve", "vapor", "vault", "vigor", "vivi
d", "vixen", "vocal", "voice",
"waste", "water", "whale", "whirl", "widow", "widen", "wide
r", "windy", "woven", "worry",
"xenon", "xeric", "xerox", "xylon", "yield", "young", "yach
t", "youth", "zebra", "zesty",
"zonal", "zesty", "zonal"};

Scanner monkey = new Scanner(System.in);


Random SecretWordSel = new Random(); // Generates random se
cret word from dictionary array
int index = SecretWordSel.nextInt(dictionary.length);
String SecretWord = dictionary[index];

System.out.println("Choose a game mode:");


System.out.println("1: Unlimited guesses");
System.out.println("2: Limited guesses");

int gameMode = 0;
int maxGuesses = 0;
boolean validMode = false;

while (!validMode) {
try {
System.out.print("Enter 1 or 2: ");
gameMode = monkey.nextInt();
if (gameMode == 1 || gameMode == 2) {
validMode = true;
} else {
System.out.println("Invalid choice. Please
enter 1 or 2.");
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please enter
a number (1 or 2).");
monkey.next(); // Clear the invalid input
}

CS Project 6
}

if (gameMode == 2) {
boolean validGuesses = false;
while (!validGuesses) {
try {
System.out.print("Enter the maximum number
of guesses: ");
maxGuesses = monkey.nextInt();
if (maxGuesses > 0) {
validGuesses = true;
} else {
System.out.println("Please enter a posi
tive number.");
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Please e
nter a positive number.");
monkey.next(); // Clear the invalid input
}
}
}

int GuessCount = 0;
boolean wordGuessed = false;

// Start the timer


Instant startTime = Instant.now();

while (true) {
if (gameMode == 2 && GuessCount >= maxGuesses) {
System.out.println("You have reached the maximu
m number of guesses."+"The word was "+SecretWord+". Better
luck next time!");
break;
}

try {

CS Project 7
System.out.println("Enter your guess:");
String input = monkey.next().toLowerCase();

if (!isValidGuess(input)) {
throw new IllegalArgumentException("Invalid
guess. Enter a 5-letter word with unique letters.");
}

GuessCount++;
int[] actualPigsnHogs = pigznhogzcalc(input, Se
cretWord);
int pigs = actualPigsnHogs[0];
int hogs = actualPigsnHogs[1];

System.out.println("Pigs: " + pigs + ", Hogs: "


+ hogs);

if (hogs == 5) {
wordGuessed = true;
break; // Exit the loop once the player gue
sses the right word (hogs == 5)
}
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println("An unexpected error occurre
d. Please try again.");
}
}

// Stop the timer


Instant endTime = Instant.now();
Duration timeElapsed = Duration.between(startTime, endT
ime);

if (wordGuessed) {
System.out.println("Good job! You have guessed the
word \\"" + SecretWord + "\\" in " + GuessCount + " trie

CS Project 8
s.");
System.out.println("Time taken: " + timeElapsed.toM
inutes() + " minutes.");
} else if (gameMode == 1) {
System.out.println("Better luck next time!");
}
}
}

CS Project 9

You might also like