#import <Foundation/Foundation.h>
#import "Zombie.h"
#import "BlockZombie.h"
#import "IronHatZombie.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
/*
打殭屍。需求:
定義普通殭屍類:實例變量:殭屍種類、殭屍總血量、殭屍每次失血量。方法:初始化、被打擊失血、死亡。
定義路障殭屍類:實例變量:殭屍種類、殭屍總血量、殭屍每次失血量,道具,弱點。方法:初始化、被打擊失血、失去裝備、死亡。
定義鐵桶殭屍類:實例變量:殭屍種類、殭屍總血量、殭屍每次失血量,道具,弱點。方法:初始化、被打擊失血、失去裝備、死亡。
For循環 模擬攻擊,創建3個殭屍對象。
(1)、普通殭屍。總血量50,每次失血3.
(2)、路障殭屍。總血量80,有路障時,每次失血2,血量剩餘一半時,失去路障,每次失血3.
(3)、鐵桶殭屍。總血量120,有鐵桶時,每次失血1,血量剩餘1/3時,失去鐵桶,每次失血3.
循環攻擊過程中:每個殭屍被攻擊時,輸出本次丟失血量,剩餘血量。丟失道具時,輸出丟失的道具。殭屍死亡時,輸出已死亡。
最後一個殭屍死亡時,攻擊停止,循環結束。輸出總攻擊次數。
*/
Zombie * zombie = [[Zombie alloc] initWithKind:@"普通殭屍" hp:50 lostHp:3];
while (zombie->_currentHp > 0) {
[zombie lostHpMethod];
}
BlockZombie * blockZombie = [[BlockZombie alloc] initWithKind:@"路障殭屍" hp:80 lostHp:2 equipment:@"英武路障之盔" weakness:2];
while (blockZombie->_currentHp >0) {
[blockZombie lostHpMethod];
}
IronHatZombie * ironZombie = [[IronHatZombie alloc] initWithKind:@"鐵桶殭屍" hp:120 lostHp:1 equipment:@"巨鯨之鐵桶聖衣" weakness:3];
while (ironZombie->_currentHp >0) {
[ironZombie lostHpMethod];
}
}
return 0;
}
#import <Foundation/Foundation.h>
@interface Zombie : NSObject
{
/*
定義普通殭屍類:實例變量:殭屍種類、殭屍總血量、殭屍每次失血量。方法:初始化、被打擊失血、死亡。
*/
@public
NSString * _kind;//種類
int _hp;
int _lostHp;
int _currentHp;//當前剩餘的血量
}
- (id)initWithKind:(NSString *)kind hp:(int)hp lostHp:(int)lostHp;
- (void)lostHpMethod;//被打擊失血
- (void)dead;//死透
@end
#import "Zombie.h"
@implementation Zombie
- (id)initWithKind:(NSString *)kind hp:(int)hp lostHp:(int)lostHp
{
self = [super init];
if (self) {
_kind = kind;
_hp = hp;
_lostHp = lostHp;
_currentHp = hp;
}
return self;
}
- (void)lostHpMethod
{
_currentHp = _currentHp - _lostHp;
if (_currentHp <= 0) {
//殭屍已經死亡
_currentHp = 0;
NSLog(@"%@被削掉%d血,還有%d血",_kind,_lostHp,_currentHp);
[self dead];//self用來調用自己類中的其他方法
}
else
{
//如果沒死,輸出血量
NSLog(@"%@被削掉%d血,還有%d血",_kind,_lostHp,_currentHp);
}
}//被打擊失血
- (void)dead
{
NSLog(@"%@死啦",_kind);
}//死透
@end
#import "Zombie.h"
@interface BlockZombie : Zombie
{
NSString * _equipment;
int _weakness;
}
- (id)initWithKind:(NSString *)kind hp:(int)hp lostHp:(int)lostHp equipment:(NSString *)equipment weakness:(int)weakness;
- (void)lostEquipment;//丟失裝備
@end
#import "BlockZombie.h"
@implementation BlockZombie
-(id)initWithKind:(NSString *)kind hp:(int)hp lostHp:(int)lostHp equipment:(NSString *)equipment weakness:(int)weakness
{
self = [super initWithKind:kind hp:hp lostHp:lostHp];
if (self) {
_equipment = equipment;
_weakness = weakness;
}
return self;
}
- (void)lostEquipment
{
_lostHp = 3;//裝備丟失,每次掉血量增加
NSLog(@"%@的%@丟了",_kind,_equipment);
_equipment = nil;//把裝備扔掉
}
//重寫掉血的方法
-(void)lostHpMethod
{
//warning _weakness的作用
if ( _equipment!= nil && _currentHp <= _hp/_weakness) {
[self lostEquipment];
}
[super lostHpMethod];
}
@end
#import "BlockZombie.h"
@interface IronHatZombie : BlockZombie
@end
#import "IronHatZombie.h"
@implementation IronHatZombie
@end