使我的用户能够使用给定的图块输入另一个单词的附加代码

问题描述 投票:1回答:1

Hello stachOverflow社区!这是我的第一篇文章,因此,如果我的文章样式不正确和/或我无法在此页面上讨论我发布的内容,请与我联系。

我的Java程序是Scrabble游戏的修改版本。这是我的游戏的运作方式:

  • 此游戏将给用户7个随机字母。然后将询问用户输入使用这7个字母的单词,然后游戏将检查该单词是否为通过使用二进制搜索在官方拼字游戏单词列表中查找可玩单词。如果是真实单词,则根据其中的字母值向用户授予积分他们给定的词。

我需要在我的代码中实现什么?

  • 我需要实现使我的Java游戏用户能够再次玩并尝试使用给定的相同随机7个字母输入另一个单词的能力。

奖励积分,如果您也可以在这些事情上帮助我:

  • 目前,我的游戏中有空白字母,提供程序用户决定制作的字母的磅值。相反,我希望任何空白图块都代表0分的得分,但是我不能仅仅在我的letterValue方法中添加一个case以在字符等于(_)时返回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
java recursion binary-search
1个回答
0
投票

您想一遍又一遍地做任何事情,包括无效的输入,请使用while循环。 boolean inGamePlay = true; while(inGamePlay){//提供并显示新的图块,并带有内部while循环要求生成单词,然后对其进行验证,计算点是否有效或再次询问是否无效,如果用户输入“退出”然后退出然后将isGamePlay设置为false,依此类推...}

[@DevilsHnd给出的解决方案>

© www.soinside.com 2019 - 2024. All rights reserved.