2013-11-21 70 views
0

我想寫一個函數到我的程序暫停繪製()3秒,當鼠標點擊。當計時器超過3秒時,draw()應該繼續,但不是。問題與定時器和循環()/ noLoop()

Deck playerDeck; 
Deck computerDeck; 

PFont font; 

int timer; //use this to allow cards to stay drawn for 2 or 3 seconds 
int cardsLeft = 52; 

**int savedTime; 
int totalTime = 3000;** //milliseconds 

void setup(){ 
    size(500,500); 
    frameRate(30); 
    playerDeck = new Deck(true,215,364,71,96); 
    computerDeck = new Deck(false,215,40,71,96); 
    font = loadFont("TimesNewRomanPSMT-20.vlw"); 
    textFont(font, 20); 
    textAlign(CENTER); 
    **savedTime = millis();** 
} 

void draw(){ 
    background(255); 

    //draws the players' decks 
    playerDeck.drawDeck(); 
    computerDeck.drawDeck(); 

    //informative text 
    fill(0); 
    text("Player",width/2,493); 
    text("Computer",width/2,27); 
    text(cardsLeft + " Cards left",width/2,height/2+5); 
} 

void mousePressed(){ 
    if(cardsLeft > 0){ //checks cards left aka clicks, limited to 52- size of deck 
    if(playerDeck.deckClicked(mouseX,mouseY)){//checks if player deck is clicked 
     println("You picked a card from your deck"); 
     playerDeck.drawCardAndCompare();//draws a random card for the player from a 2d array suit->card 
     computerDeck.drawCardAndCompare();//draws a random card for the computer from a 2d array suit->card. 
     cardsLeft--; 
    } else if(computerDeck.deckClicked(mouseX,mouseY)){//checks if the player clicked the computers deck. no need for computer interactivity so computer and player draws are simultaneous 
     println("You can't take cards from the computer's deck!"); 
    } else { 
     println("Click on your deck to pick a card");//if the player clicks elsewhere 
    } 
    } else { 
    println("Game over"); //when cards left/clicks equals or is less then 0 
    } 
    **noLoop();** 
} 

**void mouseReleased(){ 
    int passedTime = millis() - savedTime; 
    if(passedTime > totalTime){ 
    loop(); 
    savedTime = millis(); 
    } 
}** 

在按下鼠標時,屏幕上會顯示一對圖像。當釋放鼠標時,計時器應該設置3秒,並且在三秒鐘之後它將激活循環()以繪製圖像。這裏的問題是,按住鼠標按鈕3秒以上會釋放循環(),或者如果在三秒之前釋放鼠標按鈕,則再次點擊。如果我不清楚,我很抱歉,我現在真的很累,但需要完成這項工作。

+0

什麼是millis()savedTime和mp?你需要展示更多的代碼。 – Sionnach733

+0

millis()是一個內置的函數,它存儲自程序啓動以來的毫秒數,mp是舊代碼,但它沒有/不會影響輸出,savedTime是一個int,它位於頂部 –

+0

You已經有了一個解決方案,但這就是爲什麼你的代碼無法工作:只有當鼠標被釋放時,你纔會檢查'passedTime> totalTime'是否一次。你必須把它放在一個循環結構中,使它延遲*直到條件成立,而不是檢查一次並完成它。 – kevinsa5

回答

1

當鼠標釋放後,您可以讓主線程休眠3秒。它應該在時間過後恢復。將您的事件處理程序更改爲:

@Override 
    public void mouseReleased(MouseEvent e) { 
     try { 
      Thread.sleep(3000); 
      //thread will then resume 
     } catch (InterruptedException e1) { 
      e1.printStackTrace(); 
     } 
    } 
+0

謝謝一堆。這正是我想要做的。 –