我从动物串中选择了一个随机元素,我想要与所选元素相等的线索.如何获得元素相等的线索

  • 本文关键字:元素 线索 我想要 何获得 随机 一个 选择 java
  • 更新时间 :
  • 英文 :


我的数组在一个类中

private final String[] words = { "reddit", "facebook", "java", "assignment",
"game", "helloWorld", "weather", "religion", "internet", "face"};
private final String[] animals = {"squirrel", "dog", "monkey", "panda", "rat",
"kangaroo", "horse", "elephant", "fox", "cow"};
public String password;
private StringBuilder password Hidden;
private String[] animals Clues = {"Lives in trees and has a long fluffy tail", "Human's best friend", "Were are ancestors", "Has a Kung Fu movie", "Lives in New york sewers ", "Can kick you", "Looks like a Zebra", "Biggest land mammal ", "The hound and the ___" , "Our milk comes from" };
private String[] word Clues = {"Social new website", "What has your face and you can read it", "Coding language", "During this course, you've had", "ps4's have ", "first line of code we saw said", "its raining, what horrible __ ", "people have different", "uses code", "attached to our head"}; 
private String clues;

我怎样才能让动物得到同样的线索?

//this is where i show the hint in the jpanel.
private void getWord(){
JPanel Panel = new JPanel();
JTextField Intext = new JTextField();
HintPanel.add(Intext);

Hint.setText("Hint: " + clues);
}

https://github.com/Lwilliams002/Hangman-game/blob/main/HangmanGame.java以下是查看代码的存储库

作为一个建议,也许可以重新思考您想要这样做的方式。不使用一堆数组,而是使用特定的类来处理Animals、Words和其他任何您可能想要的实例。例如,如果您有一只名为Dog的动物,那么可能有一个Dog的实例,它也有一个用于Dog线索字符串数组的实例。

动物类别:

import java.util.ArrayList;
import java.util.List;

public class Animals {
private String animalName;
private String[] animalClues;
private static final List<Animals> animalInstances = new ArrayList<>();
public Animals() {
Animals.animalInstances.add((this));
}
public Animals(String animalName, String[] animalClues) {
this.animalName = animalName;
this.animalClues = animalClues;
Animals.animalInstances.add((this));
}
public String getAnimalName() {
return animalName;
}
public void setAnimalName(String animalName) {
this.animalName = animalName;
}
public String[] getAnimalClues() {
return animalClues;
}
public void setAnimalClues(String[] animalClues) {
this.animalClues = animalClues;
}
public static List<Animals> getAnimalInstances() {
return animalInstances;
}

}

你现在可以有不同数量的动物的实例,这可以从文件数据中创建。举个例子,假设我们有以下名为Animals.dat:的动物数据文本文件

# For specific animals and clues to those animals.
<Dog>
Mans best friend.
Likes to knaw on bones.
Has four legs.
Makes a great pet.
Likes to run around a park.
Likes to bark.

<Zebra>
Is black and White.
Has stripes.
Has four legs.
Has a unique pattern.
Part of the horse family.
Might see on a safari.
Start with the letter Z.
<Cat>
Has four legs.
Likes to sleep a lot.
Usually stays within the home.
A very common pet.
Likes to catch mice.
Sometimes known as a feline.
Rumored to have nine lives.
<Bear>
Is a mammal.
Has four legs.
Muppets Fozzie.
A Paddington.
Height and strength is very significant.
Has big paws and thick fur.
Hibernates in winter.
Can sometimes see one when camping.

您可以从该文件中的数据创建Animal的实例,下面提供的可运行代码对此进行了演示。我在下面提供的控制台应用程序代码允许用户选择猜测动物还是单词。使用哪个类取决于用户选择的内容(动物或单词)。该应用程序运行期间也会进行评分,用户可以随时退出。

