2017-05-15 36 views
1

我的任務是編寫一個基本的猜謎遊戲,我已經完成了,但部分任務讓我困惑。我們被要求在用戶多次輸入相同的猜測時創建警告。我已經嘗試了幾種方法來接受以前的用戶猜測並將它們與當前的用戶進行比較,但似乎沒有任何效果。誰能幫我這個?我的Google技巧似乎讓我失望了。如何比較用戶輸入猜測和他們之前的猜測?

主要是我已經試過這樣:

void guessWarning(int confirmedGuess){ 
     int prevGuess = currentGuess; 
     int currentGuess = confirmedGuess; 

    if(prevGuess == currentGuess){ 
     text("Same guess, try again",350,350) 
    } 
    } 

回答

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它,所以程序可以回憶以前的猜測,即使它重新啓動。 我會離開你試圖在草圖開始時加載數據並在草圖存在時保存數據的有趣練習。

+0

謝謝你。實際上,當我發佈這些代碼後,我確實得到了代碼,但是我被家務事後分散注意力,忘記更改帖子。儘管你已經回答了,但肯定會對我的同學有所幫助。他們也被卡住了:D – Angus