您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 入門專案:用 NSTimer 做「考反應撲克遊戲」

編輯:iOS 開發綜合

遊戲規則

畫面會以每秒一張的速度隨機閃過撲克牌,其中只有黑桃 A 是目標。看到黑桃 A 就立刻點擊撲克,系統會計算從它出現到你按下之間的毫秒數,作為反應速度成績。按太早則提示再等一等。

頭檔宣告

 @interface ViewController : UIViewController {
    IBOutlet UIImageView *pokerImage;
    NSDate *startDate;
    NSTimer *timer;
}

@property UIImageView *pokerImage;
@property NSDate *startDate;
@property NSTimer *timer;

- (IBAction)pokerPressed;

@end

UIImageView 是這裡的新角色,專門用來顯示圖片。把 imageView 拉進 storyboard 調整好尺寸,之後只要一行就能換圖:

 pokerImage.image = [UIImage imageNamed:@"0000.png"];

開場說明

在 viewDidLoad 中先擺好牌背,再彈一個只有單一「開始遊戲」按鈕的提示框。

 - (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 關閉後會自動呼叫 didDismissWithButtonIndex,不需要實作任何額外代理設定,只要方法名寫對。正好可以拿它當作「按下開始」的入口。

 - (void)alertView:(UIAlertView *)alertView
    didDismissWithButtonIndex:(NSInteger)buttonIndex {

    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 始終是 nil 空指針,對 nil 送 invalidate 自然什麼也不會發生。這個細節值得記住:Objective-C 對 nil 送訊息不會報錯,只會靜默無事,這類 bug 因此特別難查。

點擊撲克的回應

把一顆放大的透明 UIButton 鋪在 imageView 上方,點擊畫面就等於點擊按鈕。

 - (IBAction)pokerPressed {
    // 先停掉計時器,避免邊算時間邊換牌
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }

    NSString *reactionTime;
    if (spadeOn == 1) {
        // timeIntervalSinceNow 回傳負值,乘 -1000 換成毫秒
        double noSeconds = (double)[self.startDate timeIntervalSinceNow] * -1000;
        reactionTime = [[NSString alloc] initWithFormat:@"響應速度為%1.0f毫秒,繼續。", noSeconds];
    }
    if (spadeOn == 0) {
        reactionTime = @"請不要急,等黑桃A出現再按";
    }

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"再來一次"
        message:reactionTime delegate:self
        cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
    [alert show];
}

換牌的計時器方法

用 rand() % 4 產生 0 到 3 的亂數,對應四張牌。只有 case 0 是黑桃 A,此時把旗標 spadeOn 設為 1 並記錄當前時間。

 - (void)onAceTimer {
    int rNumber = rand() % 4;
    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;
    }
}

這個版本可以再改進的地方

一、亂數品質。rand() 在 C 標準中並不保證均勻,且每次啟動 App 若未呼叫 srandom() 搭配時間播種,產生的序列會完全相同。改用 arc4random_uniform(4) 會好得多。

二、可能出現連續多張黑桃。目前每張牌獨立隨機,因此可能連開三次黑桃 A。若要更公平,應該先建立一個牌組陣列、洗牌後依序發牌。

三、計時器與 RunLoop 模式。如果遊戲畫面放在可滾動容器中,拖動時 timer 會暫停。需要改用 NSRunLoopCommonModes。

四、UIAlertView 已廢棄。iOS 8 之後應改用 UIAlertController,並且它的回呼是透過 completion handler 而非 delegate 方法:

 UIAlertController *alert = [UIAlertController
    alertControllerWithTitle:@"再來一次" message:reactionTime
    preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault
    handler:^(UIAlertAction *action) { /* 重新開始遊戲 */ }]];
[self presentViewController:alert animated:YES completion:nil];

用 handler 反而更清楚:遊戲重啟的邏輯寫在自己那顆按鈕的 closure 裡,不必再靠「判斷是哪個 buttonIndex」去分流。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved