我的任务是编写一个基本的猜谜游戏,我已经完成了,但部分任务令我感到困惑。我们被要求在用户输入相同的猜测次数时创建警告。我已经尝试了几种方法来获取之前的用户猜测并将它们与当前用户进行比较,但似乎都没有。谁能帮我这个?我的谷歌技能似乎让我失望了。
我大部分时间都试过这个:
void guessWarning(int confirmedGuess){
int prevGuess = currentGuess;
int currentGuess = confirmedGuess;
if(prevGuess == currentGuess){
text("Same guess, try again",350,350)
}
}
答案 0 :(得分:1)
有多种方法可以解决这个问题。
一个选项是跟踪动态数组中的先前尝试(请参阅ArrayList)。这里有一些代码来说明这个概念:
//create a new list of integers
ArrayList<Integer> guesses = new ArrayList<Integer>();
//in your check function, test if the new value already exists
if(guesses.contains(NEW_GUESS_HERE)){
println("you've already tried this number");
}else{//otherwise add the current guess to keep track of for next time
guesses.add(NEW_GUESS_HERE);
}
另一种选择是使用HashMap。这是一个关联数组,而不是基于索引的数组。此方法更有效,您还可以跟踪每个值的尝试次数。请务必在HashMaps上阅读更多内容:从长远来看,它会对您有所帮助,并可能在短期内给您的导师留下深刻的印象。
这是一个基本的草图来说明这个想法:
//create a new hashmap of integers (key = guess, value = number of times tried)
HashMap<Integer,Integer> guesses = new HashMap<Integer,Integer>();
int answer = '=';
void setup(){}
void draw(){}
void keyPressed(){
guess(keyCode);
println(keyCode);
}
void guess(int newValue){
if(newValue == answer){
println("you guessed it!");
}else{
//check if the value was already recorded
try{
//if there was a value with this key, it's been tried before
int numberOfTries = guesses.get(newValue);
println("you've tried this value",numberOfTries,"times");
//increment the number of times this has beeen attempted
guesses.put(newValue,numberOfTries+1);
}catch(NullPointerException e){
println("it's the first time you try this number, but you haven't guessed it yet");
guesses.put(newValue,1);
}
}
}
类似的选项,但更麻烦的是使用JSONObject。 概念类似:关联数组(尽管键是字符串,而不是int),但您需要将猜测的数字转换为字符串以便首先对其进行索引:
JSONObject guesses = new JSONObject();
int answer = '=';
void setup(){}
void draw(){}
void keyPressed(){
guess(keyCode);
println(keyCode);
}
void guess(int newValue){
if(newValue == answer){
println("you guessed it!");
}else{
//hacky int to string
String newValueStr = newValue+"";
//check if the value was already recorded
if(guesses.hasKey(newValueStr)){
//if there was a value with this key, it's been tried before
int numberOfTries = guesses.getInt(newValueStr);
println("you've tried this value",numberOfTries,"times");
//increment the number of times this has beeen attempted
guesses.setInt(newValueStr,numberOfTries+1);
}else{
println("it's the first time you try this number, but you haven't guessed it yet");
guesses.setInt(newValueStr,1);
}
}
}
一件好事是你可以save对磁盘的猜测,然后load,这样程序就可以回想起之前的猜测,即使它已经重新启动了。 我会给你一个有趣的练习,即在草图开始时尝试加载数据并在草图存在时保存数据。