CoreGraphic框架解析 (十一)—— 一个简单小游戏 (三)

版本记录

版本号 时间
V1.0 2019.02.01 星期五

前言

quartz是一个通用的术语,用于描述在iOSMAC OS X 中整个媒体层用到的多种技术 包括图形、动画、音频、适配。Quart 2D 是一组二维绘图和渲染APICore Graphic会使用到这组APIQuartz Core专指Core Animation用到的动画相关的库、API和类。CoreGraphicsUIKit下的主要绘图系统,频繁的用于绘制自定义视图。Core Graphics是高度集成于UIView和其他UIKit部分的。Core Graphics数据结构和函数可以通过前缀CG来识别。在app中很多时候绘图等操作我们要利用CoreGraphic框架,它能绘制字符串、图形、渐变色等等,是一个很强大的工具。感兴趣的可以看我另外几篇。
1. CoreGraphic框架解析(一)—— 基本概览
2. CoreGraphic框架解析(二)—— 基本使用
3. CoreGraphic框架解析(三)—— 类波浪线的实现
4. CoreGraphic框架解析(四)—— 基本架构补充
5. CoreGraphic框架解析 (五)—— 基于CoreGraphic的一个简单绘制示例 (一)
6. CoreGraphic框架解析 (六)—— 基于CoreGraphic的一个简单绘制示例 (二)
7. CoreGraphic框架解析 (七)—— 基于CoreGraphic的一个简单绘制示例 (三)
8. CoreGraphic框架解析 (八)—— 基于CoreGraphic的一个简单绘制示例 (四)
9. CoreGraphic框架解析 (九)—— 一个简单小游戏 (一)
10. CoreGraphic框架解析 (十)—— 一个简单小游戏 (二)

源码

1. Swift

首先看下工程组织结构

下面看下sb中的内容

下面就是源码了

1. ResultViewController.swift
import UIKit

class ResultViewController: UIViewController {
  // MARK: - Outlets
  @IBOutlet weak var scoreLabel: UILabel!

  // MARK: - Properties
  var score: Int?
  
  // MARK: - View Life Cycle
  override func viewDidLoad() {
    super.viewDidLoad()
    
    if let score = score {
      scoreLabel.text = "Your final score: \(score)"
    }
  }

  // MARK: - Actions
  @IBAction func playAgainPressed(_ sender: Any) {
    presentingViewController?.dismiss(animated: true, completion: nil)
  }
}
2. PatternView.swift
import UIKit

class PatternView: UIView {
  // MARK: - Structures
  public struct Constants {
    static let patternSize: CGFloat = 30.0
    static let patternRepeatCount = 2
  }
  
  // MARK: - Constants
  enum PatternDirection: CaseIterable {
    case left
    case top
    case right
    case bottom
  }
  
  // MARK: - Properties
  var fillColor: [CGFloat] = [1.0, 0.0, 0.0, 1.0]
  var direction: PatternDirection = .top
  
  // Callback that draws a single pattern, a triangle
  let drawTriangle: CGPatternDrawPatternCallback = { _, context in
    let trianglePath = UIBezierPath(triangleIn:
      CGRect(x: 0, y: 0, width: Constants.patternSize, height: Constants.patternSize))
    context.addPath(trianglePath.cgPath)
    context.fillPath()
  }
  
  // MARK: - Initialization
  init(fillColor: [CGFloat], direction: PatternDirection = .top) {
    self.fillColor = fillColor
    self.direction = direction
    super.init(frame: CGRect.zero)
  }
  
  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
  }
  
  // MARK: - Drawing
  override func draw(_ rect: CGRect) {
    let context = UIGraphicsGetCurrentContext()!
    
    // Background fill
    UIColor.white.setFill()
    context.fill(rect)
    
    // Set up color space
    let baseSpace = CGColorSpaceCreateDeviceRGB()
    let patternSpace = CGColorSpace(patternBaseSpace: baseSpace)!
    context.setFillColorSpace(patternSpace)
    
    // Pattern that draws the triangle
    var callbacks = CGPatternCallbacks(
      version: 0, drawPattern: drawTriangle, releaseInfo: nil)
    
    // Set up the pattern dimensions
    let patternStepX: CGFloat = rect.width / CGFloat(Constants.patternRepeatCount)
    let patternStepY: CGFloat = rect.height / CGFloat(Constants.patternRepeatCount)
    let patternOffsetX: CGFloat = (patternStepX - Constants.patternSize) / 2.0
    let patternOffsetY: CGFloat = (patternStepY - Constants.patternSize) / 2.0
    
    // Set up the transformation matrix based on the pattern direction
    var transform: CGAffineTransform
    switch direction {
    case .top:
      transform = .identity
    case .right:
      transform = CGAffineTransform(rotationAngle: CGFloat(0.5 * .pi))
    case .bottom:
      transform = CGAffineTransform(rotationAngle: CGFloat(1.0 * .pi))
    case .left:
      transform = CGAffineTransform(rotationAngle: CGFloat(1.5 * .pi))
    }
    // Add an offset (margin) so the patterns line up nicely with each other
    transform = transform.translatedBy(x: patternOffsetX, y: patternOffsetY)
    
    // Create the pattern
    let pattern = CGPattern(
      info: nil,
      bounds: CGRect(x: 0, y: 0, width: Constants.patternSize, height: Constants.patternSize),
      matrix: transform,
      xStep: patternStepX,
      yStep: patternStepY,
      tiling: .constantSpacing,
      isColored: false,
      callbacks: &callbacks)
    // Set the  pattern
    context.setFillPattern(pattern!, colorComponents: fillColor)
    // Paint the rectangle with the pattern
    context.fill(rect)
  }
}

