Моя java-программа является модифицированной версией игры Scrabble. Вот как работает моя игра:
- Эта игра выдаст пользователю 7 случайных букв. Затем пользователю будет предложено ввести слово, используя эти 7 букв, и игра проверит, является ли слово пригодным для игры словом, просмотрев его в официальном списке слов Эрудит, используя бинарный поиск.
Если это реальноеword пользователь получает баллы на основе значений букв в данном слове.
Что мне нужно реализовать в моем коде?
- Мне нужно реализовать возможность дать моему пользователю Java-игры возможность играть снова и попытаться ввести другое слово, используя те же самые случайные 7 букв.
Бонусные баллы, если вы также можете помочь мне в следующих вещах:
В настоящее время в моей игре есть пустые буквы, дающие очкизначение письма, в котором пользователь моей программы решает их составить. Вместо этого я хотел бы, чтобы любая пустая плитка представляла счет 0 баллов, но я не могу просто добавить регистр в мой метод letterValue, чтобы он возвращал 0, когда символ равен (_), потому что я должен сказать своей программе заменитьпустую плитку с буквой, которую они хотят видеть пустой плиткой.
В настоящее время, если мой пользователь должен получить более одной пустой плитки, моя программа изменит все пустые плитки, указанные втолько одна буква, которую они хотят. Я хотел бы дать своему пользователю возможность иметь одну плитку, представляющую одну букву, в то время как другая плитка представляет другую по своему выбору.
Воттекущий код для моей игры Java:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Random;
import java.util.Scanner;
/*
Date: 10/23/2019
Programmer(s): Jaryn D. Giampaoli
Program: ScrabbleWordChampion
Version: 5.0
Purpose: This game will give the user 7 random letters. Then the user will be asked
to type in a word using those 7 letters and the game will then check if the word is
a playable word by looking it up in the official Scrabble word list using binary search.
If it is a real word the user is awarded points based on the values of the letters within
their given word.
*/
//ALGORITHM
/* Read in a file of words into an array of Strings
* Randomly pick 7 letters from alphabet (at least one vowel)
* Tell the player the 7 letters that were picked, and ask them for a word
* Input the word and then verify if it is a word (utilize Binary Search) and that it contains only letters they were given
* If it is a word, give points to the player based on the values of each letter utilized.
*/
public class ScrabbleWordChampion {
//Data variable to hold words
static String[] words = new String[300000];
static int wordCount = 0;
static char[] letters = {'A', 'E', 'I','O', 'U',
'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L',
'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W',
'Y', 'X', 'Z', '_'};
public static void main(String[] args) {
//Read in the file of the words into an array of Strings
Scanner input = null;
//Create scanner
try {
input = new Scanner(new File("Words.txt"));
} catch(FileNotFoundException e)
{
//Notify user if problem occurs
System.out.println("Error opening specified file: " +
"Words.txt");
System.exit(0); //Safe exit program
}//End try
input.nextLine(); //Read in first line
input.nextLine(); //Read in second line
//Gather data from file
while(input.hasNextLine())
{
words[wordCount++] = input.nextLine();
}//End while
//BEGINNING - User interface
startupHeader();
//UPPER & LEFT PARTS OF TILE RACK
System.out.println();//Line break for better user interface
System.out.println(" YOUR TILE RACK: ");
System.out.print("*******************");//Upper-part of user's tile rack
//First part of blank tile prompt
System.out.print(" If you see " + "\"_\"" + " in your tile rack, you");
System.out.println();
System.out.print("# ");//Left side of user's tile rack
/*Declare additional variables needed to verify that the user
only used given letters */
char[] givenLetters = new char[7];
boolean[] letterUsageStatus = new boolean[7];
boolean invalidInput = false;
String wordInvalidMessage = "Sorry! You do not have letter tile(s): ";
//Randomly pick 7 letters from alphabet (at least one vowel)
Random rand = new Random();
rand.setSeed(System.currentTimeMillis());
//Vowels
int indexOfVowel = rand.nextInt(5);
{
givenLetters[0] = letters[indexOfVowel];
System.out.print(letters[indexOfVowel] + " ");
}
//Entire alphabet
for (int i = 1; i < 7; i++) {
int index = rand.nextInt(27);
givenLetters[i] = letters[index];
System.out.print(letters[index] + " ");
}//End for
//BOTTOM & RIGHT PARTS OF TILE RACK - User Interface
System.out.print(" # ");//Right-side of user's tile rack
System.out.print(" received a blank tile!");
System.out.println();//Line Break from letters
System.out.print("******************* ");
System.out.print("Blank tiles can represent any letter.");
System.out.println();//Force additional system output to next line
System.out.println();//Line break for better user interface
/*Ask for user input of word and then verify if input is a playable word
and with only letters given */
//Declare variables
Scanner userInput = new Scanner(System.in);
String userGivenWord;
System.out.println("________________________________________________________________");
System.out.println(" NOTE: To use a blank tile(s), type underscore (_) ");
System.out.println(" *If you have more than one blank tile, ");
System.out.println(" they all will represent the same letter ");
System.out.println(" you desire to have them resemble. ");
System.out.println("________________________________________________________________");
System.out.println();
System.out.print("Using your seven letter tiles, please enter your word: ");
userGivenWord = userInput.nextLine().toUpperCase();
//Does user-given word contain a blank?
if (userGivenWord.contains("_")) {
System.out.print("What letter would you like your blank tile(s) to represent?: ");
char blankLetterTile = userInput.next().toUpperCase().charAt(0);
userGivenWord = userGivenWord.replace('_', blankLetterTile);
for (int i = 1; i < 7; i++) {
if (givenLetters[i] == '_') {
givenLetters[i] = blankLetterTile;
}
}
}
//Convert userGivenWord to UserGivenLetters (userGivenWord.toCharArray();)
char[] usedLetters = userGivenWord.toCharArray();
//Verify that the user only used given letters
for(int i = 0;i < usedLetters.length;i++)
{
boolean foundLetters = false;
for(int j=0;j<givenLetters.length;j++)
{
if(letterUsageStatus[j] == false && givenLetters[j] == usedLetters[i])
{
letterUsageStatus[j]=true;
foundLetters = true;
break;
}
}
if(foundLetters == false)
{
wordInvalidMessage += usedLetters[i]+" ";
invalidInput = true;
}
}
if(invalidInput == false)
//Check if given word is playable in Scrabble (refer to official word list)
{
//Give player points
if (wordVerify(userGivenWord))
System.out.println("With your word (" + userGivenWord + "), you acquired "
+ getPoints(userGivenWord) + " points.");
//Display invalid word message to player
else {
System.out.println();
System.out.println("You have entered a word that is not playable in the game of Scrabble!");
System.out.println("You were awarded 0 points.");
}
}
//Show player additional letters error
else
{
System.out.println();
System.out.println(wordInvalidMessage);
System.out.println("You were awarded 0 points.");
}
//Clarify letter values and display
System.out.println();
System.out.print("Do you have descrepancies on your score (Y = Yes, N = No)?: ");
char playerAnswer = 'Y';
playerAnswer = Character.toUpperCase(userInput.next().charAt(0));
if (playerAnswer == 'Y') {
System.out.println();
System.out.println("The values of each letter tile are as follows...");
System.out.println(" * 1 POINT(S): " + "\"A\"" + ", " + "\"E\"" + ", " + "\"I\"" + ", " + "\"L\"" + ", " + "\"N\"" + ", " + "\"O\"" + ", " +"\"R\"" + ", " +"\"S\"" + ", " + "\"T\"" + ", & " + "\"U\"");
System.out.println(" * 2 POINT(S): " + "\"G\"" + " & " + "\"D\"");
System.out.println(" * 3 POINT(S): " + "\"C\"" + ", " + "\"M\"" + ", & " + "\"P\"");
System.out.println(" * 4 POINT(S): " + "\"H\"" + ", " + "\"V\"" + ", " + "\"W\"" + ", & " + "\"Y\"");
System.out.println(" * 5 POINT(S): " + "\"K\"");
System.out.println(" * 8 POINT(S): " + "\"J\"" + " & " + "\"X\"");
System.out.println(" * 10 POINT(S): " + "\"Q\"" + " & " + "\"Z\"");
System.out.println(" * BLANK TILES: Point value of the letter you chose them to represent");
System.out.println();
System.out.println("+--------------------------------------------------------------+");
System.out.println("| RECIEVED NO POINTS? |");
System.out.println("| If you didn't recieve points for your word, it is due to one |");
System.out.println("| (or more) of the following reasons: |");
System.out.println("| * You attempted making a word that requires a letter |");
System.out.println("| tile(s) you were not given. |");
System.out.println("| * You made a word that is not in the official word list |");
System.out.println("| of Scrabble. |");
System.out.println("+--------------------------------------------------------------+");
//Display thank you for playing message
System.out.println();
System.out.println("Thank you for playing Scrabble Word Champion!");
}
else {
System.out.println();
System.out.println("Thank you for playing Scrabble Word Champion!");
}
}//End main
public static void startupHeader() {
System.out.println("+--------------------------------------------------------------+");
System.out.println("| SSSSS CCCCC RRRRR A BBBB BBBB L EEEEE |");
System.out.println("| S C R R A A B B B B L E |");
System.out.println("| SSSSS C RRRRR AAAAA BBBB BBBB L EEEEE |");
System.out.println("| S C R R A A B B B B L E |");
System.out.println("| SSSSS CCCCC R R A A BBBB BBBB LLLLL EEEEE |");
System.out.println("+--------------------------------------------------------------+");
System.out.println("| WORD CHAMPION VERSION |");
System.out.println("| Become a champion by practicing with making words from seven |");
System.out.println("| random letters to give you a high amount of points! |");
System.out.println("+--------------------------------------------------------------+");
}
//METHOD - valueOfLetter Method (To obtain values of letters)
public static int getValueLetter(char letter){
switch (Character.toUpperCase(letter)){
case 'G':
case 'D': return 2;
case 'B':
case 'C':
case 'M':
case 'P': return 3;
case 'F':
case 'H':
case 'V':
case 'W':
case 'Y': return 4;
case 'K': return 5;
case 'J':
case 'X': return 8;
case 'Q':
case 'Z': return 10;
default: return 1;
}
}
//METHOD - Award Points to Player
public static int getPoints(String userGivenWord) {
char[] arrayWord = userGivenWord.toCharArray();
int points = 0;
for (int i = 0; i < userGivenWord.length(); i++) {
points += getValueLetter(arrayWord[i]);
}
return points;
}
/*METHOD - wordVerify
(Check if given word is playable in official word list)*/
public static boolean wordVerify(String word) {
int lowIndex = 0; int highIndex = wordCount - 1;
int currentIndex;
while(lowIndex <= highIndex) {
currentIndex = (highIndex + lowIndex)/2;
if(word.equalsIgnoreCase(words[currentIndex]))
return true;
else if(word.compareTo(words[currentIndex]) < 0)
highIndex = currentIndex - 1;
else
lowIndex = currentIndex + 1;
}
return false;
}//End while
}//End class