因为公司项目需要,最近在学习IOS开发,为了巩固我的学习,我想着能不能把以前用C# 开发的拼图游戏移植到 Iphone 上呢,然后我就开始了这一移植的历程,因为这是第二次做这个游戏了,所以想的也就比较深入,对以前的算法进行了优化,借助系统提供的API又节省了不少代码。个人感觉这个游戏还是挺成功的。

界面设计:


开始之后:

算法:

自定义一个控件,有两个属性 ImageTag 和ImageIndex,ImageTag用来存储控件的位置,ImageIndex 用来存储图片的序号,tag 的取值范围是0 - 15

一张图片分割成4 *4 =16 张小图,从 0 开始标号,初始的时候,tag 和index相等的,

当向下滑动时,它与它的ImageTag +4的图片互换,

当向上的时间 ,取p_w_picpathTag-4,

当向左的时候,取ImageTag-1,

当向右的时候,取p_w_picpathTag+1,


改变图片后index也跟着改变,tag不变,用 tag==index来判断图片是否复位,当所有的图片都复位了,拼图也就完成了



我的想法是能不能利用系统提供的手势来移动UIImageView 控件呢,然后我就写了一个测试程序,发现手势操作只能控制View的移动,不能移动UIImageView,

所以要改变一下思路,把一个UIImageView控件加到一个View中,做成一个自定义控件,问题解决:

importFoundationimportUIKitclassPImageView:UIView{//init(p_w_picpath:UIImage!)//{////super.init(p_w_picpath:p_w_picpath)//}varparentView:ViewController!varp_w_picpathView:UIImageView!init(frame:CGRect){super.init(frame:frame)vartemp=frametemp.origin=CGPointMake(0,0)p_w_picpathView=UIImageView(frame:temp)self.addSubview(p_w_picpathView)varrecognizer1=UISwipeGestureRecognizer()recognizer1.addTarget(self,action:"handleSwipeView:")recognizer1.direction=UISwipeGestureRecognizerDirection.Rightvarrecognizer2=UISwipeGestureRecognizer()recognizer2.addTarget(self,action:"handleSwipeView:")recognizer2.direction=UISwipeGestureRecognizerDirection.Leftvarrecognizer3=UISwipeGestureRecognizer()recognizer3.addTarget(self,action:"handleSwipeView:")recognizer3.direction=UISwipeGestureRecognizerDirection.Upvarrecognizer4=UISwipeGestureRecognizer()recognizer4.addTarget(self,action:"handleSwipeView:")recognizer4.direction=UISwipeGestureRecognizerDirection.Downself.addGestureRecognizer(recognizer1)self.addGestureRecognizer(recognizer2)self.addGestureRecognizer(recognizer3)self.addGestureRecognizer(recognizer4)}funchandleSwipeView(recognizer:UISwipeGestureRecognizer!){vardir:String!ifrecognizer.direction.value==UISwipeGestureRecognizerDirection.Down.value{dir="Down"NSLog("moveDown")}ifrecognizer.direction.value==UISwipeGestureRecognizerDirection.Up.value{dir="Up"NSLog("moveUp")}ifrecognizer.direction.value==UISwipeGestureRecognizerDirection.Left.value{dir="Left"NSLog("moveLeft")}ifrecognizer.direction.value==UISwipeGestureRecognizerDirection.Right.value{dir="Right"NSLog("moveRight")}//NSLog("tag:%d",self.p_w_picpathTag)parentView.moveImages(self,directionStr:dir)}funcinitWithTagAndIndex(myTag:Int!,myIndex:Int!){self.p_w_picpathIndex=myIndexself.p_w_picpathTag=myTag}funccheckTagAndIndexValueIsSame()->Bool{returnself.p_w_picpathIndex==self.p_w_picpathTag}varp_w_picpathTag:Int!varp_w_picpathIndex:Int!}

这个是自定义View的代码,初始化的时候设置View的iamgeIndex和 p_w_picpathTag,设置图片,注册系统手势操作

调用它的checkTagAndIndexValueIsSame() 方法来检测图片是否复位.


我们再看看主界面代码:

importUIKitclassViewController:UIViewController{@IBOutletvarv_allImageViews:UIViewvarscreenWidth:CGFloat!varscreenHeight:CGFloat!vardicImages:NSMutableDictionary!vardicIndexValues:NSMutableDictionary!varLocationX:Int=0varlocationY:Int=0overridefuncviewDidLoad(){super.viewDidLoad()//Doanyadditionalsetupafterloadingtheview,typicallyfromanib.//varp_w_picpathView:UIImageView//varp_w_picpath:UIImagevarmyImage:UIImageself.screenWidth=self.view.frame.size.widthself.screenHeight=self.view.frame.size.heightvarcolWidth=(self.screenWidth-24)/4varrowHeight=(self.screenHeight-184)/4myImage=UIImage(named:"7.jpg")dicImages=NSMutableDictionary()varp_w_picpathW=myImage.size.width/4varp_w_picpathH=myImage.size.height/4varnum=0while(num<16){varrow=Float(num/4)varcol=Float(num%4)NSLog("row:%.2fcol:%.2f\r\n",row,col)varrect=CGRectMake(p_w_picpathW*col,p_w_picpathH*row,p_w_picpathW,p_w_picpathH)vartem=CGRectMake(10+colWidth*col+col,40+rowHeight*row+row,colWidth,rowHeight)varsv=PImageView(frame:tem)//sv.frame.origin=CGPointMake(10+colWidth*col+col,40+rowHeight*row+row)//sv.frame.size=CGSizeMake(colWidth,rowHeight)sv.backgroundColor=UIColor.lightGrayColor()//varfrm=CGRect()//varp_w_picpathView=PImageView(frame:frm)//p_w_picpathView.frame.origin=CGPointMake(0,0)//p_w_picpathView.frame.size=CGSizeMake(colWidth,rowHeight)//p_w_picpathView.backgroundColor=UIColor.redColor()sv.initWithTagAndIndex(num,myIndex:num)varp_w_picpath=getImage(myImage,rect:rect)if(num==0){sv.p_w_picpathView.p_w_picpath=p_w_picpath}else{//vardata=UIImagePNGRepresentation(p_w_picpath)dicImages.setObject(p_w_picpath,forKey:String(num))sv.p_w_picpathView.p_w_picpath=p_w_picpath}sv.parentView=selfself.v_allImageViews.addSubview(sv)//self.view.addSubview(p_w_picpathView)num++}NSLog("diccount:%d",dicImages.count)}overridefuncdidReceiveMemoryWarning(){super.didReceiveMemoryWarning()//Disposeofanyresourcesthatcanberecreated.}funcgetImage(img:UIImage,rect:CGRect)->UIImage{varim:UIImagevarp_w_picpathPartRef:CGImageRefvarp_w_picpathRef:CGImageRefp_w_picpathRef=img.CGImagep_w_picpathPartRef=CGImageCreateWithImageInRect(p_w_picpathRef,rect)im=UIImage(CGImage:p_w_picpathPartRef)//CGImageRelease(p_w_picpathPartRef)returnim}@IBOutletvarbtnStart:UIButton//开始游戏@IBActionfuncstart(sender:AnyObject){varvFrist=self.v_allImageViews.subviews[0]asPImageViewvFrist.p_w_picpathView.p_w_picpath=nildicIndexValues=NSMutableDictionary()varnum=1dicIndexValues.setObject(0,forKey:0)vararr:NSArray=["0"]while(num<self.v_allImageViews.subviews.count){varmyindex=arc4random()%15+1;//if(!dicIndexValues.allValues.(String(myindex)))//varobj=arr.indexOfObject(String(myindex))if(!arr.containsObject(String(myindex))){arr=arr.arrayByAddingObject(String(myindex))dicIndexValues.setObject(String(myindex),forKey:num)NSLog("key:%dvalue:%@\r\n",num,String(myindex))//vardata=dicImages.objectForKey(String(myindex))varv_img=self.v_allImageViews.subviews[num]asPImageViewv_img.p_w_picpathView.p_w_picpath=dicImages.objectForKey(String(myindex))asUIImagev_img.p_w_picpathIndex=Int(myindex)num++//NSLog("tag:%dindex:%d",v_img.p_w_picpathTag,v_img.p_w_picpathIndex)}}}//动画切换图片(没有加入动画,只是简单的移动)funcmoveImages(myImageView:PImageView,directionStr:String!){varmyTag=myImageView.p_w_picpathTagletanotherCharacter:String=directionStrvarnum=0switchanotherCharacter{case"Up":num=-4NSLog("up")case"Down":num=4NSLog("Down")case"Left":num=-1case"Right":num=1default:NSLog("default")}//边界检查if(myTag+num)>=0&&(myTag+num)<=15{varv_img=self.v_allImageViews.subviews[myTag+num]asPImageView//判断目标位置是否为空ifv_img.p_w_picpathIndex!=0{return}vartempImage=myImageView.p_w_picpathView.p_w_picpath//dicImages.objectForKey(String(myImageView.p_w_picpathIndex))asUIImagev_img.p_w_picpathView.p_w_picpath=tempImagev_img.p_w_picpathIndex=myImageView.p_w_picpathIndexmyImageView.p_w_picpathIndex=0myImageView.p_w_picpathView.p_w_picpath=nil}//up-4>=0//down+4<=15//left-1>=0//right+1<=15//检测是否完成varindexValue=0varisComplate:Bool=falsewhile(indexValue<self.v_allImageViews.subviews.count){vartempView=self.v_allImageViews.subviews[myTag+num]asPImageViewif!tempView.checkTagAndIndexValueIsSame(){return}indexValue++}//弹出消息,完成拼图NSLog("p_w_picpathTag:%d,direction:%@",myImageView.p_w_picpathTag,directionStr)}}

每移动一步就检测一次.当遇到第一个没复位的就反回,如果所有都 复位了则游戏完成了.


代码请看附件


附件:http://down.51cto.com/data/2365039