// MARK: - UIBezierPath extension
extension UIBezierPath {
  convenience init(triangleIn rect: CGRect) {
    self.init()
    // Draw out the triangle path
    let topOfTriangle = CGPoint(x: rect.width / 2, y: 0)
    let bottomLeftOfTriangle = CGPoint(x: 0, y: rect.height)
    let bottomRightOfTriangle = CGPoint(x: rect.width, y: rect.height)
    self.move(to: topOfTriangle)
    self.addLine(to: bottomLeftOfTriangle)
    self.addLine(to: bottomRightOfTriangle)
    self.close()
  }
}
3. Game.swift
import UIKit

class Game {
  // MARK: - Properties
  let maxAttemptsAllowed = 5
  let colorSelections = [UIColor.blue, UIColor.red, UIColor.magenta]
  let totalPatternCount: Int
  
  var score: Int
  var attempt: Int
  var answers: [PatternView.PatternDirection]
  
  private var majorityPatternCount: Int {
    return totalPatternCount / 2 + 1
  }
  
  // MARK: - Object Lifecycle
  init(patternCount count: Int) {
    totalPatternCount = count
    score = 0
    attempt = 0
    answers = []
  }
  
  // MARK: - Gameplay
  func play(_ guess: PatternView.PatternDirection) -> (correct: Bool, score: Int)? {
    if done() {
      return nil
    }
    if guess == answers[attempt] {
      score = score + 1
      attempt = attempt + 1
      return (true, score)
    } else {
      attempt = attempt + 1
      return (false, score)
    }
  }
  
  func setupNextPlay() -> (directions: [PatternView.PatternDirection], colors: [UIColor]) {
    var directions: [PatternView.PatternDirection] = []
    var colors: [UIColor] = []
    
    // Get a list of directions that don't belong to the correct answer
    let wrongDirections = PatternView.PatternDirection.allCases.filter{
      $0 != answers[attempt]
    }
    // Get a random number of correct answers to fill, to maintain the majority
    let numberOfCorrectPatterns = Int.random(in: majorityPatternCount ..< totalPatternCount)
    
    // Fill out the return info
    for index in 0..<totalPatternCount {
      // Front load with the correct answer
      if index < numberOfCorrectPatterns {
        directions.append(answers[attempt])
      } else {
        // Next, randomly assign wrong answers
        directions.append(wrongDirections.randomElement()!)
      }
      // Pick a random color for the pattern
      colors.append(colorSelections.randomElement()!)
    }
    // Randomly reorder the directions
    directions.shuffle()
    
    return (directions, colors)
  }
  
  func done() -> Bool {
    return attempt >= maxAttemptsAllowed
  }
  
  func reset() {
    score = 0
    attempt = 0
    answers.removeAll()
    
    generatePlays()
  }
}

// MARK: - Private methods
private extension Game {
  func generatePlays() {
    // Pick the random direction that will be the dominant one
    let allPatternDirections = PatternView.PatternDirection.allCases
    answers = (0..<maxAttemptsAllowed).map{ _ in
      allPatternDirections.randomElement()!
    }
  }
}
4. GameViewController.swift
import UIKit

class GameViewController: UIViewController {
  // MARK: - Outlets
  @IBOutlet weak var scoreLabel: UILabel!
  
  @IBOutlet weak var item1PatternView: PatternView!
  @IBOutlet weak var item2PatternView: PatternView!
  @IBOutlet weak var item3PatternView: PatternView!
  @IBOutlet weak var item4PatternView: PatternView!
  
  @IBOutlet weak var leftButton: UIButton!
  @IBOutlet weak var topButton: UIButton!
  @IBOutlet weak var bottomButton: UIButton!
  @IBOutlet weak var rightButton: UIButton!
  
