猜拳游戏--最高效版本

来源:互联网 发布:淘宝假授权书处罚 编辑:程序博客网 时间:2024/05/20 20:02
/*概述:玩家和电脑出拳,赢方加分,输的一方不加分。每一局之后询问玩家是否继续。    分析:对象1:玩家,同电脑。方法:被询问时选择出拳并输出选择(枚举)         对象2:电脑,属性:姓名,出的拳头,分数。方法:出拳,判断输赢(传玩家对象)并计分。        每结束一局,进行询问。        电脑设置成玩家的继承,方便。 add:名字和分数在创建对象同时要初始化。自定义构造方法即可。用alloc,init。加方法响应。ps:@propert生成的属性虽然是私有的,可以被子类继承,不能直接访问。但是可以通过父类的getter和setter方法  间接访问,如super.name,实质就是调用父类的方法进行间接访问和修改。 */#import <Foundation/Foundation.h>#import "Bot.h"int main(int argc, const char * argv[]){    @autoreleasepool    {        Person* player = [[Person alloc]initWithName:@"至尊宝" andScore:0];        Bot* b1 =[[Bot alloc]initWithName:@"紫霞" andScore:0];        unsigned char ifContinue = 0;        do        {            if ([player respondsToSelector:@selector(fistMethodOfPerson)])//判断player对象中是否有fistMethodOfPerson方法            {                [player fistMethodOfPerson];            }            [b1 fistAutoAndjudgeWith:player];             NSLog(@"是否继续猜拳:y-继续,n-结束");            rewind(stdin);            scanf("%c",&ifContinue);                }while (ifContinue != 'n' || ifContinue != 'N');        NSLog(@"See you!");    }    return 0;}////  Person.h//  150819-OC2#import <Foundation/Foundation.h>//typedef enum {jianDan, shiTou, bu}fistSelect;@interface Person : NSObject@property short  fist;@property NSString* name;@property short score;- (void)fistMethodOfPerson;- (instancetype)initWithName:(NSString*)name andScore:(short)score;@end////  Person.m//  150819-OC2#import "Person.h"@implementation Person- (void)fistMethodOfPerson{    do    {        NSLog(@"%@请选择出拳:1-剪刀,2-石头,3-布",_name);        rewind(stdin);        _fist = -1;//防多次输入时输入字母也满足条件的bug        scanf("%hd",&_fist);        if (_fist >=1 && _fist <= 3)//使得重复输入非法数字时不应该有出拳提示        {            NSLog(@"%@出的是:%@",_name, _fist == 1 ? @"剪刀" :(_fist == 2 ? @"石头" : @"布"));        }    }while (_fist < 1 || _fist > 3);    }- (instancetype)initWithName:(NSString *)name andScore:(short)score{    if (self = [super init])    {        self.name  = name;        self.score = score;    }    return self;}@end////  Bot.h#import "Person.h"@interface Bot : Person- (void)fistAutoAndjudgeWith:(Person*)player;@end////  Bot.m#import "Bot.h"#import <stdlib.h>@implementation Bot- (void)fistAutoAndjudgeWith:(Person *)player{    super.fist = arc4random_uniform(3) + 1;    NSLog(@"%@出的是:%@",super.name, super.fist == 1 ? @"剪刀" :(super.fist == 2 ? @"石头" : @"布"));    if (super.fist - player.fist == 2 || -1 == super.fist - player.fist)//人赢:1 - 2  2 - 3  3 - 1    {        player.score++;        NSLog(@"%@赢了!",player.name);    }else if(super.fist == player.fist)    {        NSLog(@"平局");    }else    {        super.score++;        NSLog(@"%@赢了!",super.name);    }    NSLog(@"比分为%@:%hd------%@:%hd",player.name, player.score, super.name,super.score);}@end

0 0
原创粉丝点击