OC学习--<猜拳游戏> 之 通过面向对象思想实现

首先是看了一下大概的需求,然后按照自己的想法写了一个项目,主要是通过创建人的类和机器人两个类,用面向对象的思想写的一个小项目,
实现提示玩家出拳,然后机器人随机出拳,判断输赢并记录比分的功能;首先本篇记录的是beta版本.

#import <Foundation/Foundation.h>

typedef enum
{
    shitou = 1,
    jiandao,
    bu
}FistTypeEnum;

@interface Human : NSObject
{
    @public
    NSString *_name;
    int _fisttype;
    int _score;
}


-(void)fistChuWith:(Robot *)robot;

- (NSString *)zhuanHuan:(int)fistType;

- (void)biJiao:(Robot *)robot;

@end

@implementation Human

-(void)fistChuWith:(Robot *)robot;
{
    char yesOrNo='y';
    NSLog(@"叮叮叮~~![%@]正在和[%@]进行猜拳比赛~!!",_name,robot->_name);
    while(yesOrNo=='y')
    {
        NSLog(@"[%@],请出拳! 1.石头  2.剪刀  3.布",_name);
        scanf("%d",&_fisttype);
        NSLog(@"[%@]出的是%@",_name,[self zhuanHuan:(_fisttype)]);
        [self biJiao:robot];
        NSLog(@"亲,你还要玩吗?y/n?");
        rewind(stdin);
        scanf("%c",&yesOrNo);
        rewind(stdin);
    }
    if (yesOrNo=='n')
    {
        NSLog(@"欢迎你下次再来!��");
    }

}

- (NSString *)zhuanHuan:(int)fistType
{
    switch (fistType)
    {
        case 1:
            return @"石头"    ;
            break;
        case 2:
            return @"剪刀"    ;
            break;
        case 3:
            return @"布"    ;
            break;
        default:
            return @"爆炸";
            break;
    }
}

- (void)biJiao:(Robot *)robot
{
    [robot fistChu];
    NSLog(@"[%@]出的是 %@",_name,[self zhuanHuan:(robot->_fistType)]);

    if (robot->_fistType - _fisttype == -1 || robot->_fistType - _fisttype == 2 )
    {
        NSLog(@"[%@]赢了",_name);
        (robot->_score) ++;
    }
    else if (robot->_fistType - _fisttype == 0 )
    {
        NSLog(@"你们打平了");
    }else
    {
        NSLog(@"[%@]赢了",robot->_name);
        _score++;
    }

    NSLog(@"[%@]和[%@] 比分是 %d:%d",_name,robot->_name,_score,robot->_score);
}
@end

@interface Robot : NSObject

{
    @public
    NSString *_name;
    int _fistType;
    int _score;
}

- (void)fistChu;

@end

@implementation Robot

- (void)fistChu
{
    _fistType = arc4random_uniform(3)+1;
}

@end

int main(int argc, const char * argv[])
{
    @autoreleasepool
    {
        Human *h1 = [Human new];
        Robot *r1 = [Robot new];

        h1->_name = @"小明";
        r1->_name = @"小黑";

        [h1 fistChuWith:r1];

    }
    return 0;
}

但这样子有不足的地方,就是思路不够清晰,只是调用了人的一个猜拳的行为就把所有这些行为都干完了,应该还要加入一个第三方的类来
判断和宣布结果,而不是猜拳的人来自己确定,因此,下一步的改进就是这个方面.

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-08-19 23:36  JimmyPeng4iOS  阅读(195)  评论(0编辑  收藏  举报