Small game of guessing letters

Source: Internet
Author: User
Tags array definition exit in

/** guess the alphabet game needs are as follows: The program randomly produces 5 characters in a certain order as a result of guessing (5 characters are not allowed to repeat), and the player guesses the string. The player can guess multiple times (case insensitive), and each time it is guessed, the result is prompted by the system. (Guessing the process of entering non-English characters or more than 5 characters inode requires re-entering the correct characters). If the guesses are correct, the game ends, the player's game scores are counted and the output is calculated, and if there is no guess, the results are guessed, for example, by guessing several characters and guessing the position of several characters. and prompts the player to continue the game. If the player enters exit in the console (not case sensitive), the game is aborted and the program ends.        Upgrade: 1. Increase the difficulty option, depending on the number of inputs, the number of letters generated is different. The difficulty does not write, all appears 5 place, changes the variable to be possible. 2. Increase the Chronograph function 3. Increase the game start time 4. Increase game End time
General version idea: Data structure:1. 5 random characters, stored in an array (collection). Because there are fixed lengths, the same type, using arrays is more convenient. randomchar[]2. Number of guesses,intCount3. Scoreintscore4. User input 5 characters, inputchar[]5. Guess the result, need a inputchar[] and randomchar[] than the result of the variable, with what?If there is no guessing, then the result of guessing, such as guessing the number of characters, and guessing the position of a few characters and other information analysis this sentence, guessing the wrong hint: guess the right number of characters? And guess the position of a few characters?inputchar[] and randomchar[], both have characters and subscript two properties. The subscript can be used to represent the position of the character. There are only a few characters of the same? Receive with an int a. What are the same characters and subscripts?receive with an int B. However, considering that the process of contrast must be encapsulated in a method, ultimately to return the results of the comparison, to count the scores, or to do other output by the caller, etc., it is best to use the int[] array to return a, B only. So here with int[] Result , result[0] Indicates correct character, result[1] indicates that both the character and position are correct, receiving two contrasting results respectively. Process:1before the game starts, the system generates random character combinations and hides in the background prompt to start the game2The game starts looping and starts the user input guessingString(convert user input string to uppercase and judge)//Reasonable conditions: 1. The input is not the number 2. The length is 5 or less 3. Chinese No (regular expression determines whether the character is reasonable)if it is reasonable: if it is not exit: Enter the user"string" is converted to ' character ', into the inputchar[] array, into the contrast phase. Compare phase return result[] results, enter the statistical phase if exit: Stop the game if it is unreasonable: the characters are unreasonable, please re-enter3The comparison stage, which is equal to the two-character array, returns the result4Enter the statistical stage, count the times, calculate the results, not all correct, continue the game, all correct, quit the game. The method to be implemented:1. Randomly generated characters, return the character array to the randomchar[] array. Defined:Char[] Randomletter ()2. Determine whether the input word conforms to the method, reasonable return true, otherwise return false definition:BooleanInputregex (INPUTSTR)3The comparison phase method: Compares the two character array with which characters are the same, which are the same characters and positions, and returns the result[] array definition:int[] Checkcorrect (randomchar[],inputchar[])4. Method of the statistical phase: according to Result[1] The number of judgments, if for 5, prove 5 characters all guessed right. End game. Otherwise, give hints corresponding to the number of hints, continue the game according to the above ideas, can be reflected in the code. */ Public classGuessletter { Public Static voidMain (string[] args) {Scanner scan=NewScanner (system.in); /*The return value used to receive the randomly generated character randomletter () method*/        Char[] Randomchar = {}; /*scores and Times*/        intCount = 0; intScore = 0; /*The character entered by the user, used to receive the user input string (INPUTSTR), * converted to the return value of the character Inputstr.tochararray ()*/        Char[] Inputchar = {}; /*used to receive the Checkcorrect () method return value*/        int[] result =New int[2]; /*Game Difficulty selector insertion point*/        /*1. Before the game starts, the system generates random character combinations and hides in the background prompt to start the game*/Randomchar=Randomletter ();        System.out.println (Randomchar); /*2. Start the game and start the cycle*/System.out.println ("Welcome to the Guess character game, below the official start"); /*game start time insertion point timing time insertion point*/Date Date=NewDate (); SimpleDateFormat SDF=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); String Nowtime=Sdf.format (date); System.out.println ("Game Start time:" +nowtime); LongStartTime =System.currenttimemillis ();  while(true){            /*user input guessing "string" (regular expression determines whether the character is reasonable)*/System.out.println ("Please enter the characters you guessed (cannot exceed 5 characters, cannot enter Chinese and numbers), exit: Exit the Game"); String Inputstr=scan.next (). Trim (). toUpperCase (); /*The method that determines whether the input word conforms to the reason, returns true properly, otherwise returns false*/            if(Inputregex (inputstr)) {//If reasonable: Determine whether the input is exit                if("EXIT". Equals (INPUTSTR)) {System.out.println ("Goodbye, Welcome to the game challenge.");  Break; }Else{                    //converts the user input "string" into a ' character ', into the inputchar[] array, into the contrast phase.Inputchar =Inputstr.tochararray (); //Compared to two character arrays, the contrast phase returns result[] resultsresult =Checkcorrect (Randomchar,inputchar); //Enter the statistical stage, remember the number of times, calculated results, no full answer to the situation, continue the game, all correct, quit the game.                    /*Judging by the number of result[1], if 5, prove 5 characters all guessed right. End game. Otherwise, give a hint to the number of guesses, continue the game*/                    if(Result[1] = = 5) {score= randomchar.length*100-20*count; System.out.println ("Congratulations, all right, score:" +score+ "); /*Game end time insertion point timing insertion point*/                        LongEndTime =System.currenttimemillis (); System.out.println ("Total Time:" + (Endtime-starttime)/1000+ "SEC"); System.out.println ("Game End Time:" +nowtime);  Break; }Else{Count++; System.out.println ("Guess the +result[0]+" character "+" where the position is also correct "+result[1]+"); }                }            }Else{                //if it is unreasonable: the character is unreasonable, please re-enterSystem.out.println ("character input not reasonable, please re-enter"); }        }    }    /*** Compare two character arrays with which characters are the same *@paramRandomchar system randomly generated characters *@paramInputchar Player Input characters *@returnresult[] player guessing results statistics*/     Public Static int[] Checkcorrect (Char[] Randomchar,Char[] Inputchar) {        int[] result =New int[2]; /*In contrast, each character in each group needs to be followed by one character in turn and the other set,*/        //so double-nested loops.         for(inti = 0; i < randomchar.length; i++) {             for(intj = 0; J < Inputchar.length; J + +) {                if(Randomchar[i] = =Inputchar[j]) {                    //the correct number of charactersresult[0]++; if(i = =j) {                        //the number of characters and positions are correctresult[1]++;  Break; }                }            }        }        returnresult; }    /*** Determine if the characters entered by the user are reasonable *@paramSTR User-entered String *@returnreasonable return true, otherwise return false*/     Public Static BooleanInputregex (String str) {//Reasonable conditions: 1. The input is not the number 2. The length is 5 or less 3. Chinese noString Inputregex = "([a-za-z]) {1,5}"; returnstr.matches (Inputregex); }    /*** Random Character generation method *@returnchar[] Random generated character array*/     Public Static Char[] Randomletter () {Random rand=NewRandom (); /*Add difficulty, 5 can be set to variable can be*/        Char[] random =New Char[5]; /*alphabet, Function: Will randomly select the character from here, assign to the random array.         * An index variable is required to represent the subscript of the letters.         *index Loop 5 Assignment, get 5 subscript corresponding 5 characters, assign to the random array. But there is no guarantee that it will not be repeated.          * Want to ensure that not repeat, need to randomly 5 times the number is different, how to control it?         * You can use another array, a Boolean array, that is the same length as the letters array. As long as the selected letter subscript, * reappear, the switch becomes true, that is, one more cycle, do not select the duplicate subscript of the letter. **/        intindex = 0; Char[] letters = {' 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 '}; Boolean[] flags =New Boolean[Letters.length];//the default value is false;        /*an array assignment that needs to be traversed*/         for(inti = 0; i < random.length; i++) {            //as long as the subscript of the switch array is true, it indicates that the character has been used. That is, loop again until a different subscript is randomly             while(Flags[index]) {index=Rand.nextint (letters.length); }            //assign a value to randomRandom[i] =Letters[index]; //as long as the assigned index is marked as true;Flags[index] =true; }        returnRandom; }    /*generated characters: ACHZW output: Welcome to the Guess character games, the following officially started please enter your guess characters (not more than 5 characters, cannot enter Chinese and numbers), Exit: Exit Game 5 after Love character input Unreasonable, please re-enter please enter your guess characters (not more than 5 characters, cannot enter Chinese and numbers), exit: Exit Game Achze guess on 4 characters where the position is also correct there are 4 Please enter the characters you guessed (not more than 5 characters, not Can input Chinese and digital), exit: Exit the game achzw Congratulations, all right, score: 480 points*/}
View Code

Small game of guessing letters

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.