OC實現猜拳遊戲2.0(更簡單方法,用兩個物件、繼承、條件表示式、@proterty增強和點語法)
阿新 • • 發佈:2019-01-01
/*概述:玩家和電腦出拳,贏方加分,輸的一方不加分。每一局之後詢問玩家是否繼續。 分析:物件1:玩家,同電腦。方法:被詢問時選擇出拳並輸出選擇(列舉) 物件2:電腦,屬性:姓名,出的拳頭,分數。方法:出拳,判斷輸贏(傳玩家物件)並計分。 每結束一局,進行詢問。 電腦設定成玩家的繼承,方便。 */ #import <Foundation/Foundation.h> #import "Bot.h" int main(int argc, const char * argv[]) { @autoreleasepool { // id player = [Person new];//萬能指標 只能呼叫方法,不能使用點語法,也不能訪問成員變數 Person* player = [Person new]; player.name = @"至尊寶"; player.score = 0; // player.fistOfPerson = -1; Bot* b1 =[Bot new]; b1.nameOfBot = @"青霞"; b1.score = 0; b1.fistOfBot = -1; unsigned char ifContinue = 0; do { [player fistMethodOfPerson]; [b1 fistAutoAndjudgeWith:player]; NSLog(@"是否繼續猜拳:y-繼續,n-結束"); rewind(stdin); scanf("%c",&ifContinue); }while (ifContinue == 'y' || ifContinue == 'Y'); NSLog(@"Be Better!"); } return 0; } // // Person.h // 150819-OC2 #import <Foundation/Foundation.h> //typedef enum {jianDan, shiTou, bu}fistSelect; @interface Person : NSObject @property short fistOfPerson; @property NSString* name; @property short score; - (void)fistMethodOfPerson; @end // // Person.m // 150819-OC2 #import "Person.h" @implementation Person - (void)fistMethodOfPerson { do { NSLog(@"%@請選擇出拳:1-剪刀,2-石頭,3-布",_name); rewind(stdin); _fistOfPerson = -1;//防多次輸入時輸入字母也滿足條件的bug scanf("%hd",&_fistOfPerson); if (_fistOfPerson >=1 && _fistOfPerson <= 3)//使得重複輸入非法數字時不應該有出拳提示 { NSLog(@"%@出的是:%@",_name, _fistOfPerson == 1 ? @"剪刀" :(_fistOfPerson == 2 ? @"石頭" : @"布")); } }while (_fistOfPerson < 1 || _fistOfPerson > 3); } @end // // Bot.h #import "Person.h" @interface Bot : Person @property short fistOfBot; //父類是自動生成的屬性,是存私有的變數,不能繼承和訪問,必須重新@property宣告(自動實現) @property NSString* nameOfBot;//不能與自動生成的父類屬性同名 @property short scoreOfBot; - (void)fistAutoAndjudgeWith:(Person*)player; @end // // Bot.m #import "Bot.h" #import <stdlib.h> @implementation Bot - (void)fistAutoAndjudgeWith:(Person *)player { _fistOfBot = arc4random_uniform(3) + 1; NSLog(@"%@出的是:%@",_nameOfBot, _fistOfBot == 1 ? @"剪刀" :(_fistOfBot == 2 ? @"石頭" : @"布")); if (_fistOfBot - player.fistOfPerson == 2 || -1 == _fistOfBot - player.fistOfPerson)//人贏:1 - 2 2 - 3 3 - 1 { player.score++; NSLog(@"%@贏了!",player.name); }else if(_fistOfBot == player.fistOfPerson) { NSLog(@"平局"); }else { _scoreOfBot++; NSLog(@"%@贏了!",_nameOfBot); }
<pre name="code" class="objc"> NSLog(@"比分為%@:%hd------%@:%hd",player.name, player.score, _nameOfBot,_scoreOfBot);
}@end
<img src="https://img-blog.csdn.net/20150820214807117?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="" />