/*
两个对象,玩家和机器人(同时作裁判),询问是否继续游戏。机器人 继承人 并 重写出拳和显示出拳 的方法。不太合理,仅做练习。
*/
#import <Foundation/Foundation.h>
#import "Bot.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;
char sel = 0;
do
{
[p1 fistSelectedAndShow];
[b1 fistAutoShowAndJudgeWith:p1];
NSLog(@"是否继续游戏:y-继续,n-退出");
rewind(stdin);
scanf("%c",&sel);
}while (sel != 'n' && 'N' != sel);
NSLog(@"See You!");
}
return 0;
}
//
// Person.h
// 150819-OC2
//
// Created by LongMa on 15/8/23.
// Copyright (c) 2015年 itcast. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Person : NSObject
{
NSString* _name;
short _fist;
short _score;
}
- (void)setName:(NSString*)name;
- (NSString*)name;
- (void)setFist:(short)fist;
- (short)fist;
- (void)setScore:(short)score;
- (short)score;
- (void)fistSelectedAndShow;
@end
/*
提示玩家选择出拳,接收玩家输入,输出玩家选择
*/
#import "Person.h"
@implementation Person
- (void)setName:(NSString*)name
{
_name = name;
}
- (NSString*)name;
{
return _name;
}
- (void)setFist:(short)fist
{
_fist = fist;
}
- (short)fist
{
return _fist;
}
- (void)setScore:(short)score
{
_score = score;
}
- (short)score
{
return _score;
}
- (void)fistSelectedAndShow
{
do
{
NSLog(@"请选择出拳:1-剪刀,2-石头,3-布");
_fist = -1;//防输入字母仍通过的bug
rewind(stdin);
scanf("%hd",&_fist);
}while (_fist < 1 || _fist > 3);
NSLog(@"%@出的是:%@", _name, (1 == _fist) ? @"剪刀": ((2 == _fist) ? @"石头": @"布") );
}
@end
//
// Bot.h
#import "Person.h"
@interface Bot : Person
- (void)fistAutoShowAndJudgeWith:(Person*)per;
@end
/*
机器人继承了人的属性和方法,重写方法即可。随机产生1-3的数,并与玩家的比较(传玩家对象)。输出结果和比分。
*/
#import "Bot.h"
#import <stdlib.h>
@implementation Bot
- (void)fistAutoShowAndJudgeWith:(Person *)per
{
_fist = arc4random_uniform(3) + 1;
short flag = _fist - per.fist;
NSLog(@"%@出的是:%@", _name, (1 == _fist) ? @"剪刀": ((2 == _fist) ? @"石头": @"布") );
if (flag == -2 || 1 == flag )//机器赢: 1 - 3, 2 - 1 , 3 - 2
{
_score++;
NSLog(@"%@赢了",_name);
}else if (flag == 0)
{
NSLog(@"平局!");
}else
{
per.score++;
NSLog(@"%@赢了", per.name);
}
NSLog(@"现在比分:%@:%hd分---------------%@:%hd分",per.name, per.score, _name, _score);
}
@end