  @IBOutlet weak var choiceFeedbackLabel: UILabel!
  
  // MARK: - Properties
  let numberOfPatterns = 4
  var game: Game?
  var score: Int? {
    didSet {
      if let score = score, let game = game {
        scoreLabel.text = "\(score) / \(game.maxAttemptsAllowed)"
      }
    }
  }
  
  // MARK: - View Lifecycle
  override func viewDidLoad() {
    super.viewDidLoad()
    game = Game(patternCount: numberOfPatterns)
  }
  
  override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    game?.reset()
    score = game?.score
  }
  
  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    showNextPlay()
  }
  
  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "resultSegue" {
      if let destinationViewController = segue.destination as? ResultViewController {
        destinationViewController.score = score
      }
    }
  }
  
  // MARK: - Actions
  @IBAction func choiceButtonPressed(_ sender: UIButton) {
    switch sender {
    case leftButton:
      play(.left)
    case topButton:
      play(.top)
    case bottomButton:
      play(.bottom)
    case rightButton:
      play(.right)
    default:
      play(.left)
    }
  }
}

// MARK: - Private methods
private extension GameViewController {
  func showNextPlay() {
    guard let game = game else { return }
    // Check if the game is still in progress
    if !game.done() {
      // Get the next set of directions and colors for the pattern views
      let (directions, colors) = game.setupNextPlay()
      // Update the pattern views
      setupPatternView(item1PatternView, towards: directions[0], havingColor: colors[0])
      setupPatternView(item2PatternView, towards: directions[1], havingColor: colors[1])
      setupPatternView(item3PatternView, towards: directions[2], havingColor: colors[2])
      setupPatternView(item4PatternView, towards: directions[3], havingColor: colors[3])
      // Re-enable the buttons and hide the answer feedback
      controlsEnabled(true)
    }
  }
  
  func controlsEnabled(_ on: Bool) {
    // Enable or disable the buttons
    leftButton.isEnabled = on
    topButton.isEnabled = on
    bottomButton.isEnabled = on
    rightButton.isEnabled = on
    // Show or hide the feedback on the answer
    choiceFeedbackLabel.isHidden = on
  }
  
  // Sets up the pattern view given a diretion and color
  func setupPatternView(
    _ patternView: PatternView,
    towards: PatternView.PatternDirection,
    havingColor color: UIColor
  ) {
    patternView.direction = towards
    patternView.fillColor = color.rgba
    patternView.setNeedsDisplay()
  }
  
  // Displays the results of the choice
  func displayResults(_ correct: Bool) {
    if correct {
      print("You answered correctly!")
      choiceFeedbackLabel.text = "\u{2713}" // checkmark
      choiceFeedbackLabel.textColor = .green
    } else {
      print("That one got you.")
      choiceFeedbackLabel.text = "\u{2718}" // wrong (X)
      choiceFeedbackLabel.textColor = .red
    }
    // Visual indicator of correctness
    UIView.animate(withDuration: 0.5, animations: {
      self.choiceFeedbackLabel.transform = CGAffineTransform(scaleX: 1.8, y: 1.8)
    }, completion: { _ in
      UIView.animate(withDuration: 0.5) {
        self.choiceFeedbackLabel.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
      }
    })
  }
  
  // Processes the play and displays the result
  func play(_ selection: PatternView.PatternDirection) {
    // Temporarily disable the buttons and make the feedback label visible
    controlsEnabled(false)
    // Check if the answer is correct
    if let result = game?.play(selection) {
      // Update the score
      score = result.score
      // Show whether the answer is correct or not
      displayResults(result.correct)
    }
    // Wait a little before showing the next play or transition to the
    // end game view
    DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(2000)) {
      if (self.game?.done())! {
        self.performSegue(withIdentifier: "resultSegue", sender: nil)
      } else {
        self.showNextPlay()
      }
    }
  }
}

// MARK: - UIColor extension
extension UIColor {
  // Returns an array that splits out the RGB and Alpha values
  var rgba: [CGFloat] {
    var red: CGFloat = 0
    var green: CGFloat = 0
    var blue: CGFloat = 0
    var alpha: CGFloat = 0
    getRed(&red, green: &green, blue: &blue, alpha: &alpha)
    return [red, green, blue, alpha]
  }
}

下面就是实现效果

后记

本篇主要讲述了一个简单小游戏,感兴趣的给个赞或者关注~~~

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,386评论 6 479
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,939评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,851评论 0 341
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,953评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,971评论 5 369
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,784评论 1 283
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,126评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,765评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,148评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,744评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,858评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,479评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,080评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,053评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,278评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,245评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,590评论 2 343

推荐阅读更多精彩内容