OC實現猜拳遊戲(用了繼承特性)
阿新 • • 發佈:2019-01-03
/* main.m // 150819-OC2 // Created by LongMa on 15/8/19. 物件: 1.player 屬性:姓名,出的拳頭,分數 方法:出拳(公共列舉,接收,顯示) 數字轉換為漢字 方法 2.bot(player子類) 屬性:同上//要重新定義?不需要! 3.judge 屬性:姓名 方法:根據玩家和bot的出拳判斷並輸出結果,贏方加1分 是否繼續。 */ #import <Foundation/Foundation.h> //#import "Person.h"//bot.h 已經包含,故一般只寫子類的標頭檔案即可 #import "Bot.h"//我去,不加標頭檔案會報未定義!so:子類也要在主函式裡新增標頭檔案! #import "Judge.h" int main(int argc, const char * argv[]) { @autoreleasepool { Person* p1 = [Person new]; p1->_name = @"至尊寶"; p1->_score = 0; Bot *b1 = [Bot new]; b1->_name = @"青霞"; b1->_score = 0; Judge* j1 = [Judge new]; j1->_name = @"觀音菩薩"; char ch1; do { [p1 acptAndshowFist]; [b1 fistRandomShow]; [j1 judgeBetween:p1 and:b1]; NSLog(@"是否繼續?繼續請按y,取消請按n"); rewind(stdin); scanf("%c",&ch1); }while (ch1 == 'y'|| ch1 == 'Y'); NSLog(@"Be Better!"); } return 0; } /* Person.h 1.player 屬性:姓名,出的拳頭,分數 方法:出拳(公共列舉,接收,顯示) 數字轉換為漢字 方法 */ #import <Foundation/Foundation.h> //#import "Bot.h"//子類標頭檔案的決不能新增到父類標頭檔案裡 typedef enum{jiaoDao, shiTou, bu} fistSelected; @interface Person : NSObject {@public NSString* _name; fistSelected _fist; int _score; } - (void)acptAndshowFist; - (NSString*) numToChinese:(int )num; @end //Person.m #import "Person.h" @implementation Person - (void)acptAndshowFist { do { NSLog(@"請選擇您要出的拳頭:1-剪刀,2-石頭,3-布"); _fist = -1;//如果不賦值為1-3之外,迴圈回來輸入‘y’時,_fist等於上次輸入的值,while條件會滿足,會導致bug rewind(stdin); scanf("%d",&_fist); }while (_fist <1 || _fist > 3); NSString* fist1 = [self numToChinese:_fist]; NSLog(@"[%@]出的拳頭為:%@",_name, fist1); } - (NSString *)numToChinese:(int)num { switch (num) { case 1: return @"剪刀"; break; case 2: return @"石頭"; case 3: return @"布"; default: break; } return 0; } @end //bot.h //2.bot(player子類) #import <Foundation/Foundation.h> #import "Person.h" #import <stdlib.h> @interface Bot : Person { // fistSelected _fistBot; } - (void)fistRandomShow; @end //bot.m #import "Bot.h" @implementation Bot -(void)fistRandomShow { _fist = arc4random_uniform(3) + 1;//直接使用的父類的變數,並沒有同名重定義! NSString* fist1 = [self numToChinese:_fist]; NSLog(@"[%@]出的拳頭為:%@",_name, fist1); } @end /*Judge.h 3.judge 屬性: 姓名 方法:根據玩家和bot的出拳判斷並輸出結果,贏方加1分 */ #import <Foundation/Foundation.h> #import "Person.h" #import "Bot.h" //不能少?不能! @interface Judge : NSObject { @public NSString* _name; } - (void)judgeBetween:(Person*)person and:(Bot*)bot; @end //Judge.m #import "Judge.h" @implementation Judge - (void)judgeBetween:(Person *)person and:(Bot *)bot { int sub = person->_fist - bot->_fist; if (sub == -2 || sub == 1)// 猜拳贏法:1- 3 ,2- 1, 3 - 2 { NSLog(@"【%@】贏了!",person->_name); person->_score++; }else if(sub == 0) { NSLog(@"平局"); }else { NSLog(@"【%@】贏了",bot->_name); bot->_score++; } NSLog(@"比分為%@:%d-------VS------%@:%d",person->_name, person->_score, bot->_name, bot->_score); } @end