这是代码。动物类已经显示在上面:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class CluesDemo {

// Make Scanner object class global so that we can use it anywhere.
private final Scanner userInput = new Scanner(System.in); 

public static void main(String[] args) {
// Started application this way to avoid 
// the need for statics.
new CluesDemo().startApp(args);
}

private void startApp(String[] args) {
String menuOption = "";
String gameFile = "Animals.dat";
while (menuOption.isEmpty()) {
System.out.println("Select what you want guess for in this game:");
System.out.println("  1) Animals");
System.out.println("  2) Words");
System.out.println("  3) Quit");
System.out.print("Your Choice: --> ");
menuOption = userInput.nextLine().trim();
if (!menuOption.matches("[1-3]")) {
System.out.println("Invalid menu choice! Try again...");
System.out.println();
menuOption = "";
}
}
/* switch/case is used in various locations so 
that you can add more game file types if you
like.        */
switch (menuOption) {
case "1":
gameFile = "Animals.dat";
break;
case "2":
gameFile = "Words.dat";
break;
case "3":
System.out.println("Thanks for playing. Bye-Bye.");
System.exit(0);
}
loadGameFile(gameFile, menuOption);

System.out.println();
switch (menuOption) {
case "1":
playAnimals();
break;
case "2":
playWords();
break;
}
}

private void playAnimals() {
List<Animals> gameTypeList = Animals.getAnimalInstances();
int score = 0;              // Score sum
/* The max possible score for the current question. 
The value in this variable changes based on the 
questions total number of clues minus the number 
of clues used.         */
int possibleMaxScore = 0;   
while (true) {
System.out.println("The computer has randomly selected an animal.");
System.out.println("You are tasked to determine what that animal");
System.out.println("is based on the random clues provided. Enter");
System.out.println("'q' to quit at any time:");
System.out.println();

int randomAnimal = new Random().nextInt(gameTypeList.size() - 1);
String answerAnimal = gameTypeList.get(randomAnimal).getAnimalName();
List <Integer> cluesPlayed = new ArrayList<>();
String[] clues = gameTypeList.get(randomAnimal).getAnimalClues();
possibleMaxScore = clues.length;
for (int i = 0; i < clues.length; i++) {
int clueNum = 0;
if (clues.length > 1) {
clueNum = new Random().nextInt(clues.length - 1);
}
if (cluesPlayed.contains(clueNum)) {
/* Clue was aleady played for this particular animal.
we don't want to see this clue again unless the
animal was randomly selected again.           */
if (cluesPlayed.size() == (clues.length -1)) {
/* If we've played all the clues and there still
is no correct answer then exit this loop and
question to start a new one.             */
break;
}
i--;
continue;
}
cluesPlayed.add(clueNum); // Add this clue to the cluesPlayed list.
System.out.println("Clue #" + (i + 1) + ": " + clues[clueNum]);
System.out.print("The animal is? --> ");
String answer = userInput.nextLine().trim(); // Get User input.
// Is quit desired?
if (answer.equalsIgnoreCase("q")) {
// Yes...so quit the application.
System.out.println("Thanks for playing. Bye-Bye.");
System.exit(0);
}
// Was the right animal supplied by User?
if (answer.equalsIgnoreCase(answerAnimal)) {
// Yes...
System.out.println("==================================================");
System.out.println("Correct!! '" + answerAnimal.toUpperCase() 
+ "' is the animal we were thinking of!");
score += possibleMaxScore;
System.out.println("Current Score: " + score);
System.out.println("==================================================");
System.out.println();
break;
}
else {
// No...
System.out.println("--------------------------------------------------");
System.out.println("Wrong!! A " + answer + " is NOT the animal "
+ "we were thinking of!");
possibleMaxScore--;
score--;
System.out.println("Current Score: " + score);
System.out.println("--------------------------------------------------");
System.out.println();
}
}
}
}

private void playWords() {
List<Words> gameTypeList = Words.getWordInstances();
int score = 0;              // Score sum
/* The max possible score for the current question. 
The value in this variable changes based on the 
questions total number of clues minus the number 
of clues used.         */
int possibleMaxScore = 0;   
while (true) {
System.out.println("The computer has randomly selected a word.");
System.out.println("You are tasked to determine what that word");
System.out.println("is based on the random clues provided. Enter");
System.out.println("'q' to quit at any time:");
System.out.println();

int randomWord = new Random().nextInt(gameTypeList.size() - 1);
String answerWord = gameTypeList.get(randomWord).getWord();
List <Integer> cluesPlayed = new ArrayList<>();
String[] clues = gameTypeList.get(randomWord).getWordClues();
for (int i = 0; i < clues.length; i++) {
int clueNum = 0;
if (clues.length > 1) {
clueNum = new Random().nextInt(clues.length - 1);
}
if (cluesPlayed.contains(clueNum)) {
/* Clue was aleady played for this particular word.
we don't want to see this clue again unless the
word was randomly selected again.            */
if (cluesPlayed.size() == (clues.length - 1)) {
/* If we've played all the clues and there still
is no correct answer then exit this loop and
question to start a new one.             */
break;
}
i--;
continue;
}
cluesPlayed.add(clueNum);
System.out.println("Clue #" + (i + 1) + ": " + clues[clueNum]);
System.out.print("The word is? --> ");
String answer = userInput.nextLine().trim();
if (answer.equalsIgnoreCase("q")) {
System.out.println("Thanks for playing. Bye-Bye.");
System.exit(0);
}
if (answer.equalsIgnoreCase(answerWord)) {
System.out.println("==================================================");
System.out.println("Correct!! '" + answerWord.toUpperCase() 
+ "' is the word we were thinking of!");
score += possibleMaxScore;;
System.out.println("Current Score: " + score);
System.out.println("==================================================");
System.out.println();
break;
}
else {
System.out.println("--------------------------------------------------");
System.out.println("Wrong!! " + answer.toUpperCase() + " is NOT the word "
+ "we were thinking of!");
possibleMaxScore--;
score--;
System.out.println("Current Score: " + score);
System.out.println("--------------------------------------------------");
System.out.println();
}
}
}
}

private void loadGameFile(String DataFilePath, String menuOption) {
// Read in game data
try (BufferedReader reader = new BufferedReader(new FileReader(DataFilePath))) {
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.isEmpty() || line.startsWith("#")) {
continue;
}
if (line.startsWith("<") && line.endsWith(">")) {
String tagName = line.substring(1, line.lastIndexOf(">"));
List<String> cluesList = new ArrayList<>();
while ((line = reader.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) {
break;
}
cluesList.add(line);
}
// Which class are we going to create instances of.
switch (menuOption) {
case "1": 
Animals tmp1 = new Animals(tagName, cluesList.toArray(new String[cluesList.size()]));
break;
case "2":
Words tmp2 = new Words(tagName, cluesList.toArray(new String[cluesList.size()]));
break;
}
}
}
}
catch (FileNotFoundException ex) {
Logger.getLogger(CluesDemo.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(CluesDemo.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

单词类:

import java.util.ArrayList;
import java.util.List;

public class Words {

private String word;
private String[] wordClues;
private static final List<Words> wordInstances = new ArrayList<>();

public Words() {
Words.wordInstances.add((this));
}
public Words(String word, String[] wordClues) {
this.word = word;
this.wordClues = wordClues;
Words.wordInstances.add((this));
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String[] getWordClues() {
return wordClues;
}
public void setWordClues(String[] wordClues) {
this.wordClues = wordClues;
}
public static List<Words> getWordInstances() {
return wordInstances;
}

}

Word.dat文件可能看起来像这样:

# For specific Words and clues to those Words.
<Reddit>
A Relatively new social website.
<Facebook>
What has your face and you can read it.
<Java>
Coding language.
Over 3 billion devices use it.
<Assignment>
During this course, you've had an __.
<Game>
PS4's have this ...
<HelloWorld>
First program we learned put this on screen.
Well "Hi" back at ya.
<Weather>
It's raining, what horrible __.
<Religion>
People have different ...
One faith or another.
<Internet>
Uses code.
Has cookies.
You can buy it from the __.
Great place to get content.
www.
<Face>
It's attached to our head.
Has a bunch of features.
It contains two eyes, a nose, and a mouth.
Might have dimples.
Is sometimes dirty after a hard day.

在上面的可运行程序中,要猜测的动物(或单词)是随机选择的。显示的线索也被随机选择用于要猜测的特定动物或单词。得分是基于任何特定动物或单词的线索数量。如果一只特定的动物有6条线索,那么用户有可能通过第一条线索获得6分的正确猜测。对于特定动物,每出现一条线索,这种可能性就会减少1。

这显然可以做得更好,但它很快,这里只是作为您试图实现的另一种可能替代方案的一个例子。这样做也具有相对可扩展性的潜力。而且,文本文件可以容纳大部分数据,这使得编辑、添加和删除变得容易,而不是对所有数据进行硬编码。

首先检查哪个数组有输入字符串,然后获取其索引使用该索引从各个线索数组中获取元素

// converting array to list
List<String> listOfWords = Arrays.asList(words);
List<String> listOfAnimals = Arrays.asList(animals);

从数组中获取输入字符串的索引

int indexInAnimals = listOfAnimals.indexOf(input);
int indexInWords = listOfWords.indexOf(input);

使用索引从数组中获取线索

if(listOfWords.contains(input)) {
clue = wordClues[indexInWords];
} else if (listOfAnimals.contains(input)) {
clue = animalsClues[indexInAnimals];
}
//clue for the input
System.out.println(clue);

输入:panda

输出:

Has a Kung Fu movie

最新更新