电子狗宠物游戏--command Line Tool测试
实现功能--宠物实例有方法 eat , talk , saygoodbye, 有实例变量age 和energy
每当talk一次 energy -1 ,energy没有时会要求eat, talk可以有3种选择。
有兴趣的同学可以看一下。
//
// Pet.h
// Wpet
//
// Created by 王 健 on 14-3-18.
// Copyright (c) 2014年 WJ. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Pet : NSObject
{
NSString *name;
int age;
int energy;
}
-(Pet *)initWithName:(NSString*)name andAge:(int)age;
-(void)eat;
-(void)talk:(NSString* )question;
-(void)sayGoodbye;
@end
//
//
// Pet.m
// Wpet
//
// Created by 王 健 on 14-3-18.
// Copyright (c) 2014年 WJ. All rights reserved.
//
#define MAX_ENERGY 10
#import "Pet.h"
@implementation Pet
-(Pet *)initWithName:(NSString*)n andAge:(int)a
{
self =[super init];
if (self) {
name = n;
age = a;
energy = 5;
return self;
}
return nil;
}
-(void)eat
{
char buffer1[20];
scanf("%s" ,buffer1);
NSString *foodstr = [NSString stringWithUTF8String:buffer1];
int foods = [foodstr intValue];
if(foods <= 0 )
NSLog(@"再耍我,小心扁你!");
else{
energy += foods;
if(energy<= MAX_ENERGY)
{
NSLog(@"好好吃啊!");
}else
{
energy = MAX_ENERGY;
NSLog(@"吃饱了!");
}
}
}
-(void)talk:(NSString* )question
{
energy--;
if (energy<0) {
energy = 0;
NSLog(@"饿死了,给我食物!");
[self eat];
return;
}
if ([question rangeOfString:@"age"].location !=NSNotFound) {
if(age<=0)
NSLog(@"哥的年龄是个秘密!");
else
NSLog(@"我今年%i岁",age);
}
else if ([question rangeOfString:@"name"].location !=NSNotFound)
{
NSLog(@"我就是%@啊,你真健忘!",name);
}
else if ([question rangeOfString:@"eat"].location !=NSNotFound)
{
NSLog(@"请输入食物数量");
[self eat];
}
else
{
NSLog(@"听不懂!");
}
}
-(void)sayGoodbye
{
NSLog(@"再见!");
}
@end
/
//
// main.m
// Wpet
//
// Created by 王 健 on 14-3-18.
// Copyright (c) 2014年 WJ. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Pet.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Pet *mypet = [[Pet alloc] initWithName:@"小强" andAge:50];
char bufff[20];
NSString *question;
BOOL ifend = false;
while (ifend == false)
{
NSLog(@"请输入:");
scanf("%s",bufff);
question = [NSString stringWithUTF8String:bufff];
if([question isEqualToString:@"exit"])
{
[mypet sayGoodbye];
ifend = true;
[mypet release],mypet = nil;
}else
[mypet talk:question];
}
}
return 0;
}