開發環境:Mac OS X 虛擬機 10.9.3 + Xcode 6,參考書《iPhone 30天精通》。
這個練習的目標很單純:螢幕每秒隨機換一張撲克,當黑桃 A 出現時,使用者要盡快點擊;點對了要算出反應時間,點錯了要提示。看似簡單,卻涵蓋了 UIImageView、NSTimer、NSDate 計時、UIAlertView 回呼與 if-else 狀態判斷等一組基礎知識。
imageNamed: 即可。#import <UIKit/UIKit.h>
@interface ViewController : UIViewController {
IBOutlet UIImageView *pokerImage;
NSDate *startDate;
NSTimer *timer;
}
@property UIImageView *pokerImage;
@property NSDate *startDate;
@property NSTimer *timer;
- (IBAction)pokerPressed;
@end
這裡有個設計上的選擇值得說明:我沒有採用書上的寫法,而是用循環計時器來驅動。原因是循環計時器對我來說思路更直白——一個 timer 反覆呼叫同一個換牌方法,點擊時暫停它即可。書上的做法在這個題目上或許更精簡,但對初學者而言,先把邏輯寫對比寫得漂亮重要。
int spadeOn;
- (void)viewDidLoad {
[super viewDidLoad];
// 起始顯示撲克背面
pokerImage.image = [UIImage imageNamed:@"0000.png"];
// 遊戲說明。只有一個「開始遊戲」按鈕,按下後對話框即關閉
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"考反應撲克遊戲"
message:@"當黑桃出現時以最快速度按下撲克"
delegate:self
cancelButtonTitle:@"游戲開始"
otherButtonTitles:nil, nil];
[alert show];
}
接下來就是啟動遊戲的方法。這是 UIAlertView 的標準回呼,不需要額外設定 delegate 協定,只要方法名寫對就會被呼叫:
- (void)alertView:(UIAlertView *)alertView
didDismissWithButtonIndex:(NSInteger)buttonIndex {
// 讓 spadeOn 歸零,這樣一開始就點擊會被判定為錯誤
spadeOn = 0;
// 判斷計時器是否已在運行;沒開就開,開了就不動
// isValid 回傳布林值,用來檢查計時器狀態
if (![self.timer isValid]) {
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(onAceTimer)
userInfo:nil
repeats:YES];
}
}
這裡是我卡最久的 bug:停止計時器的程式碼一直不生效。原因在於我漏寫了 self.timer = 這個指派,導致 timer 始終是個空指標——你無法對一個空指標的計時器執行 invalidate。加上指派之後,暫停就正常了。這件事的教訓是:建立物件與持有物件是兩回事,一定要把回傳值接住。
- (IBAction)pokerPressed {
// 計時器開著就關掉
if (self.timer) {
[self.timer invalidate];
self.timer = nil;
}
NSString *reactionTime;
if (spadeOn == 1) {
// timeIntervalSinceNow 回傳的是「現在減去該時刻」,
// 因為 startDate 是過去,所以結果為負,需乘 -1000 轉成正毫秒
double noSeconds = (double)[self.startDate timeIntervalSinceNow] * -1000;
reactionTime = [NSString stringWithFormat:@"響應速度為 %.0f 毫秒,繼續。", noSeconds];
}
if (spadeOn == 0) {
reactionTime = @"請不要急,等黑桃A出現再按";
}
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"再來一次"
message:reactionTime
delegate:self
cancelButtonTitle:@"確定"
otherButtonTitles:nil, nil];
[alert show];
}
由於提示框關閉時會再次觸發上面那個 didDismissWithButtonIndex:,遊戲就自動進入下一輪——這正好形成了一個閉環,不需要額外寫「重新開始」的邏輯。
- (void)onAceTimer {
int rNumber = rand() % 4; // 四張牌,對應 0、1、2、3
switch (rNumber) {
case 0:
pokerImage.image = [UIImage imageNamed:@"11.png"];
spadeOn = 1; // 黑桃出現
startDate = [NSDate date]; // 記下時間,後續算反應速度用
break;
case 1:
pokerImage.image = [UIImage imageNamed:@"21.png"];
spadeOn = 0;
break;
case 2:
pokerImage.image = [UIImage imageNamed:@"31.png"];
spadeOn = 0;
break;
case 3:
pokerImage.image = [UIImage imageNamed:@"41.png"];
spadeOn = 0;
break;
}
}
四種隨機結果中只有第一種是黑桃 A,所以只有它會把 spadeOn 設為 1,其餘皆為 0。後面 pokerPressed 就是靠這個變數判斷使用者點對還是點錯——這是最典型的「用一個狀態變數把非同步事件串起來」的做法。
這個版本是為學習而寫的,有幾處明顯可以再打磨:
showDataForAlbumAtIndex 這類 API 都已 deprecated,新專案應改用 UIAlertController;計時可改用 CACurrentMediaTime() 取得更高精度。但作為一個「用循環計時器把狀態、計時與 UI 串起來」的入門練習,它確實把該練的都練到了。