PuzzleGame
swift拼圖
源碼鏈接:https://github.com/HelloYeah/PuzzleGame
最近在自學swift,工作一直用OC,一接觸swift,語法上還是有很大的差異。用起來相當不適應。在百度大神的助力下艱辛的把這個拼圖demo寫出來。
歡迎各路大神斧正。歡迎各位新學swift的一起交流。
效果圖如下
2.gif
思路解析
每張可移動的紙片設(shè)計為Puzzle類。 Puzzle 有行號,列號,圖片三個屬性 和 移動方法 func move(direction : Direction)
import UIKit
enum Direction {
case DirectionUp
case DirectionDown
case DirectionLeft
case DirectionRight
}
class Puzzle: NSObject {
var col : NSInteger!
var row : NSInteger!
private(set) var image : UIImage!
init(image: UIImage, withCol col: NSInteger, withRow row: NSInteger){
super.init()
self.col = col
self.row = row
self.image = image
}
func move(direction : Direction) {
switch direction {
case .DirectionUp:
row = row - 1
case .DirectionDown:
row = row + 1
case .DirectionLeft:
col = col - 1
case .DirectionRight:
col = col + 1
}
}
}
PuzzleView 用于展示Puzzle的視圖。每個PuzzleView 擁有一個puzzle屬性。
import UIKit
class PuzzleView: UIImageView {
var puzzle : Puzzle?{
didSet{
self.image = puzzle?.image
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.borderWidth = 1.0/UIScreen.main.scale
self.layer.borderColor = UIColor.lightGray.cgColor
self.isUserInteractionEnabled = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
控制器中添加并布局好9個PuzzleView,每個PuzzleView添加點擊手勢。
emptyPuzzle空白的PuzzleView。每次移動時,通過這個PuzzleView 和點擊的PuzzleView對比位置,相鄰則可以移動。否則不做任何處理
//emptyPuzzle空白的PuzzleView。每次移動時,通過這個PuzzleView 和點擊的PuzzleView對比位置,相鄰則可以移動。否則不做任何處理
let emptyPuzzle : Puzzle = Puzzle.init(image: UIImage.init(), withCol: 2, withRow: 2)
func click(tap: UITapGestureRecognizer) {
let puzzleView = tap.view as! PuzzleView
let puzzle = puzzleView.puzzle!
let col = puzzle.col
let row = puzzle.row
if col == emptyPuzzle.col {
if row! - emptyPuzzle.row == 1 {
puzzle.move(direction: .DirectionUp)
puzzleView.frame.origin.y -= height
emptyPuzzle.move(direction: .DirectionDown)
}
if row! - emptyPuzzle.row == -1 {
puzzle.move(direction: .DirectionDown)
puzzleView.frame.origin.y += height
emptyPuzzle.move(direction: .DirectionUp)
}
}
if row == emptyPuzzle.row {
if col! - emptyPuzzle.col == 1 {
puzzle.move(direction: .DirectionLeft)
puzzleView.frame.origin.x -= width
emptyPuzzle.move(direction: .DirectionRight)
}
if col! - emptyPuzzle.col == -1 {
puzzle.move(direction: .DirectionRight)
puzzleView.frame.origin.x += width
emptyPuzzle.move(direction: .DirectionLeft)
}
}
}
總結(jié):有其他好的思路大家有更好的,可以分享一下。