Objective-C 实现实现2048算法类算法类
参数model有一个二维数组data,及阶数matrix
// .h文件
@class DataModel;
@interface Algorithm : NSObject
@property (nonatomic,assign) int addScore; // 加分
- (void)caculateTop:(DataModel *)model; // 上滑规则
- (void)caculateBottom:(DataModel *)model; // 下滑规则
- (void)caculateLeft:(DataModel *)model; // 左滑规则
- (void)caculateRight:(DataModel *)model; // 右滑规则
- (BOOL)randNewOne:(DataModel *)data;
- (int)getAddScore;
@end
// .m文件
@implementation Algorithm
#pragma mark - 滑动规则
- (void)caculateTop:(DataModel *)model {
[self up_remove_blank:model];
[self up:model];
}
- (void)caculateBottom:(DataModel *)model {
[self down_remove_blank:model];
[self down:model];
}
- (void)caculateLeft:(DataModel *)model {
[self left_remove_blank:model];
[self left:model];
}
- (void)caculateRight:(DataModel *)model {
[self right_remove_blank:model];
[self right:model];
}
- (int)getAddScore {
int temp = _addScore;
_addScore = 0;
return temp;
}
#pragma mark - 新一个
- (BOOL)randNewOne:(DataModel *)model {
array data = [model getData];
int all = 0;
for (int i=0; i<model.matrix; i++) {
for (int j=0; j<model.matrix; j++) {
if (data[i][j] == 0) {
all = all + 1;
}
}
}
if (all == 0) {
return NO;
}
int index = arc4random() % all;
all = 0;
for (int i=0; i<model.matrix; i++) {