iOS 拼图游戏
2017-05-26 本文已影响158人
ldclll
使用UICollectionView实现简单的拼图游戏,思路就是使用有图的cell与空白的cell进行交换
初始化截图游戏胜利截图
首先定义model类并实现相应的方法
//初始化
- (instancetype)initWithSerie:(NSInteger)serie;
//一二维转换
- (NSInteger)indexWithPoint:(CGPoint)point;
- (CGPoint)pointWithIndex:(NSInteger)index;
//设置胜利数组
- (void)setWinArr;
//设置游戏数组
- (void)setPlayArr;
//设置空白位置
//- (void)removeNumber:(NSInteger)num;
- (BOOL)isWin;
//交换位置
- (void)changeLocation:(CGPoint)cPoint :(CGPoint)wPoint;
//返回基点
- (CGPoint)upPoint;
- (CGPoint)downPoint;
- (CGPoint)leftPoint;
- (CGPoint)rightPoint;
//判断是否越界
- (BOOL)isUpOut:(CGPoint)point;
- (BOOL)isDownOut:(CGPoint)point;
- (BOOL)isLeftOut:(CGPoint)point;
- (BOOL)isRightOut:(CGPoint)point;
//控制器
- (void)up;
- (void)down;
- (void)left;
- (void)right;
- (void)Key;
Controller代码
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [self.TextField.text integerValue]*[self.TextField.text integerValue];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
UIImageView *image = (UIImageView *)[cell viewWithTag:1];
NSString *str = [NSString stringWithFormat:@"%@", _puz.playArr[indexPath.row]];
image.image = [UIImage imageNamed:str];
return cell;
}
- (IBAction)TextDidEndOnExit:(id)sender
{
self.puz = [[puzzle alloc] initWithSerie:[self.TextField.text integerValue]];
[self.CollectionView reloadData];
}
- (IBAction)UpButton:(id)sender
{
[self.puz up];
[self.CollectionView reloadData];
}
- (IBAction)DownButton:(id)sender
{
[self.puz down];
if ([_puz isWin]) {
alert(@"恭喜你通关了!", @"ok")
}
[self.CollectionView reloadData];
}
- (IBAction)LeftButton:(id)sender
{
[self.puz left];
[self.CollectionView reloadData];
}
- (IBAction)RightButton:(id)sender
{
[self.puz right];
if ([_puz isWin]) {
alert(@"恭喜你通关了!", @"ok")
}
[self.CollectionView reloadData];
}
- (IBAction)KeyButton:(id)sender
{
[self.puz Key];
[self.CollectionView reloadData];
if ([_puz isWin]) {
alert(@"恭喜你通关了!", @"ok")
}
}